body:
I'm not sure what is wrong with my code, but whenever I call `addNewLine`, the `linesInserted` variable is not updating correctly. When I print the value of `linesInserted` inside of the `addNewLine` method, it shows as incrementing, but when I print the value inside of the `draw` method, it shows that it is 0.

I have tried different increment operators (`linesInserted += 1` and `linesInserted = linesInserted + 1`). Oddly enough, when I do `linesInserted = 99` instead of `linesInserted++`, it sets the value correctly. I'm wondering if I am possibly messing up a reference somewhere?

```
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1331.h>
#include <SPI.h>

class Character {
  public:
    char** lines; // using char for 8 bit integer
    int sizeOfLines;
    char symbol;
    Adafruit_SSD1331* display;
    int width;
    draw(int x, int y, int color);
    addNewLine(char startX, char startY, char endX, char endY);
    int linesInserted = 0;
};

Character::draw(int x, int y, int color) {
  if (linesInserted < sizeOfLines) {
    display->setCursor(0, 39);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "SYMBOL %c\nWASTED MEMORY", symbol);
    Serial.println(symbol);
    Serial.print(linesInserted);
    Serial.print(" ");
    Serial.println(sizeOfLines);
    display->print(buf);
  }
  for (int i = 0; i < sizeOfLines; i++) {
    char* line = lines[i];
    display->drawLine(line[0] + x, line[1] + y, line[2] + x, line[3] + y, color);
  }
};

Character::addNewLine(char startX, char startY, char endX, char endY)  {
  linesInserted++;
  if (linesInserted > sizeOfLines) {
    display->setCursor(0, 15);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "ERROR\nSYMBOL %c\nTOO MANY LINES", symbol);
    display->print(buf);
  } else {
    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
  }
};
```

EDIT: Git repo to the project is added - https://github.com/Pyrodron/charger-destination-board

title: Public variable in class not incrementing

Answers: 2

body:
It would be good to see how this is used rather than just having a class with no context.
But I'd start by removing unnecessary parts, like the display pointer, and you could always use a simple program, like ideone.com to compile quickly and check for errors.

As I read through it I see 2 flaws with memory management.
This block is using the size of a char pointer instead of a character. I don't understand what you want this code to do.

    (char**) malloc(sizeof(char*) * Char.sizeOfLines);
Try something more like:

    (char**) malloc(sizeof(char) * <numberOfCharsPerLine> * Char.sizeOfLines);

But then even though you're allocating memory for a whole block of lines, then each time you add a new one, you're allocating memory for a new line.

    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

Instead try something like:

    lines[linesInserted - 1][0] = startX;
    lines[linesInserted - 1][1] = startY;
    ...

body:
It's difficult to pin down the exact details as to why the problem it's manifesting exactly the way it is. But, in short, it's fair to say you're running out of memory.

First, just a note:  The code I'm testing with (because it compiles) is the code out of your github repo, which used a `char` type variable for `linesInserted` and had a commented-out `println(linesInserted);`, so it kind of seems like at one point you'd been trying to print the count as character, specifically non-printable control characters.  So that might may have been confusing you.  I uncommented it and added a `, DEC)` parameter to it (rather than casting) to coerce println into treating it as an int.

I tested your code without the display library in a PC environment to allow me to run valgrind on it.  It didn't find anything; I wasn't necessarily expecting it to.  But, I did crudely instrument your code in this enviroment to see that you're calling `malloc()`/`new` 124 times, for a total of 500 bytes, but importantly this does not include the structure heap overhead, which is significant because you're `new`-ing tiny four-character chunks.

Then I ran your code as compiled for an AVR.  Because I don't have your display, and wanted to match your environment as closely as possible, I left the display code in but NOPed out a few function calls that would have screwed up my test rig.

The primary finding is that you're dangerously close to "running out" of memory:

000005e0 | 01 00 02 04  00 01 00 02 - 00 04 00 03  01 03 05 04 | ........ ........
000005f0 | 00 01 03 02  03 04 00 01 - 06 02 06 04  00 00 00 00 | ........ ........
00000600 | 00 04 00 02  00 02 00 04 - 00 01 01 01  01 04 00 00 | ........ ........
00000610 | 02 00 02 04  00 02 02 02 - 02 04 00 01  03 01 03 04 | ........ ........
00000620 | 00 00 04 00  04 04 00 02 - 04 02 04 04  00 01 05 01 | ........ ........
00000630 | 05 04 00 00  06 00 06 04 - 00 02 06 02  06 00 00 00 | ........ ........
                                                      ^^
                                              [__brkval]

                          [SP]
                           VV
000006b0 | 00 00 00 00  00 00 b7 09 - 03 01 01 06  02 a5 02 00 | ........ ........
000006c0 | 00 00 00 01  00 57 05 06 - cc 00 03 8f  0f 01 00 00 | .....W.. ........
000006d0 | 00 01 00 00  03 00 03 00 - 00 00 07 02  a4 00 01 00 | ........ ........
000006e0 | 03 02 a4 00  05 f8 0d 06 - f6 00 03 00  00 08 c3 08 | ........ ........
000006f0 | de 00 01 00  01 80 1a ed - 02 04 00 41  a4 02 04 00 | ........ ...A....

There's 120 byte separation between the edge of the heap and the stack pointer.  The implementation of the `malloc` that I ran this under checks to see whether or the the stack pointer is within `128` (`__malloc_margin`) bytes.  As your code was building in my environment, without the counter-printing in, this managed to not-fail to allocate.  However adding a single additional call to `addNewLine` was enough to cause `malloc()` via `new` to fail.  So you are indeed right on the edge.  And you have **no** checks to see if `malloc` or `new` returning `nullptr`.

You're making one allocation after another without deallocation anything, which is resulting in a fairly simple pattern of the heap edge advancing by the requested size of your allocation plus 2 bytes each time.  So that's about 248 bytes waste in just heap structure.

I'm not sure on the exact cause of your counter being overwritten, assuming that's what's actually happening.  In fact I was having a hard time finding an case where it would overwrite anything in memory with the code as you have it, but here's a good candidate:

```c++
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
```

With generated code looking like:

0x24c6 [addNewLine+244] ldi    r25, 0x00       ; 0
0x24c8 [addNewLine+246] call   0x3830  ;  0x3830 [malloc]
0x24cc [addNewLine+250] movw   r30, r24
0x24ce [addNewLine+252] st     Z, r10
0x24d0 [addNewLine+254] std    Z+1, r11        ; 0x01
0x24d2 [addNewLine+256] std    Z+2, r17        ; 0x02
0x24d4 [addNewLine+258] std    Z+3, r16        ; 0x03

So, if `malloc()` fails, apparently the `new` statement will just assume that it didn't and goes ahead and writes into the memory at 0x0000 (nullptr) anyway, ugh.  I think this is because technically you're calling the normal new that is supposed to throw an exception on failure.  But there are no exceptions with the way avr-g++ is set up for Arduino.  [As it exists in ArduinoCore-avr version 1.8.3][1], the new code just returns what malloc returns and the compiler thinks an exception will be in progress if it fails.  Normally you would call the std::nothrow version of new[] that returns nullptr on failure, as in:
```c++
lines[linesInserted - 1] = new(std::nothrow) char[4]{startX, startY, endX, endY};
// check lines[linesInserted - 1] against nullptr here
```

However, there's no facility to do that in 1.8.3.  The master as of writing [appears to have addressed this][2], but that's not shipping yet.

---

The short answer to this is basically: **Don't do that.** That is:

* Avoid dynamic allocation altogether where possible.

* This was mentioned in the comments, but it's worth repeating, use flash where you can.  Besides getting your character data into `PROGMEM`, you also have some string literals that can be moved into flash by way of `F()`.

* To the extent that you're doing dynamic allocation requests:

  * Check to see that they're actually succeeding

  * Make as few requests as possible.

   * Do them up-front at the beginning of the code.  The "up-front" part you're more or less already doing, so that much is good.

   * It seems if you're going to dynamically allocate under core version 1.8.3 and you're at all in danger of having an allocation failure, it is important that you *not* use new, since doing so may cause it to overwrite memory for the initialization/construction part after the allocation proper has failed.  Alternately, seriously consider modifying your Arduino core's new.cpp file to do something like call `abort()` if `malloc()` returns `nullptr`, at a minimum, if not something more sensible.  Otherwise, this could drive you insane.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/new.cpp#L25
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/6d29250/cores/arduino/new.cpp#L68


body:
I have mosquitto MQTT installed on my VPS server which I can subscribe and publish to it using paho client thorugh websockets. However when I tried to connect to it through Arduino, I get the following error:

    Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
    Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
    Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

I uploaded the following code to arduino:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>

    // Update these with values suitable for your network.

    const char* ssid = "IOT";
    const char* password = "11112222";
    const char* mqtt_server = "burooq.com";

    WiFiClient espClient;
    PubSubClient client(espClient);
    unsigned long lastMsg = 0;
    #define MSG_BUFFER_SIZE (50)
    char msg[MSG_BUFFER_SIZE];
    int value = 0;

    void setup_wifi() {

      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      randomSeed(micros());

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived [");
      Serial.print(topic);
      Serial.print("] ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();

      // Switch on the LED if an 1 was received as first character
      if ((char)payload[0] == '1') {
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is active low on the ESP-01)
      } else {
        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
      }

    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        // Attempt to connect
        if (client.connect(clientId.c_str())) {
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish("test", "hello world");
          // ... and resubscribe
          client.subscribe("test");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

    void setup() {
      pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
      Serial.begin(115200);
      setup_wifi();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);
    }

    void loop() {

      if (!client.connected()) {
        reconnect();
      }
      client.loop();

      unsigned long now = millis();
      if (now - lastMsg > 2000) {
        lastMsg = now;
        ++value;
        snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
        Serial.print("Publish message: ");
        Serial.println(msg);
        client.publish("test", msg);
      }
    }

<!-- end snippet -->

i checked my server mosquitto ports which shows

    mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP 127.0.0.1:1883 (LISTEN)

I checked my conf file and it has

    listener 1883 localhost

so how what's wrong within my code or settings that prevents me from connecting to my server?`

title: I Can't Connect to my MQTT server via arduino

Answers: 1

body:
This is the problem:

> mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP
> ***127.0.0.1***:1883 (LISTEN)

Your MQTT server is listening only on port 127.0.0.1.  That will accept ***local*** incoming connections only but nothing from another IP address.

The IP 127.0.0.1 is the LOCAL ONLY IP address.  You need to reconfigure your MQTT server to listen on either IP 0.0.0.0 or whatever that server's actual IP address is.

Check your mosquitto.conf file and look for the line that begins with "bind_address":

    listener 1883 localhost

change this to:

    listener 1883 0.0.0.0

and restart your MQTT server.


body:
I'm trying to understand this circuit found [here][1].
[![enter image description here][2]][2]

  [1]: https://www.instructables.com/How-to-drive-a-DC-Motor-with-Transistor-Arduino-Tu/
  [2]: https://i.stack.imgur.com/1j0ti.png

I understand that the Arduino cannot directly run a DC motor because it can only supply 40mA of current and also due to the back EMF which can damage it. I can also understand this circuit if they used an external power supply and used the transistor as a switch to drive the DC motor. But, I do not understand this configuration shown in the pic where the power supply is the arduino itself.

title: How can a DC motor (toy) be run with only an Arduino and transistor without an external power source?

Answers: 1

body:
Your confusion lies in *what* can "supply" power.

Your assumptions are all correct *for an IO pin*. However the Arduino has *more* than just IO pins. It has power pins.

These power pins are not controlled in any way by the microcontroller - they are merely connections into the power supply circuit that also powers the microcontroller.

So in that circuit the Arduino's power supply is shared between the Arduino (the MCU) and the motor.

The 5V pin of the Arduino can supply up to 450mA (when powered from USB - 500mA less about 50mA for the MCU) or up to 800mA when supplied with about 6.5V into the barrel jack (any more than that will cause excess heat to be dissipated which will reduce the maximum current the 5V regulator can handle before shutting down).


body:
I've been learning Arduino for a while, and for my next project I'm attempting to build a drone. When I tested the motors that I purchased before, they seemed to work fine using the PWM pins and I saw no need for a motor driver.

However, now, a week later, the PWM pins are much too weak. I've set them to OUTPUT mode and HIGH.

Should the basic digital output pins be able to run fairly small drone motors like mine?

title: Weak Arduino output pins

Answers: 2

body:
The Absolute Maximum is 40 mA per pin, but you shouldn't go even close to that; max. 20 mA per pin is about where you want to be. Total current (all pins) shouldn't exceed 200 mA.

Only you know what current your "fairly small" motors pull, but you may have fried a few IO pins.

Also, you need flyback (or maybe bidirectional TVS) diodes and a few capacitors on your motors to keep noise and inductive kick-back away from your pins. Motor driver modules often have these installed, but your Arduino pins don't. Inductive kick-back can easily kill IO pins also.

body: Time to purchase another Arduino or use the other pins. Before you connect the new one you need to get a method of driving the motors. Keep in mind they are inductive and will reverse polarity and kick back a voltage that will keep rising until adsorbed. If you will be reversing them pick a MOSFET bridge to drive them. If just on/off/PWM pick a Logic rated avalanche rated N-Channel MOSFET with a high enough voltage and current rating. If your Arduino is 3V3 you need to be sure the gate will be on at about 2.5V. Connect all the grounds together and connect the source of the MOSFET to ground as well. Place something in the 25-50 Ohm resistor from the Arduino pin to the Gate of the MOSFET. Then connect the motor to the drain and the appropriate + supply. No diodes need as it has one built into the MOSFET designed for this. If you want the MOSFET off place something like a 10K resistor from the Arduino pin to ground. Remember a Power Supply the Arduino is NOT! While you are waiting on the parts go through several tutorials on the arduino and motors. There are some good ones and some not so good.


body:
```c++
#include <Servo.h>

Servo myservo;
int pos = 0;
int servo_pin = 3;
int led_pin = 4;

void setup() {
  myservo.attach(servo_pin);
  Serial.begin(9600);
  pinMode(led_pin,OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char serial = Serial.read();
    if (serial == '2') {
      servo();
    }
    if (serial == '1') {
      digitalWrite(led_pin,HIGH);
    } else if (serial == '0') {
      digitalWrite(led_pin,LOW);
    }
  }
  delay(100);
}

void servo() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    delay(5);
  }
  delay(5000);  // problem is here
  for (pos = 180; pos >= 0; pos -= 1)
    myservo.write(pos);
  delay(5);
}
```

When I run this code and send '2', the `servo()` functions start, but it includes a delay function.

Now I want to send '2' and then send '1'. When I do this, the first servo starts, but the LED starts **after** the servo function. I want to start this at the same time.

title: How can I execute two functions at the same time?

Answers: 2

body:
Make little task using `millis` function.

    // GLOBAL VARIABLE
    uint32_t taskMillis = 0;

    ....

    // IN LOOP
    if (taskMillis && millis() - taskMillis >= 5000)
    { /* SWITCHES DIRECTION */ }

With that code you can make two tasks(one to switch direction, second to move Servo by X deg).
Here is video about this topic.

https://www.youtube.com/watch?v=v5SpPXMmHJE

I hope this anwser will help you.

body:
The short answer is no. Delay causes your Arduino to stop dead in its tracks, and do NOTHING else until the specified time has passed. (You can still service interrupt service routines, but ignore that.)

The answer is to rewrite your code to use `millis()` instead of delay. You record the current `millis()` value, and compare the new time to `millis()` to see if enough time has passed.

For the most part you should stop using the `delay()` function and forget exists. It will get you into trouble.

Do a Google search on "Arduino blink without delay" and study the project that comes up to learn this approach.


body:
I am trying to toggle on/off between two separate HTTP request.
One submit button to turn it on, and another separate submit button to turn it off.

I expect the device to launch in the off/low 0V position

`digitalWrite(switchPin2, LOW);`

The first submit button would turn the device on/HIGH/sw1, the second submit button would turn it off/LOW/sw2.

But what it is doing is at first nothing when the first/sw1 submit button is pressed but when I press the sw2 submit, I get serial output telling me that sw1 was just pressed. Then if I press sw2 again, it will tell me sw2 was just pressed but will not repeat the cycle until i press sw1 again. Then sw2 becomes functional, just performing the wrong function.

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    ESP8266WebServer server(80);

    const char* ssid = "ssid";
    const char* password =  "pass";
    int switchPin2 = 4;

    //counter variable
    int switch2;

    String inString;

    void webpage() {
      server.send(200,
              "text/html",
              " \
               \

Air conditioner manager
 \n\

Turn air conditioner on for "+String(switch2)+" ms
 \
               <form name='frm1 method='post'> \
                <input type='text' name='sw1' value=8000> \
                <input type='submit' value='Submit'> \
               </form> \

Turn air conditioner off for "+String(switch2)+" ms
 \
               <form name='frm2' method='post'> \
                <input type='text' name='sw2' value=8000> \
                <input type='submit' value='Submit'> \
               </form> \
               \
              ");
    }

    void response() {
      //add additional switch/relay here if adding new plug
      if (server.hasArg("sw1") && (server.arg("sw1").length() > 0)) {
        Serial.print("Switch 1 entered:\t");
        Serial.println(server.arg("sw1"));
        digitalWrite(switchPin2, HIGH);
        Serial.print("\nUnit is on:\n");
        int num = server.arg("sw1").toInt();
        ++switch2;
        server.sendHeader("Location", String("/"), true);
        server.send (302, "text/plain", "");
      } else if (server.hasArg("sw2") && (server.arg("sw2").length() > 0)) {
        Serial.print("Switch 2 entered:\t");
        Serial.println(server.arg("sw2"));
        digitalWrite(switchPin2, LOW);
        Serial.print("\nUnit is off:\n");
        int num = server.arg("sw2").toInt();
        ++switch2;
        server.sendHeader("Location", String("/"), true);
        server.send (302, "text/plain", "");
      } else {
        server.send(400, "text/html", "
HTTP Error 400

Bad request. Please enter a value.
");
      }
    }

    void setup() {
      Serial.begin(115200);
      pinMode(switchPin2, OUTPUT);
      digitalWrite(switchPin2, LOW);
      WiFi.begin(ssid, password);  //Connect to the WiFi network
      while (WiFi.status() != WL_CONNECTED) { // Wait for connection
        delay(500);
        Serial.println("Waiting to connect...");
      }
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP()); // Print the local IP
      // server.on("/body", handleBody); // Associate the handler function to the path
      server.on("/",HTTP_GET, webpage);
      server.on("/",HTTP_POST,response);
      server.begin(); // Start the server
      Serial.println("Server listening");
    }

    void loop() {
      server.handleClient(); //Handling of incoming requests
    }

I get no error, only erratic output.

How do I toggle on/off between 2 submit buttons?

UPDATE: Serial output.

    Waiting to connect...
    IP address: 192.168.1.9
    Server listening
    Switch 1 entered: 8000

    Unit is on:
    Switch 2 entered: 8000

    Unit is off:

title: Peculiar relay behavior from POST

Answers: 0


body:
I'm working in a project where I have to send data from long distances (about 1 km) between 2 Arduinos UNO which are powered by computer's USB ports. The place is a small city with no large buildings. I have bought two transceptors [LORA RA-02 SX1278][1] at 433 MHz with an antenna for this frequency, like this:

[![enter image description here][2]][2]

The results are dissapointing. I can reach 300-350 meters with a stable communication (1 data send every 5 seconds). I was only able to, only one time, receive a data from a 1.4 km distance, but the message was corrupt, like this:

[![enter image description here][3]][3]

I have tried:
- Different programs and libraries (Now, i'm working with [this library][4])
- Frequencies from 410 MHz to 525 MHz, according to the range inscriptions on the module

But the distance is still far away from 1 km for a stable communication. I have seen some people reaching 2-3 km with this module and some documents say that it is possible to reach 10 km.

The question is, what am I doing wrong or what I should change to improve the results?

Any help or related experience is very useful!

  [1]: https://docs.ai-thinker.com/_media/lora/docs/c048ps01a1_ra-02_product_specification_v1.1.pdf
  [2]: https://i.stack.imgur.com/iPLLy.png
  [3]: https://i.stack.imgur.com/HezJV.jpg
  [4]: https://github.com/sandeepmistry/arduino-LoRa/blob/master/examples/LoRaReceiver/LoRaReceiver.ino

title: Real range of long range transceptor LORA RA-02 SX1278 with Arduino UNO

Answers: 0


body:
I am trying to setup L298N motor driver controller with my Arduino. Different online schematics about how to connect them are mostly similar - but they differ in powering the Arduino from the drive controller's 5v pin.

I am connecting 7.5v to the Vin and Gnd to the motor driver controller screw terminal , and I wish the power the Arduino from the 5v screw terminal. Since I am planning to use the 5v screw terminal as output I am choosing to leave the 5v jumper on.

Here are 3 of the schematics I've found online,

 1. Source [Homemade-circuits](https://www.homemade-circuits.com/l298n-dc-motor-driver-module-explained/):
[![enter image description here][2]][2]

This is what I was expecting to see. But from [Arduino Uno Rev3 Faq](https://store.arduino.cc/usa/arduino-uno-rev3),

```
Vin -- The input voltage to the Arduino board when it's using an external power source (as opposed to 5
volts from the USB connection or other regulated power source). You can supply voltage through this pin,
or, if supplying voltage via the power jack, access it through this pin.

5V -- This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power
either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).
Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.
```

*This one looks wrong to me.* I am under the assumption that Vin pin is expecting 7-12V because it's connected to voltage regulator which will cause a 2v drop. Which mean I should not connect 5v from the motor controller to Vin - making this schematic incorrect. Is my analysis correct? [Here](https://arduino.stackexchange.com/a/4460/34157) is an answer that says I can not use the 5v pin to power an Arduino since it an input pin and not an output pin.

 2. Source [teachmemicro](https://www.teachmemicro.com/use-l298n-motor-driver/):
[![enter image description here][3]][3]

*This one looks ok to me* since the 5v source at motor controller is a regulated source and that's what exactly Arduino is expecting on 5v pin based on aforementioned FAQ. Can I implement is safely?

 3. Source [Instructables](https://www.instructables.com/L298N-MOTOR-DRIVER-MODULE/):
[![enter image description here][1]][1]

*I do not know if it's correct or not.* Notice that the 5v screw terminal is not connected to Arduino in any way. Is it setup going to work? I am wondering where the Arduino is getting its power from?

I am wondering which schematic should I follow. I am hesitant to hook up my L298N motor driver and Arduino without without understanding why each schematic is choosing to power the Arduino differently.

  [1]: https://i.stack.imgur.com/P7d7p.png
  [2]: https://i.stack.imgur.com/thgTB.png
  [3]: https://i.stack.imgur.com/3ZNci.png

title: How to power Arduino Uno from L298N motor driver's 5v terminal?

Answers: 3

body:
Clearly, your design (last image) won't work, because as you expected, the Arduino won't have power. It is a feasible design however, if you use it while still developing and you have the USB cable connected. Because then the Arduino will draw the power for itself from there.

Vin expects 7-12V, but allows an unregulated input (which is fine for connecting a battery). You can use the 5V pin to supply power from a regulated output as well. Since (pressumably) the output of the motor driver is regulated, that could work, however I would not advise it and directly connect the battery to the VIn pin.

Connecting the 5V output of the motor driver to the VIn pin *might* work. While this will likely not destroy anything, it may be to low to drive the internal regulator, which might cause the Arduino to run on undervoltage levels. You might see weird behavior in that case (pins not correctly recognizing high from low, incorrect measurements on analog inputs or even software crashes).

body:
![enter image description here](https://i.stack.imgur.com/Cc9Nz.jpg)

I happened to just set up a similar circuit yesterday on a RC car. L298 is powered through a 3S lipo batterie, Uno is powered through the 5v output which also powers a servo. Uno powers a rc receiver. I burnt an Uno trying to power both servo and receiver.

body:
I was facing same problem but I solved it by attaching L298 power pins to icsp power pins

![icsp pins](https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/hex-file-and-icsp-pins-of-arduino/Images/image002.jpg)

Remember the voltage should be constant and there should not be any fluctuation other wise atmega will go in programming mode


body:
I want to generate a 15 kHz pulse with an Arduino using Timer1, but the problem is that if we want a 15000 Hz clock we need to initialize the timer with *1/15000* seconds or *66.66* microseconds, but we can only pass integers without any decimal precision in the `Timer1.initialize(66);` function which generates a frequency of 15155 Hz.

So is it possible by any other means to generate an exact *15000 Hz* or frequencies between *15000 Hz - 15155 Hz*?

```c++
#include <TimerOne.h>

void setup() {
  pinMode(9,OUTPUT);
  Timer1.initialize(66);  // Frequency, 100 µs = 10 kHz
  Timer1.pwm(9,255);
}

void loop() {}
```

title: Is it possible to generate an exact 15 kHz clock pulse using an Arduino?

Answers: 6

body:
Yes, you can. Sort of...

A 66.6 µs delay means one delay of 66 µs and then two delays of 67 µs.
You could keep a close loop that calculates the micros() divided by 66 and modulo by 2 for every iteration. This will give you an alternating 1 and 0. Save the previous value to check this value for a change and digitalWrite HIGH or LOW.

I have no means at the moment to test the code, but in (semi-pseudo) code this would look something like:

```
void loop()
{
  int freq=15000;
  float interval = ((float)1000000/(float)freq)/2;//33.333333
  byte state=0;
  byte previousState=0;
  while (1)
  {
    unsigned long currentMicros=micros();
    previousState=state;
    state = (unsigned long)((float)currentMicros / interval) % 2;
    if (state==1 && previousState==0) digitalWrite(9,HIGH);
    if (state==0 && previousState==1) digitalWrite(9,LOW);
  }
}
```

This method will guarantee that after one second exactly 15000 periods have passed. The timing of the individual periods, however, might vary a little.

body:
Since the timer1 library only accepts whole numbers for the µs parameter you get a error. You could skip using the library and configure the timer directly. Or you could have a look at the [source code of the library](https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L189-L213), and see that you can kind of bypass the limitation it has by only calculating a more accurate value for the `ICR1` register.

Look at `cycles = ((F_CPU/100000 * microseconds) / 20);`. If you were to insert your 66.66666µs into this, instead of 66µs, you'd get `533` instead of `528`.

This value is then used to set the PWM frequency in line 213. So you'd need to overwrite the `ICR1` register with the more accurate value.

Your final code should look like:

```
pinMode(9,OUTPUT);
Timer1.initialize(66);
ICR1 = 533;
Timer1.pwm(9,255);
```

PS you might need to tweak this 533 value to get an even more accurate resulting frequency.

body:
*In answer to a comment from the OP asking for another microcontroller that can do this, and in addition to Majenko's reply comment:*

A SAMD21G running at 48 MHz (as seen on some Arduinos) can make 15 kHz, in several ways.

Note that this assumes that the clock is exactly 48 MHz, and stable, and both assumptions could well be wrong, unfortunately. It helps if the clock is derived from a crystal; not all SAMD21G-based Arduinos do that, if any. This possible lack of clock precision and stability applies to all MCUs.

The SAMD21G does have a fractional PLL, and you can of course adjust the PER register, so some fine-tuning is possible if you have the equipment to measure the actual output frequency.

If you decide to go with one of the SAMD21G-based Arduinos: there is a [PWM library][1] for those (I know it well, as I wrote it) that will let you set a clock divider, a prescaler, and a resolution, which should make it easy enough to arrive at a (nominal) 15 kHz. There's a frequency table under "extras".

  [1]: https://github.com/ocrdu/Arduino_SAMD21_turbo_PWM

body:
You can get pretty close if you program Timer 1 directly (not
through the library), and have it run with the prescaler set to 1.
Ideally, you want the period of the timer in clock cycles to be:

F\_CPU / 15 kHz = 16,000 kHz / 15 kHz ≈ 1066.67 CPU cycles

If you round this to the nearest integer, you get

F\_CPU / 1,067 = 16,000 kHz / 1,067 ≈ 14.9953 kHz

This is about 0.03% too slow, well within the tolerance of the ceramic
resonator clocking the Uno.

Here is my attempt at this. I have tested it.

```c++
constexpr float PWM_FREQUENCY = 15e3;  // 15 kHz
constexpr uint16_t PERIOD = round(F_CPU / PWM_FREQUENCY);

void setup() {
    // Configure Timer 1 for 15 kHz PWM on pin 9 = PB1 = OC1A.
    DDRB  |= _BV(PB1);    // set pin as output
    TCCR1B = 0;           // stop timer
    TCCR1A = _BV(COM1A1)  // non-inverting PWN on OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock @ F_CPU
    ICR1   = PERIOD - 1;  // period
    OCR1A  = PERIOD / 4;  // duty cycle
}

void loop(){}
```

body:
A better way to do the above *average* 15 kHz (or any other frequency) is with a phase accumulator scheme.  There are no IF tests; on each tick of an interrupt, you add a step to an accumulator and output the state of its MSB.  This can give incredible resolution, and is probably the best you can do.  But though the *average* frequency will be dead-on, the jitter can be terrible.  I use this method in my open-source DaqPort sketch
<https://www.daqarta.com/dw_rraa.htm#00ff>, which is used by DaquinOscope
<https://www.daqarta.com/dw_rroo.htm> and Arduino_Oscillators <https://www.daqarta.com/dw_rrss.htm> mini-apps running in Daqarta.  There's also a Jitter_Tbl macro to compute the jitter for arbitrary sample rates and output frequencies.  Although not relevant here, this phase accumulator method can also go to exceptionally *low* frequencies, into the micro-hertz range, and the jitter is extremely small there.

body:
I can get within 5 Hz of 15,000 using a 16 MHz clock on a Nano, Uno or 2560. Here is the code...

    // RTM_TimerCalc 1.20
    // Timer-1 Mode_14_16Bit_Fast_TOP_is_ICR

    TCCR1B = 0x18; // 0001 1000, Disable Timer Clock
    TCCR1A = 0xA2; // 1010 0010

    ICR1 = 1067-1;
    OCR1A = (int) (ICR1 * 0.25);
    OCR1B = (int) (ICR1 * 0.50);
    TCNT1=0x0;

    // UnComment following lines for UNO-NANO Timer-1 Pins
    // pinMode(9, OUTPUT);  // OC1a
    // pinMode(10, OUTPUT); // OC1b

    // UnComment following lines for 2560 Timer-1 Pins
    // pinMode(11, OUTPUT);  // OC1a
    // pinMode(12, OUTPUT);  // OC1b

    TCCR1B |= 1; // Prescale=1, Enable Timer Clock

Here is the Error Results...
ASK:       15,000 Hz
CALC:     14,995.3139643861 Hz
OFFSET:  -4.6860356139 Hz

hth


body:
Kind of a fringe question here, but could not find anything concrete so figured I would throw it to this great community.

I have 2 DS80 flow meters (Hall Effect Sensor type flow meters - nothing special about them except they are bigger for 3" pipes), and they work fine, wired, code, etc and get decent readings and all that so no issues there.

During my bench prototyping, I noticed that sometimes, in spite of no "flow", I would detect "pulses" from the sensor. Because they are sitting on a workbench, with no pipes connected, I assume this is either:

- Random transient voltage, maybe bleed from its neighbors in the wiring or what not
- Maybe the magnet on one fin is parked at the sensor and vibration is causing it to bounce

The second one is what it is, but the first one feels like something I could iron out. The question is, should I have a cap/resistor/something on the data line from the sensor to smooth out readings? Because it is PWM I do not know what to put there that wouldn't interfere with the signal itself (if anything). Absolutely NOT critical, as I said it works fine under load and I do not need hyper-accurate readings. More of a "could I do this better" question.

title: Hall Sensor (Fluid Flow) "Noise"

Answers: 0


body:
I want to detect the exact time signal from an FM radio station. The signal is transmitted in the form of 5 short pulses and one long one. My task is to determine the presence of a pulse in the audio data stream and its duration.
It is understood that the signal is received by the radio receiver and then the audio signal is fed to the atmega microcontroller.
The pulse duration varies in the range of 100 ... 560 ms

How can you control the appearance of these pulses using a microcontroller, and also determine their duration? Below is an example of computer processing. The same is required to be implemented on a microcontroller.

1. I have a reference recorded signal in WAV format.
This recorded signal from the output of the radio receiver contains both the speaker's speech, music, and the **exact time signal**:
[![enter image description here][1]][1]

2. I know the time signal is centered at 1 kHz, so
apply filtering to this signal. The filter has the following frequency response:
[![enter image description here][2]][2]

The signal after the filter looks like:
[![enter image description here][3]][3]

3. It remains to apply the threshold device and duration selection.
However, I do all this in an audio editor to understand the ongoing processes. In fact, I need to implement this on an arduino, so I really hope for your tips, because I don't know how to implement a filter on an arduino for one frequency, and I also don't know how to make a pulse detector and a meter for its parameters.

Below is the result of homodyne, the method suggested in the comments. On the test signal, the algorithm was able to identify the required pulses! It remains to write a sketch where there is a detection threshold and definition of the duration!
I was able to write a condition, when the threshold is exceeded, the LED turns on, and turns off otherwise. But I don't know how to make the definition of duration yet ...[![enter image description here][4]][4]

*Added after a few days:*

I was able to assemble the entire structure, the sketch below does the following:
1. Listens to the audio signal coming to the analog input of the arduino from the radio receiver on the RDA5807M microcircuit, through an amplifier on one transistor, which provides signal amplification and offset to the positive range.

2. Performs homodyne processing: selects only the signal with a frequency of 1 kHz, all other frequencies are suppressed

3. Selects the optimal detection threshold for finding the exact time signal of 1 kHz frequency at the background level.

4. Calculates the duration of each pulse

5. Finds the exact time by the last impulse using the recalculation formula.

Thus, at the moment I get the exact time digit in the serial port monitor.

But the end result I want to get is setting the resulting digit on a seven-segment display. Having looked at the sketches of his work, I found that the values in the loop are constantly processed there, which again slows down the microcontroller, but for me this is unacceptable. As I understand it, you need to write a separate function into which you pass the value of the hour and set this value on the indicator only once an hour. But I don’t know how to implement it. I ask for help!

    / * Last edited on January 25, 2021.
       1 kHz homodyne signal detection

      This program continuously samples analog input A0 and uses a homodyne
      detection circuitry for signal identification at 1 kHz (+/- 24 Hz at -3 dB).

      The A / D converter is set to "free running mode" and takes one sample every 104 µs.
      The samples are multiplied by two generated 1 kHz signals ("local oscillator") in quadrature to each other.
      The products are then low-pass filtered with a time constant of 64 sampling periods (6.656 ms),
      which gives (I, Q) signals with a bandwidth of 24 Hz.
      Finally, the signal strength is calculated as I ^ 2 + Q ^ 2.

      The program is designed for Arduino Uno and will probably work on any AVR based Arduino,
      having an ADC and operating at a frequency of 16 MHz.

      For a detailed explanation, see
      http://arduino.stackexchange.com/a/21175

      Posted by: 2016 Edgar Bonet Orozco.
    * /

    // Here is everything related to the parameters of the RDA5807M receiver:
    #include <Wire.h>

    #define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
    // registers
    #define RDA5807M_REG_CONFIG 0x02
    #define RDA5807M_REG_TUNING 0x03
    #define RDA5807M_REG_VOLUME 0x05
    #define RDA5807M_REG_RSSI 0x0B
    // flags
    #define RDA5807M_FLG_DHIZ 0x8000
    #define RDA5807M_FLG_DMUTE 0x4000
    #define RDA5807M_FLG_BASS 0x1000
    #define RDA5807M_FLG_ENABLE word (0x0001)
    #define RDA5807M_FLG_TUNE word (0x0010)
    // masks
    #define RDA5807M_CHAN_MASK 0xFFC0
    #define RDA5807M_CHAN_SHIFT 6
    #define RDA5807M_VOLUME_MASK word (0x000F)
    #define RDA5807M_VOLUME_SHIFT 0
    #define RDA5807M_RSSI_MASK 0xFE00
    #define RDA5807M_RSSI_SHIFT 9

    uint8_t volume = 7; // 0..15
    uint16_t freq = 938; // 107.3FM
    uint16_t reg02h, reg03h, reg05h, reg0Bh;
    // Receiver end

    unsigned long startTime; // Turn on two timers, this
    unsigned long elapsedTime; // and this one
    int threshold = 300; // Set the maximum noise level
    boolean timing = false; // I do not know...

    #include <util / atomic.h>

    // The analog input used must be between A0 and A5.
    const uint8_t analog_in = 0;

    // The frequency we want to define, in Hz.
    const float SIGNAL_FREQ = 1000.0;

    // Time bits.
    const float SAMPLING_FREQ = F_CPU / (128 * 13.0); // 9.615 kHz
    const long PHASE_INC = round (SIGNAL_FREQ / SAMPLING_FREQ * (1L << 16));
    const int LOG_TAU = 6; // tau = 64 / SAMPLING_FREQ = 6.656 ms

    // Set the ADC to constant conversion mode "free running mode"
    static void configure_adc ()
    {
      ADMUX = _BV (REFS0) // ref = AVCC
               | _BV (ADLAR) // left adjust result
               | analog_in; // input channel
      ADCSRB = 0; // free running mode
      ADCSRA = _BV (ADEN) // enable
               | _BV (ADSC) // start conversion
               | _BV (ADATE) // auto trigger enable
               | _BV (ADIF) // clear interrupt flag
               | _BV (ADIE) // interrupt enable
               | 7; // prescaler = 128
    }

    // Demodulated (I, Q) amplitudes.
    volatile int16_t signal_I, signal_Q;

    // Interrupt handler is called every time the ADC is ready to read.
    ISR (ADC_vect)
    {
      // Read the ADC and convert to a signed number.
      int8_t sample = ADCH - 128;

      // Update the phase of the local oscillator.
      static uint16_t phase;
      phase + = PHASE_INC;

      // Multiply samples by square waves in quadrature.
      int8_t x = sample;
      if (((phase >> 8) + 0x00) & 0x80) x = -1 - x;
      int8_t y = sample;
      if (((phase >> 8) + 0x40) & 0x80) y = -1 - y;

      // First order low pass filter.
      signal_I + = x - (signal_I >> LOG_TAU);
      signal_Q + = y - (signal_Q >> LOG_TAU);
    }

    / * Return the power reading. * /
    static uint16_t get_power_reading ()
    {
      int16_t I, Q;
      ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        I = signal_I;
        Q = signal_Q;
      }
      return sq ((int8_t) (I >> LOG_TAU)) + sq ((int8_t) (Q >> LOG_TAU));
    }

    // *********************************************** ***********************
    void setup ()
    {
      configure_adc ();
      Serial.begin (9600);

      // Receiver start:
      Serial.begin (9600);
      Wire.begin ();
      // Register 02h - enable, settings
      reg02h = RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
      setRegister (RDA5807M_REG_CONFIG, reg02h);

      // And then we decided to further strengthen the bass: (I don't need this, I need to somehow remove it)
      reg02h | = RDA5807M_FLG_BASS;
      setRegister (RDA5807M_REG_CONFIG, reg02h);

      // Register 03h - select radio station
      // After reset in register 03h, the default value is 0
      // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
      reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
      setRegister (RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);
    // Register 05h. Set the volume, do not change the rest of the beats
      reg05h = getRegister (RDA5807M_REG_VOLUME); // Read the current value
      reg05h & = ~ RDA5807M_VOLUME_MASK; // Reset the VOLUME bits
      reg05h | = volume << RDA5807M_VOLUME_SHIFT; // Set a new volume
      setRegister (RDA5807M_REG_VOLUME, reg05h);
      // Receiver end:
    }

    void loop ()
    {
      // Print power readings every 8ms.
      static const uint16_t print_period = 8;
      static uint16_t last_print;
      uint16_t now = millis ();
      if (now - last_print> = print_period) {
        //Serial.println (get_power_reading ()); // Build a graph by which you can determine the optimal threshold
        // If the signal has exceeded the threshold, start timing:
        if (get_power_reading ()> threshold &&! timing)
        {
          startTime = millis ();
          timing = true;
        }
        // If the signal is below the threshold, stop the countdown and display the amount of time passed - the pulse duration:
        if (get_power_reading () <= threshold && timing)
        {
          elapsedTime = millis () - startTime;
          timing = false;
          //Serial.println(elapsedTime);
          if (elapsedTime> = 80 && elapsedTime <= 580)
          {
            int h = floor ((elapsedTime - 100) / 20); // Get the time in hours, but there are 6 pulses, but only the last one is needed.
            //Serial.println(h);
            // "valround" --- Round to the nearest integer,
            // "floor (x)" --- Round down to integer
            if (h> = 1 && h <= 24) // If the time is defined as abnormal, beyond reasonable limits, then simply forget it:
            {
              Serial.println ("Exact time:");
              Serial.print (h);
              Serial.println (": 00");
            }
          }
        }
        last_print + = print_period;
      }
    }

    // Receiver start:
    void setRegister (uint8_t reg, const uint16_t value) {
      Wire.beginTransmission (0x11);
      Wire.write (reg);
      Wire.write (highByte (value));
      Wire.write (lowByte (value));
      Wire.endTransmission (true);
    }

    uint16_t getRegister (uint8_t reg) {
      uint16_t result;
      Wire.beginTransmission (RDA5807M_RANDOM_ACCESS_ADDRESS);
      Wire.write (reg);
      Wire.endTransmission (false);
      Wire.requestFrom (0x11, 2, true);
      result = (uint16_t) Wire.read () << 8;
      result | = Wire.read ();
      return result;
    }
    // receiver end

  [1]: https://i.stack.imgur.com/sBjw3.jpg
  [2]: https://i.stack.imgur.com/Gknqq.png
  [3]: https://i.stack.imgur.com/7FQRh.png
  [4]: https://i.stack.imgur.com/c0G5k.jpg

title: Time signal. Determine the presence of pulses and their duration

Answers: 1

body:
If the voice and music are superimposed on top of the signal you are
looking for, that will make matters quite difficult. The first thing you
have to do is filter out all the unwanted sound. The limit on how
aggressively you can filter is given by the width of the pulses. If you
want to detect 100 ms pulses, your filter width should probably be more
than 10 Hz. The filter you used in your test is way larger than that.

Given the limited processing power of your typical Arduino, it may be
preferable to do all the signal conditioning in the analog domain, prior
to digitizing it on the Arduino. If you really have to do everything in
the Arduino, you will still have to adjust the amplitude and the offset
of the signal in the analog domain so that it fits the range of the ADC.

For implementing a narrow-band filter on the Arduino itself, I generally
recommend to use an [homodyne detection][homodyne] scheme. This can give
you very narrow filters at a minimal processing cost. See this [other
answer][answer] where I discuss the working of the scheme, and provide a
link to an implementation.

If you have something similar to an Uno, you should be able to load that
sketch directly, although you may want to tweak the time constant in
order to make the filter narrower. You can then send it your test
signal, collect back the power readings sent by the sketch through the
serial port, and plot those. This should give you a new test signal for
prototyping the next stages of your processing pipeline. If all goes
well, you would just have to set a threshold for detecting the pulses,
and then have some condition on the length of the detected pulses to
sort out spurious pulses from legit ones.

[homodyne]: https://en.wikipedia.org/wiki/Homodyne_detection
[answer]: https://arduino.stackexchange.com/a/21175/7508

**Edit**: I suggested using a threshold on the detected power for
deciding when there is a pulse and when there is not. However, if the
power signal is noisy, this simple scheme may not be good enough.

One possible way to reduce the noise is to increase the time constant of
the filter by increasing `LOG_TAU`. Do not set it above 8,
otherwise it may overflow some variables. Also note that, the larger the
time constant, the lower the bandwidth, which can be an issue if the
frequencies are not very accurate.

Another option is to low-pass filter the power readings. This can be
done on a sub-sampled signal in order to lower the processing cost.

Finally, for deciding whether there is a pulse or not, it can be useful
to add some hysteresis to the detection, basically simulating a [Schmitt
trigger][]. This is simply accomplished by replacing the detection
threshold with two distinct thresholds: a high one for the “no pulse” →
“pulse” transition, and a lower one for the reverse transition:

```cpp
const uint16_t LOW_THRESHOLD  = ...;
const uint16_t HIGH_THRESHOLD = ...;

// within loop:
static enum { NO_PULSE, PULSE } state = NO_PULSE;
uint16_t power = get_power_reading();
if (state == NO_PULSE && power >= HIGH_THRESHOLD) {
    state = PULSE;
    register_pulse_start();
}
if (state == PULSE && power < LOW_THRESHOLD) {
    state = NO_PULSE;
    register_pulse_end();
}
```

[Schmitt trigger]: https://en.wikipedia.org/wiki/Schmitt_trigger


body:
I recently switched computers and installed Arduino IDE, Added SAMD21 to the boards manager and installed drivers.

My sketch previously ran on my laptop with no problems.  Now when I try to compile for the SAMD21 Mini, I get a 'Serial1' was not declared in this scope error.

If I try to compile it for Mega, there are no problems.

I have tried sample code with Serial1 for SAMD21 and it compiled and uploaded with no problems.

title: "SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope

Answers: 1

body: Ahhhh, I figured it out.  I had to add `#include "Arduino.h"` to the .cpp file.


body:
I have an LCD keypad shield that I'm using to control a Catalex serial MP3 module and I have an int variable that has the volume setting which can go from 1 to 30. I'm trying to send the variable to the module but it's not working. Here's the code for the serial request:

```c++
void SetAttractVolume() {
  SerialString = SerialString2 + AttractVolume;
  delay(20);
  Send_buf[0] = 0x7e; // starting byte
  Send_buf[1] = 0xff; // version
  Send_buf[2] = 0x06; // the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = 0x06; //
  Send_buf[4] = 0x00; // 0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = 0x00;
  Send_buf[6] = 0x12;
  Send_buf[7] = 0xef; //ending byte
  for (uint8_t i=0; i<8; i++) {
    mySerial.write(Send_buf[i]); // send bit to serial mp3
    Serial.print(Send_buf[i], HEX); // send bit to serial monitor in pc
  }
  Serial.println();
}
```
"0x12" is the volume control, you set the 12 to any number from 1 to 30 to change it, I thought I could just put my variable in there, like this:

```c++
void SetAttractVolume() {
  SerialString = SerialString2 + AttractVolume;
  delay(20);
  Send_buf[0] = 0x7e; // starting byte
  Send_buf[1] = 0xff; // version
  Send_buf[2] = 0x06; // the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = 0x06; //
  Send_buf[4] = 0x00; // 0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = 0x00;
  Send_buf[6] = 0xAttractVolume;
  Send_buf[7] = 0xef; //ending byte
  for (uint8_t i=0; i<8; i++) {
    mySerial.write(Send_buf[i]) ;//send bit to serial mp3
    Serial.print(Send_buf[i],HEX);//send bit to serial monitor in pc
  }
  Serial.println();
}
```

This doesn't compile, I know it's not the correct way to do it, but I want to know how to do it right.

Thanks in advance.

title: Sending variable over serial

Answers: 0


body:
I am trying to bring the esp32 example code live. I am able to upload the image error free but when I remove the jumper and then press the reset switch, instead of seeing it logon to my network via serial monitor, I just get this repeating over and over and over again.

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8

    Brownout detector was triggered

    ets Jun  8 2016 00:22:57

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8

    Brownout detector was triggered

    ets Jun  8 2016 00:22:57

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8

    Brownout detector was triggered

    ets Jun  8 2016 00:22:57

    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1216
    ho 0 tail 12 room 4
    load:0x40078000,len:9720
    ho 0 tail 12 room 4
    load:0x40080400,len:6352
    entry 0x400806b8
    ets Jun  8 2016 00:22:57

How do I boot an esp32-cam correctly?

code:

    #include "esp_camera.h"
    #include <WiFi.h>

    //
    // WARNING!!! Make sure that you have either selected ESP32 Wrover Module,
    //            or another board which has PSRAM enabled
    //

    // Select camera model
    //#define CAMERA_MODEL_WROVER_KIT
    //#define CAMERA_MODEL_ESP_EYE
    //#define CAMERA_MODEL_M5STACK_PSRAM
    //#define CAMERA_MODEL_M5STACK_WIDE
    #define CAMERA_MODEL_AI_THINKER

    #include "camera_pins.h"

    const char* ssid = "getAjobFool";
    const char* password = "andreasd1";

    void startCameraServer();

    void setup() {
      Serial.begin(115200);
      Serial.setDebugOutput(true);
      Serial.println();

      camera_config_t config;
      config.ledc_channel = LEDC_CHANNEL_0;
      config.ledc_timer = LEDC_TIMER_0;
      config.pin_d0 = Y2_GPIO_NUM;
      config.pin_d1 = Y3_GPIO_NUM;
      config.pin_d2 = Y4_GPIO_NUM;
      config.pin_d3 = Y5_GPIO_NUM;
      config.pin_d4 = Y6_GPIO_NUM;
      config.pin_d5 = Y7_GPIO_NUM;
      config.pin_d6 = Y8_GPIO_NUM;
      config.pin_d7 = Y9_GPIO_NUM;
      config.pin_xclk = XCLK_GPIO_NUM;
      config.pin_pclk = PCLK_GPIO_NUM;
      config.pin_vsync = VSYNC_GPIO_NUM;
      config.pin_href = HREF_GPIO_NUM;
      config.pin_sscb_sda = SIOD_GPIO_NUM;
      config.pin_sscb_scl = SIOC_GPIO_NUM;
      config.pin_pwdn = PWDN_GPIO_NUM;
      config.pin_reset = RESET_GPIO_NUM;
      config.xclk_freq_hz = 20000000;
      config.pixel_format = PIXFORMAT_JPEG;
      //init with high specs to pre-allocate larger buffers
      if(psramFound()){
        config.frame_size = FRAMESIZE_UXGA;
        config.jpeg_quality = 10;
        config.fb_count = 2;
      } else {
        config.frame_size = FRAMESIZE_SVGA;
        config.jpeg_quality = 12;
        config.fb_count = 1;
      }

    #if defined(CAMERA_MODEL_ESP_EYE)
      pinMode(13, INPUT_PULLUP);
      pinMode(14, INPUT_PULLUP);
    #endif

      // camera init
      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
        Serial.printf("Camera init failed with error 0x%x", err);
        return;
      }

      sensor_t * s = esp_camera_sensor_get();
      //initial sensors are flipped vertically and colors are a bit saturated
      if (s->id.PID == OV3660_PID) {
        s->set_vflip(s, 1);//flip it back
        s->set_brightness(s, 1);//up the blightness just a bit
        s->set_saturation(s, -2);//lower the saturation
      }
      //drop down frame size for higher initial frame rate
      s->set_framesize(s, FRAMESIZE_QVGA);

    #if defined(CAMERA_MODEL_M5STACK_WIDE)
      s->set_vflip(s, 1);
      s->set_hmirror(s, 1);
    #endif

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      startCameraServer();

      Serial.print("Camera Ready! Use 'http://");
      Serial.print(WiFi.localIP());
      Serial.println("' to connect");
    }

    void loop() {
      // put your main code here, to run repeatedly:
      delay(10000);
    }

title: esp32-cam stuck in repeat boot

Answers: 1

body:
The message:

> Brownout detector was triggered

is being generated by your ESP32 because there is a problem with the Vcc power to the module.

Check the following:

1. Your USB cable.  Some cables are just plain cheap and can't supply the power the ESP32 needs.  Get a better one.

1. Some PCs are not able to supply enough power from their USB ports to supply the ESP32, try a powered USB hub and/or a different PC.

1. Some ESP32 modules are poorly made and may have bad solder joints or low quality components.  Your only real option here is to buy a better ESP32.

1. If you are powering other components from the ESP32's power supply, stop it.  Power any accessories separately.


body:
I am using the **MPU6050_light** library for getting the data for my quad-copter. When I am obtaining the gyro values from the MPU6050 without running the motors, its giving correct values but on running the motors and getting the values, I am getting a huge spike on both axes. I am a **newbie and a tenth-grader** so i don't know so much about electronics. I tried using a **Kalman filter** but could not find any code which can help me and the Kalman Library was too complex. I think if I apply some kind of filter the problem will be solved. If any one knows any other filter and its code, if you can share it, it would be of great help.
The code is as follows:
```
#include <SoftwareSerial.h>
#include <Servo.h>
#include <MPU6050_light.h>
#include <Wire.h>

double x = 0.0, y = 0.0, z = 0.0;
int c=0;

SoftwareSerial Slave(5,6);
Servo m1, m2, m3, m4, l;
MPU6050 mpu(Wire);

int throttle = 0;
int t1 = 0, t2 = 0, t3 = 0, t4 = 0;
unsigned long timer;
int of = 0;

void setup()
{
  Slave.begin(9600);
  Serial.begin(9600);
  Wire.begin();
  byte stat = mpu.begin();
  del(1000);
  mpu.calcOffsets();
  del(2000);
  m1.attach(3, 800, 2000);
  m2.attach(9, 800, 2000);
  m3.attach(10, 800, 2000);
  m4.attach(11, 800, 2000);
  l.attach(12, 800, 2000);
  throttle = 0;
  normal();
  del(10000);
  l.detach();
  while (of == 0)
  {debug();}
}

void loop()
{
  normal();
  debug();

  if (of == 0)
  {
    safe_land();
  }

  getxyz();

  if (x < -5.0)
  {
    t1 = t1 + 1;
    t3 = t3 + 1;
    debug();
    normal();
    getxyz();
  }

  if (x > 5.0)
  {
    t2 = t2 + 1;
    t4 = t4 + 1;
    debug();
    normal();
    getxyz();
  }
  if (y < -5.0)
  {
    t4 = t4 + 1;
    t3 = t3 + 1;
    debug();
    normal();
    getxyz();
  }

  if (y > 5.0)
  {
    t2 = t2 + 1;
    t1 = t1 + 1;
    debug();
    normal();
    getxyz();
  }

}
void normal()
{
  m1.write(throttle + t1);
  m2.write(throttle + t2);
  m3.write(throttle + t3);
  m4.write(throttle + t4);

}
void safe_land()
{
  throttle = 0;
  t1 = 0;
  t2 = 0;
  t3 = 0;
  t4 = 0;
  normal();
  off();
}
void off()
{
  m1.detach();
  m2.detach();
  m3.detach();
  m4.detach();
  while (true);
}
void del(int tii)
{
  unsigned long tim = (unsigned long)(tii);
  unsigned long t = millis();
  while (millis() - t <= tim);
}
void getxyz()
{
  mpu.update();
  x = (double)(mpu.getAngleX());
  Serial.print("X:");
  Serial.println(x);
  y = (double)(mpu.getAngleY());
  Serial.print("Y:");
  Serial.println(y);
  //z = (double)(mpu.getAngleZ());
}

void debug()
{

  if (Slave.available())
  {
   c=(int)(Slave.read());
  }
   if(c<=180)
   {
    throttle=c;
   }
   if(c==200 || c==201)
   {
    of=c-200;
   }
}
```
I am also using two Arduino UNOs, hence the software serial...

title: When I start running the Brushless motors with MPU6050 in my quadrocopter, there is a sudden spike in the data of Gyro X-axis and Gyro Y-axis

Answers: 0


body:
In my NodeMCU I want a statement to turn on an LED, which is easy, just use `pinnumber, HIGH`. But, what I'm trying to do here is connect multiple LEDs to one pin like this:[![Diagram showing multiple LEDs on a breadboard using a single current limiting resistor.][1]][1]

  [1]: https://i.stack.imgur.com/FEQDc.png

I just wanted to know if this will work and whether all the LEDs will turn on by one command write `(pinnumber, high)` or do I have to do something else to this circuit?
Please help I'm a noob to electronics.

And also, is the resistor correct(1k ohm) or is it 220ohm, because different places suggest different things.

title: I'm working on a NodeMCU project and have a small doubt about LEDs and resistors

Answers: 2

body:
No! Most likely it will not work.

An LED lights up if the Voltage between the Anode (one side of the LED) and cathode (the other leg) exceeds a so called forward voltage (Vf).

This Vf depends on the creation process and differs between different colors. Vf can be between abt. 1.8 Volt (red LEDs) and abt. 4.2 Volt (blue LEDs). Even if the LEDs would have the same color, they might have different forward voltages. If you arrage 4 LEDs in parallel, like you did above, the Voltage over the 4 LEDS is as low as the Vf of the LED with the lowest Vf among the four. If the four LED would not have equal (Vf)s, only one LED will light up and all others stay dark or just glow a little bit.

The sum of the current that flows through the 4 LEDs must also flow through the resistor. So the resistor must let pass 4 times the current that is required for one LED. An normal 3mm or 5mm LED works best at about 10mA to 20mA. Let's say the LEDs have all the same Vf = abt. 2 Volts, and you choose to drive them with 15 mA.
You need 60 mA in sum for the 4 LEDs, that must pass the resistor. You can compute the required resistance with  Ohms law. `R = U / I`.

 - R is the resistance in Ohms.
 - U is the voltage over the resistor in Volts.
 - I is the current through the resistor in Ampere.

    U = Voltage of the ESP (3.3 Volt) minus
        the lowest forward voltage of the LEDs (2 Volt)
    I = the wanted current 60mA = 0.06 Ampere

    R = (3.3-2) / 0.06 = 140 / 6 = abt. 23 Ohm
    (27 Ohm resistors should be available.)

The resistor depends on the Voltage of the ESP, the kind of the LED and the amount of current you need to reliably light up the LEDs. You can not just take values from schematics or discussions the internet. Also 60 mA is very much current for the ESP pin. That might be a problem.

The best way the Light up 4 LEDs from one pin would be to use one resistor for each LED and a MOS FET Transistor that is connected to 5 Volts with its Drain pin, the parallel LED resistor pairs with its Source and to the ESP pin with its Gate. You should also be sure that the MOS FET you use is able to switch with a 3.3 V voltage from the ESP on its Gate.

If you did not understand what I have written, I advice you to learn the basics before experimenting further. The values above are all useless if the conditions change.

body:
Yes, technically your circuit works. But don't do like this.

TLDR;

This applies only to what you are doing
1. LED is current device. We control brightness by control current flow through it.
2. Each IO pin (of ESP8266) has current drive capable (source/sink) 12mA only, so calculate it wisely or you risk killing it.
3. Simplest way to control current of LED is using current limiter or just a resistor in series
4. Voltage drop across red LED (Vf) is 1.8v
5. 4 LEDs in parallel work just like 1 LED, assuming the same kind, but of course 4 times dimmer
6. Current goes through each LED = 1/4 of current goes through resistor (kirchhoff law of current)
7. Equation: 3v3 = 1.8v + V_R hence , V_R = 1.5v
8. Current goes through resistor I_R = V_R / R
9. 5mm LED has nominal current of 20mA to be considered brightest that last VERY long time.
10. BUT ESP8266 can only do 12mA. You go 20mA, ESP8266 goes bye bye.
11. So choose 10mA to be on safe side. Plug 10mA into #8, hence R = 1.5v / 10mA = 150 ohm
12. You can choose resistor value from 220R up to 1K, no problem. Higher resistance, less current.
13. You can do rough calculation, ignore voltage drop across LED, just use 3v3 / 10mA = 330R. Hence you will see people usually use resistor 330 ohm regardless 3v3 or 5v, red LED or green LED. Because at 5v it is 15mA, red or green makes only 0.3mA different. Nothing to worry.
14. But your circuit has 4 LEDs in parallel, hence current through each LED = 10mA/4 = 2.5mA
15. Fact: Even as low as 0.15mA (R=10k with 3v3 power supply), RED and GREEN LEDs are still bright enough for indication.

Note:
- My guess is, you are using LEDs like a torch. More LEDs = more brightness, right? Unfortunately, it won't work like that. You want to use transistor (BJT) or mosfet as a switch to turn on power supply for LED instead of driving LED from IO pin. Google high side switch or low side switch for that matter. Better solution is to use LED driver IC.
- Normally for simple indicator, I just whack a 470R resistor in series of a LED regardless voltage to drive it (5v or 3v3). It still gives quite intense brightness when you stare directly on it. Sometime you want to use 1k ohm just to reduce the brightness further or even sanding the LED from crystal clear into translucent white.


body:
We are using ESP32 with arduino sdk for developing our application. In our application we need to implement BOD to detect with specific voltage level.

Basically we want to set specific voltage level and when device goes to power off it will detect and trigger interrupt. How I can set interrupt for brown out detect?

we have only this code:

```
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"

void setup() {
  Serial.begin(115200);
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 1); //enable brownout detector
}

void loop() {
  Serial.println("Start BOD");
  delay(1000);
}
```

title: How to implement brown out detector arduino ESP32?

Answers: 1

body:
The ESP32's on-board BOD is mainly intended to inhibit operations that might cause corruption if they happened with too low a voltage.  There is a very unpredictable amount of time for the code in the ESP32 to do anything but effectively halt.

If that's what you want, then you have enabled it in your code above.

If you want to detect a power outage, for example, and log something, then you need two things:

1. A reliable detector that the power has failed.
1. A battery or capacitor-based circuit that will continue the ESP32's power for long enough for you to do what you need to do.

So when "1" happens you set a GPIO pin on the ESP32 which triggers your interrupt and you do what you need to do while the power remains stable.


body:
I'm a beginner of Arduino programming,  when I dumped the following code into Arduino NANO board, at the first the output is as expected. But After few trials the 16*2 LCD display is getting off and DC motor pump is running continuously.

```c++
      #include <Wire.h>
      #include <Adafruit_MLX90614.h>
      #include <LiquidCrystal_I2C.h>
      LiquidCrystal_I2C lcd(0x27, 16,2);

      char *typeName[]={"Object","Ambient"};

      Adafruit_MLX90614 mlx = Adafruit_MLX90614();

      const int trigPin = 13;
      const int echoPin = 12;
      #define DCwater_pump 11

      long duration;
      int distance;

     void setup()
     {
          Serial.begin(9600);
          Serial.println("S.O.A.P. DISPENS");

          Serial.print("Ambient = ");
          Serial.print(mlx.readAmbientTempF());
          Serial.print("*F\tObject = ");
          Serial.print(mlx.readObjectTempF());
          Serial.print("*F");

          Serial.println();

          delay(500);

          if (!mlx.begin())
          {
              lcd.print("MLX90614 Failed");
              lcd.setCursor(0,1);
              lcd.print("check wiring!");
              while (1)
              ;
          }
          Wire.begin();
          lcd.begin(16,2);
          lcd.backlight();
          lcd.print("S.O.A.P.D. Temp");
          lcd.setCursor(0,1);
          lcd.print("S.O.A.P.D. Temp");
          delay(500);
          clearCharacters(2-1,0, 16-1);

          pinMode(trigPin, OUTPUT);
          pinMode(echoPin, INPUT);
          pinMode(DCwater_pump, OUTPUT);

    }

void loop()
{

        printTemp('C');
        delay(1000);

        printTemp('D');
        delay(1500);

}

float getTemp(char type)
{

  float value;
    float tempObjec = mlx.readObjectTempC();
    float tempAmbient = mlx.readAmbientTempC();

   if(type =='C')
   {
    value = tempObjec;
   }
   else if(type =='D')
   {
    value = tempAmbient;
   }
   return value;

}

            void printTemp(char type)
  {
            clearCharacters(1,0, 16-1 );
            float TmpC =getTemp(type);
            float TemF;
            TemF = (TmpC*1.8)+32;
            lcd.setCursor(0,1);
            if(type =='C')

              {
                lcd.print(typeName[0]);
                lcd.print(" ");
                lcd.print(TemF);
                lcd.print((char)223);
                lcd.print("F");
               }

                  else if(type =='D')
                  {
                    lcd.print(typeName[1]);
                    lcd.print(" ");
                    lcd.print(TemF);
                    lcd.print((char)223);
                    lcd.print("F");
                  }

  }

void clearCharacters(uint8_t row,uint8_t start, uint8_t stop )
{
    for (int i=start; i<=stop; i++)
    {
    lcd.setCursor (i,row);
    lcd.write(254);
    }

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance= duration*0.034/2;

    Serial.print("Distance: ");
    Serial.println(distance);

           if (distance < 30)
          {
           digitalWrite(DCwater_pump,HIGH);
           Serial.println("DC Pump is ON Now!!");
           delay(500);
          }
          else
          {
           digitalWrite(DCwater_pump,LOW);
           Serial.println("DC Pump is OFF Now!!");
           delay(500);
          }

}
```

title: When is following code is dumped into Arduino NANO the output is not as expected after few trials

Answers: 0


body:
im using ph meter DFROBOT v1.0 at i compiled the code from the DFROBOT web this is the code

    *
     # This sample code is used to test the pH meter V1.0.
     # Editor : YouYou
     # Ver    : 1.0
     # Product: analog pH meter
     # SKU    : SEN0161
    */
    #define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
    #define Offset 0.00            //deviation compensate
    #define LED 13
    #define samplingInterval 20
    #define printInterval 800
    #define ArrayLenth  40    //times of collection
    int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
    int pHArrayIndex=0;
    void setup(void)
    {
      pinMode(LED,OUTPUT);
      Serial.begin(9600);
      Serial.println("pH meter experiment!");    //Test the serial monitor
    }
    void loop(void)
    {
      static unsigned long samplingTime = millis();
      static unsigned long printTime = millis();
      static float pHValue,voltage;
      if(millis()-samplingTime > samplingInterval)
      {
          pHArray[pHArrayIndex++]=analogRead(SensorPin);
          if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
          voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
          pHValue = 3.5*voltage+Offset;
          samplingTime=millis();
      }
      if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
      {
        Serial.print("Voltage:");
            Serial.print(voltage,2);
            Serial.print("    pH value: ");
        Serial.println(pHValue,2);
            digitalWrite(LED,digitalRead(LED)^1);
            printTime=millis();
      }
    }
    double avergearray(int* arr, int number){
      int i;
      int max,min;
      double avg;
      long amount=0;
      if(number<=0){
        Serial.println("Error number for the array to avraging!/n");
        return 0;
      }
      if(number<5){   //less than 5, calculated directly statistics
        for(i=0;i<number;i++){
          amount+=arr[i];
        }
        avg = amount/number;
        return avg;
      }else{
        if(arr[0]<arr[1]){
          min = arr[0];max=arr[1];
        }
        else{
          min=arr[1];max=arr[0];
        }
        for(i=2;i<number;i++){
          if(arr[i]<min){
            amount+=min;        //arr<min
            min=arr[i];
          }else {
            if(arr[i]>max){
              amount+=max;    //arr>max
              max=arr[i];
            }else{
              amount+=arr[i]; //min<=arr<=max
            }
          }//if
        }//for
        avg = (double)amount/(number-2);
      }//if
      return avg;
    }

and its work, untill i want to combine thats code to my code, the ph value = 0.00
im just copy paste the code from the website in to my code and its not working what should i do

    void loop()
    {
      //-------------Read Function sensor-----------
    //  PPM----
        gravityTds.setTemperature(temperature);  // set the temperature and execute temperature compensation
        gravityTds.update();  //sample and calculate

        tdsValue = gravityTds.getTdsValue();
        tdsValue=(tdsValue *2)/1000;// then get EC the value
        Serial.print(tdsValue,5);
        Serial.println("ppm");

        hasilec = (ppmcensor - inputec );
        Serial.print("Eror EC : ");
        Serial.println(hasilec,6);

    // ph-----
      if(millis()-samplingTime > samplingInterval)
      {
          pHArray[pHArrayIndex++]=analogRead(SensorPin);
          if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
          voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
          pHValue = 3.5*voltage+Offset;
          samplingTime=millis();
      }
      Serial.print("Nilai pH :");
      Serial.println(voltage,2);

    //  ph = (phcensor - inputph);

    //  hasilec = random(-200, 0) / 100.0;
    //  ph = random(-200, 200) / 100.0;
      ph = 130/100.0;

      unsigned long now = millis();

      SerialMon.print("EROOR pH    ");
      SerialMon.print(ph);
      SerialMon.print("  ");
      SerialMon.print("ERORR EC ");
      SerialMon.print(hasilec);
      SerialMon.println("");
      SerialMon.print(ph);  Serial.print(" ");
      SerialMon.print(hasilec);   Serial.print(" ");
      SerialMon.println(" ");

      fuzzy->setInput(2, hasilec);
      fuzzy->setInput(1, ph);
      fuzzy->fuzzify();

      float pompa01 = fuzzy->defuzzify(1);//pHDOWN
      float pompa02 = fuzzy->defuzzify(2);//pHUP
      float pompa03 = fuzzy->defuzzify(3);//ABMIX

      SerialMon.println("Result= ");
      SerialMon.println("");
      SerialMon.print(" Pompa1 pHDOWN: ");
      SerialMon.println(pompa01);
      SerialMon.print(" pompa2 phUP  : ");
      SerialMon.println(pompa02);
      SerialMon.print(" pompa3 ABMIX : ");
      SerialMon.println(pompa03);
      SerialMon.println("");
      SerialMon.println("");
      SerialMon.println("");

      delay (2000);

      long int pompa1 = pompa01*1000;
      long int pompa2 = pompa02*1000;
      long int pompa3 = pompa03*1000;

      pump_periods[0] = pompa1; //PHdown
      pump_periods[1] = pompa2; //PHup
      pump_periods[2] = pompa3; //ABMIX

    //  for (int i = 0; i < jml_pump; i++) {
    //      if (now - pump_last_actuations[i] >= pump_periods[i]) {
    //          pump_states[i] = (pump_states[i] == LOW) ? HIGH : LOW;

    //          digitalWrite(pump_pins[i], pump_states[i]);
    //          pump_last_actuations[i] = now;
    //      }
    //  }

      for (int i = 0; i < jml_pump; i++) {
      digitalWrite(pump_pins[i], LOW);     // Start pump i
      delay(pump_periods[i]);            // nyala waktu dalam pompa[i] ms
      digitalWrite(pump_pins[i], HIGH);     // Stop pump i
      }
      delay(100000);
    }
    double avergearray(int* arr, int number){
      int i;
      int max,min;
      double avg;
      long amount=0;
      if(number<=0){
        Serial.println("Error number for the array to avraging!/n");
        return 0;
      }
      if(number<5){   //less than 5, calculated directly statistics
        for(i=0;i<number;i++){
          amount+=arr[i];
        }
        avg = amount/number;
        return avg;
      }else{
        if(arr[0]<arr[1]){
          min = arr[0];max=arr[1];
        }
        else{
          min=arr[1];max=arr[0];
        }
        for(i=2;i<number;i++){
          if(arr[i]<min){
            amount+=min;        //arr<min
            min=arr[i];
          }else {
            if(arr[i]>max){
              amount+=max;    //arr>max
              max=arr[i];
            }else{
              amount+=arr[i]; //min<=arr<=max
            }
          }//if
        }//for
        avg = (double)amount/(number-2);
      }//if
      return avg;
    }

title: error ph meter cant show the data

Answers: 0


body:
From the image, the diodes share the same anode which is driven by 'Do Something'. My question is: through using Arduino IDE, what code should I write that connects the output of the multiplexer (Z) to a specific diode's cathode (Y0 or Y1 or ... or Y7), which in turn is connected to 'Do Something' that drives the cathode probably? In this code, I want the ESP32 microcontroller to connect this cathode to 'Do Something' for say 3 seconds and then switch to the next diode's cathode with a delay of 0.1 seconds [where no diodes' cathodes are connected to Z]       (and so on: in a continuous loop).

Here some code I found online but not sure what needs to be added to get the proper functionality:

    int outputs[4] = {4,0,2}; // pins for selecting LED
    int inhibit_pin = 15; // pin for turning off all LEDs

    void setup() {
      for(int i;i<3;i++){
        pinMode(outputs[i],OUTPUT); // output selection for LED control
      }
      pinMode(inhibit_pin,OUTPUT);
      digitalWrite(inhibit_pin,LOW); // raise high to disable all

    }

    void loop() {
      // looping through all 8 LEDs
      for (int j=0;j<8;j++){
        // turn on LEDs based on bit conversion
        for(int i=0;i<3;i++){
          digitalWrite(outputs[i],bitRead(j,i));
        }
        delay(100); // delay .1 sec
      }
    }

I don't think that "digitalWrite(outputs,bitRead(j,i));" is actually needed and I am not quite sure of what it does.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Yp46k.jpg

title: Connecting the cathode of a diode to the output of a multiplexer

Answers: 1

body:
The code you have posted should loop through the 8 possible MUX in/out pins (Y0...Y7) connecting one at a time to pin 3.

Assuming your Y0 through Y7 are each connected to a pin on your "do something" block, the mux should connect each of the 7 pins on your "do something" to Z.

One problem I see is that your code changes the pin select values on the MUX while the MUX is enabled. As you execute your `for(int i=0;i<3;i++)` loop and toggle the different select bits to S0...S2, the MUX will connect different Y0...Y7 pins to Z, until it settles on the final set of values for S0...S2. You should really set inhibit_pin to HIGH (disabling the mux before entering your `for(int i=0;i<3;i++)` loop, and then set it to LOW again at the end of the `i` loop and before the delay. (to re-enable the MUX at the now-completely-selected pin.)

Your description is a little hard to follow, but it sounds like that is what you want.

If you want each pin to be connected for 3 seconds, then not connected to any pin for .1 seconds before moving on to the next pin, you might rewrite your loop like this:

```
void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){

    // disable the mux while selecting a pin
    digitalWrite(inhibit_pin,HIGH);

    // select a MUX pin
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    // re-enable the mux now that we've selected a pin
    digitalWrite(inhibit_pin,LOW);

    delay(3000); // leave the pin active for 3 seconds.

    // disable the mux for .1 seconds
    digitalWrite(inhibit_pin,HIGH);
    delay(100);
  }
}
```


body:
I tried to connect two modules that require I2C connection and they won't work at the same time.

I used the [Arduino Sensor Kit - Base][1]. This kit does not need any connection, you just have to code to get your desired output. I wanted to display the Air Pressure (BMP280) module values to the 0.96" OLED Display, however, it is refusing to run both the air pressire and the OLED display at the same time. Only running one module (either Air pressure or OLED) at a time makes it work. Does it have something to do with how the I2C connection is wired on the board?

    #include "Arduino_SensorKit.h"

    void setup() {
      // put your setup code here, to run once:
      Oled.begin();
      Oled.setFlipMode(true);
      Oled.setFont(u8x8_font_7x14B_1x2_r);

      Pressure.begin();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Oled.clear();

      Oled.setCursor(0, 10);
      Oled.print("Temp: ");
      Oled.print(Pressure.readTemperature());
      Oled.print(" C");
      Oled.setCursor(0, 20);
      Oled.print("Pres: ");
      Oled.print(Pressure.readPressure());
      Oled.print(" Pa");
      Oled.setCursor(0, 30);
      Oled.print("Alti: ");
      Oled.print(Pressure.readAltitude());
      Oled.print(" m");

      delay(1000);
    }

What I did:

 1. Test to see if Air Pressure will still work while both Air Pressure and OLED is connected by using `Serial.begin()`. Now I know that only the OLED does not work when both modules are connected.
 2. Changed order of initialization. Same result: Air Pressure works but not OLED

  [1]: https://www.seeedstudio.com/Arduino-Sensor-Kit-Base-p-4743.html

title: Grove Base Kit Multiple I2C Connection

Answers: 1

body:
About two weeks ago there was a change in the Arduino_SensorKit Library that introduced an error with the instanciation of the Oled object.

I found the error in the release (v1.0.6) of the library. The previous release (v1.0.5) could cause another issue, as it uses a software I2C. I doubt the hardwired sensores are connected with the correct pins. But I have no hardware, so I can not check this.

I propose a workaround to see, if the identified issue caused your observations.

    #include "Arduino_SensorKit.h"

    U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2;
    // if the line above does not work
    // comment it and uncomment the following line.
    // U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2(U8X8_PIN_NONE);

    void setup()
    {
      Oled2.begin();
      Oled2.setFlipMode(true);
      Oled2.setFont(u8x8_font_7x14B_1x2_r);

      Pressure.begin();
    }

    void loop()
    {
      Oled2.clear();

      Oled2.setCursor(0, 10);
      Oled2.print("Temp: ");
      Oled2.print(Pressure.readTemperature());
      Oled2.print(" C");

      delay(1000);
    }

Could you please try out and report your experience.
If it would work, I can support the fixing of the issue.


body:
I want to set a temperature and have Nano turn on for 2 minutes then off for 2 minutes and repeat using the same temperature originally set and have the ability to change temperature settings and do the same.

The following sketch works along with displaying battery voltage using MIT Inventor 2 app via Bluetooth HC-05 to my Android phone (without the on/off sequence I am looking to do).

I hope to keep my feet warm but also extend the battery life.  Can you tell me what methods I should research to figure out how to do this? I have looked at millis(), blink without delay, and my own limited programming skills without success.  Thanks.

```c++
#define right 5
#define left 6

int leftval = 0;
int val=0;
int vg=0;

void setup() {
  Serial.begin(9600);
  pinMode(left, OUTPUT);
  pinMode(right, OUTPUT);
  pinMode(A0, INPUT);
}

void loop() {
  int vg = analogRead(A0);
  Serial.println(vg / 82.049, 1);
  delay(200);
  if (Serial.available() >= 2) {
    unsigned int a = Serial.read();
    unsigned int b = Serial.read();
    unsigned int val = (b * 256) + a;

    if (val >= 0 && val <= 255) {
      analogWrite(right,val);
      delay(200);
    }

    if (val >= 1000 && val <= 1255) {
      leftval = val - 1000;
      analogWrite(left, leftval);
      delay(200);
    }
  }
}
```

title: I am making heated socks with adjustments by Nano and want to extend batterty life?

Answers: 1

body:
With an electrical heating element powerful enough to warm your feet, the power to the heating element is hundreds or thousands of times greater than the power to your Arduino. Anything you do to reduce the power consumed by your Arduino will have no meaningful effect on your total power consumption. It's like trying to stop a drip in your faucet to save water while the main water pipe has water gushing out of a gaping hole.

Heating elements convert watts of power to calories of heat. The more watts you put in, the more heat you get.

Current • duty cycle • on-time = total power consumed AND total heat generated.

If you reduce the duty cycle to the heating element, you will reduce the power consumed, but you will also reduce the amount of heat generated.

Given that you already have the ability to vary the duty cycle to your heating element (via your analogWrite to `right` and `left`) the only meaningful way to reduce power consumption is to lower the heat setting. It looks like you already have that ability. Turn down the heat setting and have slightly colder feet, or use a higher capacity battery.

All that said, if you turn the heat setting down to 0, the heating element completely stops using power. At that point the Arudino will slowly drain your battery while your electric socks sit in your sock drawer. It would be worth putting your Arduino in ultra-low-power sleep mode (or even turning it off entirely) to avoid draining it while you're not using it.

## Edit:

If you want to run the heating element on for 2 minutes, off for 2 minutes, that would give exactly the same power savings as running it at half the current power level, but constantly.

If you really want to implement the 2 minutes on, 2 minutes off approach, you will need to use millis() to keep track of the time when you last turned the elements on/off. I suggest refactoring your current code to remove delay and use millis as well.

Take a look at the "BlinkWithoutDelay" sketch (which I believe is included with the IDE, and is certainly available online) for an idea of how to handle timing things without using `delay()`.


body:
I'm trying to put an Arduino Nano in low-power mode using this guide: [Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery](http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/).

The article suggests 3 things: use the Low-Power library from Rocketscream, cut the power to the power LED, and remove the voltage regulator.

So far I've only done the first two and reduced the clock speed to 8 MHz.

The important part of the source code that puts the Arduino in deep sleep looks like this:

```c++
void setup() {
  CLKPR = 0x80; // (1000 0000) enable change in clock frequency
  CLKPR = 0x01; // (0000 0001) use clock division factor 2 to reduce the frequency from 16 MHz to 8
}

void loop() {
  // Go to sleep until the next scheduled wake up
  int32_t waitSeconds = 60;
  while (waitSeconds > 0) {
    period_t waitFor = SelectWaitTime(waitSeconds);
    LowPower.powerDown(waitFor, ADC_OFF, BOD_OFF);
    waitSeconds -= PeriodToSeconds(waitFor);
  }
}

period_t SelectWaitTime(int32_t secondsToWait) {
  if (secondsToWait >= 8)
    return SLEEP_8S;
  else if (secondsToWait >= 4)
    return SLEEP_4S;
  else if (secondsToWait >= 2)
    return SLEEP_2S;
  else if (secondsToWait >= 1)
    return SLEEP_1S;
}
```

In essence, sleep for up to 8 seconds, remove the seconds from the counter, then sleep again.

So far I've only scratched off the trace to the power LED and haven't removed the voltage regulator. According to the article above, this should reduce the power consumption to around 0.05 mA but I get around 1.7 mA, which is over 30 times more!

Electrically, I only have a MOSFET as a power switch connected to one of the analog pins (I use it as a digital output) and another controller, connected to the I2C pins (the Arduino acts as Slave). The other controller is turned off through the MOSFET when I take the measurements. Physically removing the connections doesn't change the consumption, so I don't think any of that is related.

Is there something I did wrong? What can I do to achieve power consumption similar to the one in the article?

title: How to put Arduino Nano in low power sleep mode (<0.05mA)

Answers: 1

body: Turns out the voltage regulator was AMS1117 - not MIC5205-KB50/KB33/KBAA like the one in the article. Ripping it off gave me the 0.026 mA idle current which is even better than what I was hoping for.


body:
I have seen [this video][1]:

[Over The Air programming Tutorial][1]

For programming the Arduino modules via internet  OTA system, so I have tried the [adafruit][2] account and don't find the **AIO_KEY** part [on it][3], ( as you can see below):

[![enter image description here][4]][4]

So I like to know about other web server systems for testing this option on the Arduino module (for me is ESP8266 01!).

So please suggest some free internet website as alternative options  like suggested site via above video ( adafruit).

The codes for making the esp8266 ready to accept the OTA process is accessible [here][5].

Note: Also the [https://io.adafruit.com/][6] server have some Problem right now:

So if possible I like to know is any safe methods exist for the interrupt and server problem
 situation like this ([adafruit 503 error, seen below][7]) during the Arduino  OTA programming?

[![enter image description here][8]][8]

**Update**:

I have found the link of adafruit **OTA_Key** :

https://io.adafruit.com/ss1/dashboards/<Your_acount_Name>

[![enter image description here][9]][9]

Thanks.

  [1]: https://www.youtube.com/watch?v=GR2ZXyPaqMo
  [2]: https://io.adafruit.com
  [3]: https://accounts.adafruit.com/users/security
  [4]: https://i.stack.imgur.com/5dae1.png
  [5]: https://github.com/techiesms/Over-The-Air-Programming/blob/master/OTA.ino
  [6]: https://io.adafruit.com/
  [7]: https://www.uptimia.com/website-availability-test/e98da71a
  [8]: https://i.stack.imgur.com/XnhHx.png
  [9]: https://i.stack.imgur.com/802ht.png

title: Searching for free OTA Server Host list name

Answers: 0


body:
New to Arduinos and stuff.

I have tried the L293D and the transistor method but the motor just wouldnt work.

I have tested the motor and it definitely is fine.

Below is my layout for this attempt:

Bits used:

 - Arduino UNO
 - 1N4007 Diode
 - PN2222
 - 230 ohm resistor

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/vnva5.jpg

My sketch is ::

```c++
int motorPin = 3;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(motorPin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()) {
    int speed = Serial.parseInt();
    if (speed >= 0 && speed <= 255) {
      analogWrite(motorPin, speed);
    }
  }
}
```

HELP!!!

title: DC Motor will not work. Transistor method nor L293D!

Answers: 0