body:
Sorry I am new with this.
I am trying to read a JSON response from my website using an ESP8266, but it keeps failing.  I am using the following code:

    WiFiClientSecure httpsClient;    //Declare object of class WiFiClient
    httpsClient.setInsecure();
    httpsClient.setTimeout(15000); // 15 Seconds

    if (httpsClient.connect(host, httpsPort)) {

      String Data ="/IOT/Device_Setup.php?MAC="+deviceMAC;

      httpsClient.print(String("POST ") + Data + " HTTP/1.1\r\n" +
       "Host: " + host + "\r\n" +
       "Connection: close\r\n\r\n");

      while (httpsClient.connected()) {
        String line = httpsClient.readStringUntil('\n');
        Serial.println(line);
        if (line == "\r") {
          Serial.println("headers received");
          break;
        }
      }
      String payload = "";
      while (httpsClient.available()) {
        char c = httpsClient.read();
        payload=payload+c;
      }

      Serial.println(payload);

      // Allocate JsonBuffer
      // Use arduinojson.org/assistant to compute the capacity.
      const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
      StaticJsonDocument<200> jsonBuffer;
      // Parse JSON object
      DeserializationError error = deserializeJson(jsonBuffer, payload);
      if (!error) {

        const char* Switch = jsonBuffer["Switch"];
        const char* LED = jsonBuffer["LED"];
        const char* DHT = jsonBuffer["DHT"];

        // Decode JSON/Extract values
        Serial.print("Switch = ");
        Serial.println(Switch);
        Serial.print("LED = ");
        Serial.println(LED);
        Serial.print("DHT = ");
        Serial.println(DHT);
      }
    }

When I print out the payload after the header I receive the following output:

> 22

> {"Switch":"0","LED":"0","DHT":"1"}

> 0

I know the 22 is the hex value for the number of bytes being sent.  Is there a way of ignoring the numbers and just using the JSON code?

title: JSON Parser fails because number of bytes is being sent

Answers: 0


body:
I am trying to interface 16by2 lcd with msp432p401m controller but my 16 by 2 lcd is not showing any character. I have attached schematic and code for reference. By using same schematic and code 20 by 4 lcd is working properly.

please help me...

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

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

  [1]: https://i.stack.imgur.com/eIgN0.png
  [2]: https://i.stack.imgur.com/ev678.png

title: 16 by 2 lcd display is not showing any character

Answers: 0


body:
I'm trying to build a sensor that should update an MQTT broker only if something changes. So every few seconds it's supposed to wake up just enough to check a few inputs, compare them with the last time it woke up, and only if there has been a change should it connect to the broker and write the updates. I don't expect many updates per day, but if I sleep more than 10 seconds, I might miss them.

I'm using `WiFi.forceSleepBegin()` and `WiFi.forceSleepWake()`, mainly based on [these articles](https://www.bakke.online/index.php/2017/05/21/reducing-wifi-power-consumption-on-esp8266-part-1/). But there is this tempting option of `ESP.deepSleep(n, WAKE_RF_DISABLED)`

The [API](https://arduino-esp8266.readthedocs.io/en/latest/libraries.html#esp-specific-apis) that I found only mentions this:

> If you implement deep sleep with WAKE_RF_DISABLED and require WiFi functionality on wake up, you will need to implement an additional WAKE_RF_DEFAULT before WiFi functionality is available.

Do I read this correct if I understand that I would need to make another `deepSleep` just to wake up again with WiFi back active? Or is there an easier way to boot up the WiFi after such a sleep?

Thank you

title: How to bring WiFi back up if woken from deepSleep(WAKE_RF_DISABLED)

Answers: 2

body:
    WiFi.forceSleepBegin();
    delay(1);
    WiFi.forceSleepWake();
    delay(1);

Source: [GitHub][1]

That also works, I tested it December 2020.  Thanks to Erik Bakke for finding it.  It's a bit more clean than another Deep Sleep boot with the modem enabled.  Igrr and I both struggled to find a way to wake the modem, and Erik mixed the magic sauce.  Hopefully it still works today with the changes to the core WiFi files.

  [1]: https://github.com/esp8266/Arduino/issues/3072#issuecomment-741524721

body:
Yes, you understood correctly; after using `ESP.deepSleep(n, WAKE_RF_DISABLED)` to disable WiFi, the most reliable method to re-enable it is to call `ESP.deepSleep(1, WAKE_RF_DEFAULT)`. Then connect to WiFi on the next wake (which should be in 1 second). [Apparently][1], `WAKE_RFCAL` and `WAKE_NO_RFCAL` also result in WiFi working.

A cheap way to approach this, is to normally sleep with `WAKE_RF_DISABLED` but when your WiFi connection fails, sleep with `WAKE_RF_DEFAULT` to make the next connection more likely to be successful.

If you want a more elegant, but slightly more complex solution, you can use the [RTC memory][2] to store the known WiFi state when you sleep; so when you sleep with `WAKE_RF_DISABLED`, you'll know that you'll have to reset with `WAKE_RF_DEFAULT` before trying to connect. And, when you wake again, you'll know the WiFi has been enabled.

As mentioned in [another answer][3], after using `WAKE_RF_DISABLED`, you could call `WiFi.forceSleepBegin()` and then immediately call `WiFi.forceSleepWake()` to try to bring the WiFi back up without resetting. While I have actually found this to work, sadly it seems to be unreliable. Seems like it might work while on USB power, but when changing to another power source, it stops working. I'm not sure why. When using that approach, sometimes the MCU will consume only 40 mA when it's supposed to consume 70 mA with WiFi on, so this suggests to me that the WiFi doesn't properly initialize.

All that being said, I would suggest that using `WAKE_RF_DISABLED` is quite extreme. Like in your original solution, I have found that you can avoid using `WAKE_RF_DISABLED` altogether if you call `WiFi.forceSleepBegin()` immediately when the device starts (i.e. at the top of your `setup()` function), and then `WiFi.forceSleepWake()` when you want to use WiFi. When the device starts, there is only perhaps 50-100ms when the device is using 70mA before WiFi is turned off. This is probably acceptable for most low power designs.

  [1]: https://hutscape.com/tutorials/wakeup-with-no-radio
  [2]: https://hutscape.com/tutorials/rtc-memory
  [3]: https://arduino.stackexchange.com/a/85289/78174


body:
//Here is my code so far

    int speakerPin = 9;

    int length = 28;

    char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

    int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

    int tempo = 150;

    void playTone(int tone, int duration) {

    for (long i = 0; i < duration * 1000L; i += tone * 2) {

       digitalWrite(speakerPin, HIGH);

       delayMicroseconds(tone);

       digitalWrite(speakerPin, LOW);

       delayMicroseconds(tone);

    }

    }

    void playNote(char note, int duration) {

    char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                     'c', 'd', 'e', 'f', 'g', 'a', 'b',

                     'x', 'y' };

    int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                     956,  834,  765,  593,  468,  346,  224,

                     655 , 715 };

    int SPEE = 5;

    for (int i = 0; i < 17; i++) {

       if (names[i] == note) {
        int newduration = duration/SPEE;
         playTone(tones[i], newduration);

       }

    }

    }

    void setup() {

    pinMode(speakerPin, OUTPUT);

    }

    void loop() {

    for (int i = 0; i < length; i++) {

       if (notes[i] == ' ') {

         delay(beats[i] * tempo);

       } else {

         playNote(notes[i], beats[i] * tempo);

       }

       delay(tempo);

    }

    }

title: Any advice on how to repeat the song 6 times instead of infinitely?

Answers: 1

body:
Assuming, the program can stop after playing 6 times, put another `for` loop in the `loop` function:

    void loop()
    {
       for (int nTimes = 0; nTimes < 6; nTimes++)
       {
          // Existing loop code
       }

       while(true) {};
    }

A less crude way is to create a global variable:

    int _timesPlayed = 0;

And change the `for loop`:

    void loop()
    {
       if (_timesPlayed < 6)
       {
          // Existing loop code

         _timesPlayed++;
       }
    }


body:
I have two DT-06 boards [DT06 datasheet][1].

----------

The board stock firmware provides Web UI for wifi/network/serial setup. I've replaced the firmware on one board with other sketch; but now I want to revert it to the stock firmware. I cannot find the stock firmware source code anywhere. The DT-06 manufacturer also won't give it out.

Is it possible to extract the stock firmware from another DT-06 board and put it back into the other DT-06 board?

Thank you.

  [1]: https://www.mikrocontroller.net/attachment/349564/UserManualForTTL-WiFi.pdf

title: How to extract code on one DT-06 board to another board?

Answers: 1

body:
Okay. I found a way to extract the binary file (stock firmware) from one DT-06 and flash it to another modified DT-06, by using esptool command

    /*To extract firmware */:
    esptool.py -p COM4 -b 460800 read_flash 0 0x400000 dt06_backup.bin
    /*To flash the backup binary file to another DT-06 */
    esptool.py -p com4 write_flash -fm dout 0x00000 dt06_backup.bin


body:
I working on a project where I want to collect sensor data (from a sensor) and I want to analyze the first 20 data sample (e.g., find the range, trendline e.t.c.). I know how to compile a timer interrupt in Arduino IDE (using an ISR timer), but how would I be able to do this something similar (ISR timer) in MATLAB. The reason being, I want to collect my sensor data at exactly 20 Hz and using a delay function can prove to be inaccurate. Also, when I run a sample program that collects data in MATLAB, my sample frequencies change from 15Hz to even 24Hz (as shown below) . Does anyone have any suggestion on how I can do this? If the question is not clear enough I can elaborate more in the comments.

This is my MATLAB code:

```
clear all;
a = arduino('com4', 'uno');
i = 0;
v1 = zeros(1e4,1);
v2 = zeros(1e4,1);
x = zeros(1e4,1);
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
                 'StartDelay',5,'Period', 1);
start(t)

stat=true;
tic
while(stat==true)
   %while i<60
    i = i + 1;
    v1(i) = readVoltage(a, 'A0');
    v2(i) = readVoltage(a, 'A1');
    x(i) = i;
    disp(x(i));
    pause(.00001);

  % end
end
toc

% %Plot voltage versus time
v1 = v1(1:i);
v2 = v2(1:i);
x = x(1:i);

p = v1;
n = v2;
%Plot voltage versus time
figure(1);
plot(x,p,'-',x,n,'-')
xlabel('Elapsed time (sec)')
ylabel('v')
title('Ten Seconds of voltage Data')
%set(gca,'xlim',[t(1) t(i)])
legend('v1', 'v2');

%
delete(t) % Always delete timer objects after using them.
```

Output is
```
>> Timer
     1

     2

     3

     4

     5

     6

     7

     8

     9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

Timer!
    76

Elapsed time is 5.032553 seconds.
>>
```

I apologize for the long output. But as you can see, I specified a pause time of .00001, which should give me well over a 20Hz sampling frequency. But I only get 76 samples/5 seconds = 15.2Hz. Also, sometime when I run this the program may collect 79sample/5secons, or even  121sample/5seconds. It just is not consistent. I was hoping to solve this with a timer interrupt that will be hard coded in MATLAB to collect data at exactly 20Hz. Please let me know what y'all think. Thank you.

title: How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab?

Answers: 2

body:
Each communication with Arduino takes 20ms, you have two in the loop so in the ideal conditions you could get 25 readings/second. [See here the source][1]

This also depends on the size of the data you request.

I think [this is what you are looking for][2] but I cant give you any advice since I don't have Matlab and Octave is not having this feature.

  [1]: https://www.mathworks.com/help/supportpkg/arduinoio/ug/custom-library-concepts.html#bu73xge
  [2]: https://www.mathworks.com/help/supportpkg/arduinoio/ug/code-generation-from-matlab-function-block.html

body:
I've configured the timer differently making use of its `UserData` property. The timer will update the data every fixed period for a specified number of samples.

```matlab
close all;
clear all;

% Some useful constants.
NUM_SAMPLES = 20;
PERIOD = 0.05;

global a;
a = arduino('com4', 'uno');

% Initialise data. It will be updated by the timer.
data.i = 0;
data.v1 = zeros(NUM_SAMPLES, 1);
data.v2 = zeros(NUM_SAMPLES, 1);
data.x = (1:NUM_SAMPLES) * PERIOD;

% Initialise timer for a fixed period for a specific number of samples.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = PERIOD;
t.TasksToExecute = NUM_SAMPLES;
t.TimerFcn = @TimerCallback;
t.UserData = data;

% Run the timer and wait for it to complete.
start(t);
wait(t);
stop(t);
data = t.UserData;  % Retrieve the updated data.
delete(t);

% Plot voltage versus time.
figure(1);
plot(data.x, data.v1, '-', data.x, data.v2, '-');
xlabel('Elapsed time (s)');
ylabel('Voltage (V)');
title('Voltage Data');
st = sprintf("%0.3f seconds", NUM_SAMPLES * PERIOD);
subtitle(st);
legend('v1', 'v2');

function TimerCallback(obj, event)
    global a;
    obj.UserData.i = obj.UserData.i + 1;
    obj.UserData.v1(obj.UserData.i) = readVoltage(a, 'A0');
    obj.UserData.v2(obj.UserData.i) = readVoltage(a, 'A1');
end
```


body:
I am a complete novice in programming and I hope someone could guide me here. I am doing a haptic research project, where 8 DC coin vibrating motors would be fitted on the fingers of subjects (excluding thumbs), and the subject has to respond the number of fingers they feel the vibrations on.

Every trial has to have a different pattern of outputs, say: in first trial, 4 motors are activated-motor 1, motor5, motor8 and motor 3. In a single trial, the motors have to have a common delay of 150 ms and 4 seconds break after next one starts.

**My question is, that in 8 motors, there are 255 different activation patterns possible. How do I define all these 255 patterns and randomise their sequence?
I am using the mega board and connecting each motor to a PWM pin and all having a common ground.**

Here is a sample code with 3 such combinations (only seven motors are connected here):

```c++
#define viboutpin 2
#define viboutpin1 3
#define viboutpin2 4
#define viboutpin3 5
#define viboutpin4 6
#define viboutpin5 7
#define viboutpin6 8

void setup() {
     pinMode(viboutpin,OUTPUT);// define a pin as output
     pinMode(viboutpin1,OUTPUT);
     pinMode(viboutpin2,OUTPUT);
     pinMode(viboutpin3,OUTPUT);
     pinMode(viboutpin4,OUTPUT);// define a pin as output
     pinMode(viboutpin5,OUTPUT);
     pinMode(viboutpin6,OUTPUT);
}

void loop() {
    digitalWrite(viboutpin,HIGH);
    digitalWrite(viboutpin1,HIGH);
    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin3,HIGH);
    digitalWrite(viboutpin4,HIGH);
    digitalWrite(viboutpin5,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin, LOW);
    digitalWrite(viboutpin1,LOW);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin3,LOW);
    digitalWrite(viboutpin4,LOW);
    digitalWrite(viboutpin5,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin4,HIGH);
    delay(150);
    digitalWrite(viboutpin4,LOW);
    delay(2000);
}
```

title: How to run multiple DC motors in different patterns?

Answers: 1

body:
Why not generate a psuedo random number from 0 to 255 and use it as a code for which motors are to be activated - bit 0 == viboutputpin0, etc.? Then one function can look at each bit in turn and activate that motor if the bit is set, delay, and stop the motors.

You'll probably want to test your code with a few pre-defined test patterns instead of the random ones, and once you're satisfied that it works, randomly seed the random number generator so your project will generate a different pattern each time. One way to do that is to ask via terminal for the operator to click the 'Send' button (or tap the space bar if you're using a separate terminal emulator that sends key by key). Measure the time from the request to the response in microseconds, discard the 2 or 3 least significant bits of the result and keep the next 8. The micros() function's resolution is 4 usec at 16 MHz, is the reason for discarding those 2 lower bits.


body:
I'm currently working on nodeMCU and need to use interrupt pin. I find out there are bouncing problem when using interrupt thus i use capacitor 100uF to solve this problem. **The question is by using multiple interrupt pin, do i need multiple capacitor (one for each pin) or only one for all pin?** The question arise because if I parallel the capacitor it would increase the capacitance and perhaps would create a problem(?)

I using interrupt pin for LM 393 speed encoder [like this one][1]
(for simplicity, i use switch to describe the encoder pin on schematic)
Basically work like switch but no floating pin since it is a comparator, always between high or low.

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

  [1]: https://www.amazon.com/DAOKI-Measuring-Optocoupler-Arduino-Encoders/dp/B081W2TY6Q
  [2]: https://i.stack.imgur.com/QtsP0.png

title: Debouncing interrupt using capacitor

Answers: 0


body:
I recently downloaded the expressif ESP32 library and I'm trying to run the CameraWebServer example. Attempting to compile it results in the following error:

```
Sketch uses 2529577 bytes (192%) of program storage space. Maximum is 1310720 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.
```

I can reduce this number (192%) to 120% by changing partition scheme from "Default" to "No OTA (Large APP)". Online I've seen people using a partition scheme called "Huge APP", which I believe would solve my problem, but I don't see that option in Tools. Only "Default", "Large App" and "Minimal SPIFFS" (which doesn't work either).

How can I get the "Huge APP" partition scheme option in Arduino IDE?

title: No "Huge APP partition scheme" (ESP32)

Answers: 1

body:
I was able to fix the issue by editing the boards.txt file and adding the following lines:

```
lolin32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
lolin32.menu.PartitionScheme.huge_app.build.partitions=huge_app
lolin32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
```

This will add a "Huge APP" partition scheme to WEMOS Lolin32.


body:
When reading and writing with a python serial port connection to arduino, if I don't use latin-1 ('ISO-8859-1'), the results are not as expected. Like if I have

```
int outP = 5;
//...
int outV = Serial.read();
analogWrite(outP, outV);
```

While with python I have

```
serial_port.write(chr(255).encode())
```
I read 3.78 V from the pin, whereas if I use

```
serial_port.write(chr(255).encode(encoding = 'latin-1'))
```
I get 5.04 V. I have read latin-1 and utf-8 don't always match, but is there something about arduino that requires using latin-1? Of course, these return different values when testing each encoding, using 255 gives b'\xc3\xbf' (from 'Ã¿') with utf-8 or b'\xff' from ('ÿ') with latin-1, but why does arduino work with latin-1?

FYI other options that work are
```
v = 255

serial_port.write(v.to_bytes(1, byteorder = 'big'))

serial_port.write(bytes[v])

```

title: Why do I need to use latin-1 instead of utf-8 when using python with arduino?

Answers: 1

body:
> but is there something about arduino that requires using latin-1?

No, not really.

What it comes down to is that `Serial.read()` reads bytes, irrespective of whatever encoding they may be being used with.  ISO-8859 only encodes character code points in the 0-255 range, so when you choose a 0-255 code point and send it as ISO-8859, it gets sent as 1 byte, which is how you're code has been written to receive it.

A 255 code point as utf-8 would require multiple bytes to encode and so would result in multiple `Serial.read()` calls for a given value.

If you open a python3 REPL and put `chr(255).encode()` or more explicitly `chr(255).encode('utf-8')` you will see it results in `b'\xc3\xbf'`.  So on the Arduino side you will see this as two separate `Serial.read()` results, `0xC3` and `0xBF`.

When you're just taking in strings and UTF-8 and splatting them out via `Serial.println()`, the Arduino is blissfully unaware of that they're UTF-8 and not ISO-8859.  Really you could use any encoding you wanted, the the caveat being that if you're using c-strings to store them, the encoding would need to be one that doens't allow for a single null byte to be in the middle of the string.

---

You may want to look into using [struct.pack][1] rather than cobbling together python bytestrings with sequences of `chr()` and `.encode(whatever)`. `struct.pack` will also result in a bytestring, but it's more purpose built for doing this.

You can `import struct` and then `struct.pack('B', 255)` will result in `b'\xff` same as `chr(255).encode('iso8859-1')`, but at least expresses intent.  `'B'` here signifies an `unsigned char` range, you'll find the format specifiers in the documentation. You'll get a greater benefit when you begin using multiple fields where `struct.pack` will be a lot less unwieldy than the `chr` and `encode` and string concatenation.

  [1]: https://docs.python.org/3/library/struct.html#struct.pack


body:
This is the first time I use the Internet with the Arduino in the proteus ,
What are the stages that I must follow in order to be able to control the switch via Bluetooth?
If it was possible to clarify more, because I really do not know anything about the other applications, taht my first project in iot.
[![enter image description here][1]][1]

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

title: how to control switch (proteus) using bluetooth card (HC-05) and arduino?

Answers: 0


body:
I am using an Arduino and two relays to control 12V DC motor.
I need to rotate the motor in both directions.

For the first trials it worked fine. Finally one next switching fried my Arduino.

I think there is something wrong in the schematic.
I believe that Arduino was killed by reverse voltage spike produced by motor.

I already know that I need a diode across the motor. However, I have two directions here.

So, what is the proper schematic for my task?

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

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

title: Control DC motor in both directions with two relays

Answers: 1

body:
In short, you're probably overloading your regulator.

It's difficult to say for sure, but I have a suspicion and can give a framework for thinking about it with some very crude numbers.

If you're powering the Nano from a 12 V source, you are dropping 7 V across the regulator.  If you do the math on this 7 V drop, it means every 14 mA drawn through the regulator induces nearly a tenth Watt of heat in the regulator.  7 V * 0.014 A = 0.098 W.  I'm guessing you have a budget of perhaps 300mW based on the way the Nano's regulator is set up.

The ATmega328P says it uses 5.2 mA (typical) or 9 mA (maximum) at 5 V and active at 8 MHz.  But really it will use more at the 16 MHz frequency.  For sake of argument, I'm just going to say it's using 14 mA, because it makes the math easy and because power usage scales somewhat linearly with frequency.

Just the power led will use about 3 mA, if it's an official Nano, but for simplicity sake, I'll call it 7 mA, being half of 14 mA and we'll ignore the fact that there are other loads on the board like the serial transceiver.

Your relay coils will use *at least* 30 mA, but likely more, perhaps a lot more.  But for ease of calculation lets go optimistic and say they only use 28 mA (cause 2 * 14 mA).

So we have the ATMega328P inducing 100 mW in the regulator, the power led and some extras adding 50 mW. at at least one relay coil energized for another 200 mW.  So right there you're already at 350 mW.  If you screwed up and managed to energize both relays, 550 mW.  Hopefully the regulator will enter thermal shutdown when this happens, in which case all you need to do is let it cool down and, you know, stop doing that.  But it may also just die,which is more likely if you have a clone that happens to use a crappier regulator.

But, I think these numbers are conservative.  For example, a datasheet for a Songle SRD-05VDC-SL-C relay that a lot of these modules use seems to say it will use closer **70 mA** each, rather than 28 mA.  This means operating just one of these coils by itself, nevermind the rest of the Arduino, will cause nearly half a Watt to be dissipated in the regulator if you're powering from 12 V.  If you managed to turn on both coils well... nothing good.

If this is not *the* problem you're having, it is *a* problem.  You can save yourself a fair bit of trouble by powering your Nano from USB with a powered hub or reasonable quality USB-output wall adapter.  Doing so bypasses your regulator altogether.

If you're going to continue staging down 12 V to 5 V for the relay coils, then you may need an external regulator to operate the relay modules, just to unload the the Nano's regulator.  Exactly how you'd go about that depends somewhat on the construction of the relay module.  Some of them make it a bit easier on you and are design to accept voltage from a second source for the coils.


body:
I want to use c++ data structures such as vectors, arrays, map... in my Arduino sketch. I made sure to **add -std=c++11 and -std=gnu++11 in platform.txt**, I am still getting the following error message:

> fatal error: unordered_map: No such file or directory
> #include <unordered_map> compilation terminated. exit status 1 unordered_map: No such file or directory

Here's a snapshot from ~/arduino-nightly/hardware/arduino/avr/platform.txt:

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

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

Versions:

 - Arduino ide: 1.8.14
 - g++: 5.4.0
 - avr-g++: 4.9.2

**What else should I set up?**

title: Unable to compile c++11 libraries despite having added -std=c++11 in platform.txt

Answers: 1

body:
The AVR-based Arduinos don't come with anything close to a full C++ standard library implementation.  They have [avr-libc][1] which is fairly complete to at least the [C99 standard][2], that is the C standard from 1999, not C++.  What you're doing with `-std=c++11` is influencing the standard used by the compiler to interpret the C++ language itself.  This does work fine on AVR based Arduinos, but is not going to give you the sort of C++ containers you may be used to on a desktop or larger embedded system, like an ESP8266.

Much of the C++ standard library would be completely out of place on an AVR based Arduino, particularly those parts that make use of dynamic allocation like `unordered_map` in your error message.

There are *some* parts of the C++ library implemented via [Arduino STL][3].  Whether or not you *should* be using containers from it is another question.

If you do try to use Arduino STL, I'd encourage you to use more conservative parts of it.  Something like an `unordered_map`, but with less (or no) dynamic allocation could be implemented by using Arduino STL's `std::array` and functions from its `<algorithm>` header, like their `std::find` or `std::lower_bound`, etc.  Trying to use a C++ `map` or `vector` container or something of that sort is kind of asking for trouble, more so on the more common AVR-based Arduinos with only roughly 2 Kbyte of RAM.

  [1]: https://nongnu.org/avr-libc/
  [2]: https://en.wikipedia.org/wiki/C99
  [3]: https://www.arduino.cc/reference/en/libraries/arduinostl/


body: I recently bought a Raspberry Pi Pico to play with, and am attempting to upload my first program to it *the Arduino way*, as my own operating system rather than a c++ program over an existing operating system (meaning to replace the built-in Raspberry Pi Pico operating system which runs MicroPython, not in the sense of running Linux, Windows, Mac, or any derivative or fork). I have not found any record of people hacking it like that - is it possible? If so, how would I go about it? Sorry if this is in the wrong Stack Exchange.

title: Arduino Core for the Raspberry Pi Pico

Answers: 3

body:
Here is the library for the Arduino IDE and a Raspberry Pi pico.

https://github.com/lrusak/Arduino-Core-Pico

Just install normally as a .zip.

body:
Official support.
-----------------

Apparently there's official support for it, now anyway.

I was digging around in the [Arduino-mbed core][1], trying to help someone else, specifically in the [boards.txt][2] and spied the line:

> pico.name=Raspberry Pi Pico

Unfortunately, I don't have any way to give it a proper test as I don't have one of these.  But I did go so far as to install the core and compile a simple hello world program.

In boards manager
-----
Search for "mbed rp2040"; these names sometimes change, but those terms work well now.  You can see in the lower item, I have version 2.0.0 installed.

[![Boards manager dialog shown with search terms "mbed rp2020"][3]][3]

Board menu selection
----

`Tools`/`Board`/`Arduino Mbed OS RP2040`/`Raspberry Pi Pico`

[![Shows Menu with board selected.][4]][4]

Seems to work.
-------------
As you see it at least builds without error.  As I said, I'm unable to give it a real test.  But that at least looks promising.

[![Shows successful build.][5]][5]

  [1]: https://github.com/arduino/ArduinoCore-mbed/
  [2]: https://github.com/arduino/ArduinoCore-mbed/blob/2.0.0/boards.txt
  [3]: https://i.stack.imgur.com/CSz4e.png
  [4]: https://i.stack.imgur.com/GvLEf.png
  [5]: https://i.stack.imgur.com/fWqTS.png

body:
It is worth mentioning [this excellent alternative](https://github.com/earlephilhower/arduino-pico) to the Arduino one from Earle F. Philhower. It seems well-maintained and doesn't depend on Mbed OS, so it leaves more space (ram and flash) for your application.

[Here](https://github.com/earlephilhower/arduino-pico/issues/117#issuecomment-830356795) an informal comparative list.


body:
I have a nodejs application deployed and have been trying to send data to the api using the following sketch on my nodemcu:

```

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

Serial.begin(115200);
WiFi.begin("mySSID", "myPassword");

while (WiFi.status() != WL_CONNECTED)

delay(500);
Serial.println("Waiting for connection");

}

void loop() {

if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status

  HTTPClient http;
  http.begin("https://www.livesessions.host/api/v1/readings" , "cc2707645d0222700161a174671cb8b0258eaa91");
  http.addHeader("Content-Type", "application/json");
  String postMessage = "{'deviceMAC':'ddd eee fff', 'humidity':'99', 'soilTemp':'88'}";
  int httpCode = http.POST(postMessage);
  Serial.print("http result:");
  Serial.println(httpCode);
  http.writeToStream(&Serial);
  String payload = http.getString();
  http.end();

  }else{

    Serial.print("Error in Wifi connection");

}

delay(30000); //Send a request every 30 seconds

}
```

Although I am able to make data entries using the api and postman, the below code returns -1 (which I think is connection refused), the website is an https site.

Please advise on what I am doing wrong.

Thanks.

title: nodemcu POST request over https return error code -1

Answers: 0


body:
I'm working on a research project that allows me to press a button on a matrix that then outputs a parameter like temperature, humidity etc. But I cannot find out what is wrong with the buttons, when I press them nothing is happening. Thank you very much! I've attached what the connection between the Arduino and the keypad looks like.

    #include <EEPROM.h>
    #include <GravityTDS.h>
    #include "DHT.h"
    #include <LiquidCrystal_I2C.h>
    #include <Wire.h>
    #include <Servo.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <Keypad.h>
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    #define DHTPIN 7
    #define DHTTYPE DHT11   // DHT 11
    #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
    #define PUMPPIN 9
    #define ONE_WIRE_BUS 4
    int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
    int pHArrayIndex = 0;
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);
    Servo myservo;
    GravityTDS gravityTds;
    DHT dht(DHTPIN, DHTTYPE);

    char incomingByte;
    String inputString;
    int pump = 9; // Output for pump Control
    double avg;
    int h;
    float t;
    float tdsValue;
    float temperature = t;
    static unsigned long samplingTime = millis();
    static unsigned long printTime = millis();
    static float pHValue, voltage;

    const byte ROWS = 4;
    const byte COLS = 4;

    char hexaKeys[ROWS][COLS] = {
      {'A', 'B', 'C', 'D'},
      {'E', 'F', 'G', 'H'},
      {'I', 'J', 'K', 'L'},
      {'M', 'N', 'O', 'P'}
    };

    byte rowPins[ROWS] = {44, 42, 40, 38};
    byte colPins[COLS] = {36, 34, 32, 30};

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    void setup() {

      lcd.begin();
      pinMode(pump, OUTPUT); //sets the digital pin as output
      digitalWrite(pump, LOW); // Initial state of the pump
      Serial.begin(9600);
      gravityTds.setPin(A1);
      gravityTds.setAref(5.0);
      gravityTds.setAdcRange(1024);
      gravityTds.begin();
      dht.begin();
      sensors.begin();
    }

    double averagearray(int* arr, int number) {
      int i;
      int max, min;
      long amount = 0;
      if (number <= 0) {
        Serial.println("Error number for the array to avraging!/n");
        return 0;
      }
      else 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;
    }

    void loop() {
      lcd.print("working so far. test1");
      delay(5000);
      char customKey = customKeypad.getKey();
      int pumptime = 1000;
      switch (customKey) {
        case 'A':
          // pump
          digitalWrite(pump, HIGH); // on pump
          delay(pumptime);
          digitalWrite(pump, LOW);//off pump
          break;
        case 'B':
          // add pump time
          pumptime += 500;
          break;
        case 'C':
          // less pump time
          pumptime -= 500;
          break;
        case 'D':
          // reset pump time
          pumptime = 1000;
          break;
        case 'E':
          //temp
          sensors.requestTemperatures();
          lcd.setCursor(0, 0);
          lcd.print("Celsius temperature: ");
          lcd.print(sensors.getTempCByIndex(0));
          lcd.print((char)223);
          lcd.print("C");
          delay(5000);
          lcd.clear();
          break;
        case 'F':
          // Temperature & humidity
          h = dht.readHumidity();
          t = dht.readTemperature();
          lcd.setCursor(0, 0);
          lcd.print("Humidity:");
          lcd.print(h);
          lcd.print("%");
          lcd.setCursor(0, 1);
          lcd.print("Temperature:");
          lcd.print(t);
          lcd.print((char)223);
          lcd.print("C");
          delay(5000);
          lcd.clear();
          break;
        case 'G':
          // TDS
          h = dht.readHumidity();
          t = dht.readTemperature();
          temperature = t;
          gravityTds.setTemperature(temperature);
          gravityTds.update();
          tdsValue = gravityTds.getTdsValue();
          lcd.setCursor(0, 0);
          lcd.print("TDS: ");
          lcd.print(tdsValue);
          lcd.print("ppm");
          delay(5000);
          lcd.clear();
          delay(5000);
          lcd.clear();
          break;
        case 'H':
          // pH
          lcd.clear();
          lcd.setCursor(0, 0);
          if (millis() - samplingTime > samplingInterval)
          {
            pHArray[pHArrayIndex++] = analogRead(SensorPin);
            if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
            voltage = averagearray(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
          {
            lcd.print("Voltage:");
            lcd.print(voltage, 2);
            lcd.print("    pH value: ");
            lcd.println(pHValue, 2);
            digitalWrite(LED, digitalRead(LED) ^ 1);
            printTime = millis();
          }
          delay(5000);
          lcd.clear();
          break;
        case 'I':
          // test buttons
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'J':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'K':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'L':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'M':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'N':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'O':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'P':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
      }//switch
      lcd.print("working so far. test2");
      myservo.write(0);
      delay(10000);
      myservo.write(90);

      delay(1800000);

}

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

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

title: 4x4 matrix keypad not working

Answers: 1

body:
Imho, your delay function in loop() is a root cause.
First, you should remove the below code

      myservo.write(0);
      delay(10000);
      myservo.write(90);

      delay(1800000);

Then,please reduce delay(5000) -> delay(200).
Build and execute your code.
Press and hold a single button and take a look what happen in LCD. At least, you able to confirm the keypad hardware works well or not.


body: I'm using the Arduino plugin in CLion. I can't seem to figure out how to have multiple cpp files for my classes. I have been putting the code in my .h up until now, but that's going to bite me soon.

title: In CLion, how can I set up multiple cpp files for arduino

Answers: 0


body:
I’m working on a project, to create an air mouse for people with repetitive strain injury (since I have it as well). I’m flexible with the hardware required. The plan is to use data from an IMU for movement. I’m currently learning how to work with the sensor.

I have also been researching how to eventually convert the sensor data to mouse movements. I understand that you can do this over Bluetooth (Bluetooth HID, or HID over GATT). However, this is where I reach my limits.

I was hoping to find a library, which can do this for me (similar to the mouse.h library) as it feels like it would take me months learning about the Bluetooth standards to try to implement it myself.

The options I found in my research:

 - [Adafruit boards only library so ties you to their ecosystem][1]
 - [mbedOS library, code seems different then the arduino sketches I’ve
   seen so far and is difficult to understand][2]
 - [esp32 based library,    would need to learn how to use that
   processor and not sure if    supported properly in arduino IDE)][3]
 - [Arduinoble.h library, would    you need to create the mouse HID
   profile from the ground up)][4]

Since many of you are much more experienced than me, I would be grateful for any guidance on how to proceed. Would you show a preference for any of the options above? Or should I be attempting to do things differently, e.g. without a mouse library (but where would I start)?

PS. In case it’s useful, I have basic familiarity with C++ (e.g. I understand classes, pointers, etc.), but I don’t have a programming background. I have done a few simple arduino projects and most of the examples on the official website.

  [1]: https://github.com/cyborg5/BLE52_Mouse_and_Keyboard
  [2]: https://github.com/tcoppex/mbed-ble-hid
  [3]: https://github.com/asterics/esp32_mouse_keyboard
  [4]: https://www.arduino.cc/en/Reference/ArduinoBLE

title: Bluetooth HID for mouse project

Answers: 0


body:
i built a car that works with four motors,one motor driver(specifically the l293d),the arduino and the battery pack with four AA-Batteries. The motors work fine though, but they only work when it is connected to the laptop and the battery pack.I've also removed the METAL insulation from the copper wire and now it is copper.Sadly i have also connected the two poles together and there was some lightning but no fire thankfully(by accident of course).if anyone else had the same issues and fixed them please contact me.
Thank you very much stranger.

title: My car only moves when it is plugged directly into both my pc and battery pack?

Answers: 0


body:
I want to power an ESP32 with a 3.7V LiPo battery. There's a LED matrix of 64 WS2812 LEDs attached to the ESP32. I learned that I need a buck boost converter to power the microcontroller as it needs a 5V power input. The boost converter delivers that when there is no matrix attached. However if the matrix is attached it only receives about 2.7V. Turning the potentiometer on the boost converter changes nothing in this case. What is the reason for this? I am sorry if this question seems basic to you. I am an beginner with electronics.

Here is a rather hideous scetch of the connections. I hope this is okay:
[![enter image description here][1]][1]

This is the buck converter I used: https://www.amazon.de/gp/product/B079H3YD8V/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1

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

title: Power LED Matrix With LiPo Battery & ESP32

Answers: 1

body:
The way you have it set up is fine if you aren't going to light up all the LEDs at full brightness. And if you do, you're not going to break your ESP32 Dev Board the way you have it set up in your diagram (since you are not running the power THROUGH the board). The LiPo battery probably has its own little regulator on it to prevent it from being damaged.

Check your dev board specifications on how much power you actually need to supply to the Vin pin. [The ESP32 chip operates between 2.3 and 3.6 volts (3.3 recommended).][1] Your dev board regulates the 5v to provide that amount to the chip.

Most likely, your dev board will run fine on the 3.7V provided by your LiPo without the buck-boost. I use a similar setup (without a buck-boost) to demo little projects to friends. I use a ESP32U-01 dev board from EZSBC, a 64 LED Matrix from Adafruit, and a 3.7v LiPo battery.

Depending on how many LEDs are lit (and what color), you shouldn't expect the battery to last very long. And the overall brightness of your led matrix will be limited.

If you are using the [FastLED Animation Library][2], I would recommend setting a power limit using set_max_power_in_milliwatts function and limiting it to 1500mW for starters. Again, if you are not drawing power THROUGH the ESP32 board, you're fine.

  [1]: https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf
  [2]: http://fastled.io/


body:
This sample code for the esp32 doesn't work. When contacting the website I get a 301 error and the website acts as if nothing was ever recieved. Note: Been using arduino for 2 years.

    /*
      Rui Santos
      Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

      Permission is hereby granted, free of charge, to any person obtaining a copy
      of this software and associated documentation files.

      The above copyright notice and this permission notice shall be included in all
      copies or substantial portions of the Software.
    */

    #include <WiFi.h>
    #include <HTTPClient.h>

    const char* ssid = "lol";
    const char* password = "u tried";

    //Your Domain name with URL path or IP address with path
    String serverName = "http://requestbin.net/r/63agtdpl";

    // the following variables are unsigned longs because the time, measured in
    // milliseconds, will quickly become a bigger number than can be stored in an int.
    unsigned long lastTime = 0;
    // Timer set to 10 minutes (600000)
    //unsigned long timerDelay = 600000;
    // Set timer to 5 seconds (5000)
    unsigned long timerDelay = 5000;

    void setup() {
      Serial.begin(115200);

      WiFi.begin(ssid, password);
      Serial.println("Connecting");
      while(WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.print("Connected to WiFi network with IP Address: ");
      Serial.println(WiFi.localIP());

      Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
    }

    void loop() {
      //Send an HTTP POST request every 10 minutes
      if ((millis() - lastTime) > timerDelay) {
        //Check WiFi connection status
        if(WiFi.status()== WL_CONNECTED){
          HTTPClient http;

          String serverPath = serverName + "?temperature=24.37";

          // Your Domain name with URL path or IP address with path
          http.begin(serverPath.c_str());

          // Send HTTP GET request
          int httpResponseCode = http.GET();

          if (httpResponseCode>0) {
            Serial.print("HTTP Response code: ");
            Serial.println(httpResponseCode);
            String payload = http.getString();
            Serial.println(payload);
          }
          else {
            Serial.print("Error code: ");
            Serial.println(httpResponseCode);
          }
          // Free resources
          http.end();
        }
        else {
          Serial.println("WiFi Disconnected");
        }
        lastTime = millis();
      }
    }

title: ESP32 Post Request Not Working

Answers: 0


body:
I got a Resistive sender fuel gauge sketch off the internet that I have adapted.  The Resistive sender is a floating magnet that activates read switches to vary the resistance.  Using a stable 5v power source and 100-ohm resistor I have a voltage bridge that is connected to the sender and pin A1.  The original sketch uses this to get the voltage into liters:

```c++
TankValue0 = map(sensorTankValue0, 352, 824, 0, 100);
if (TankValue0 < 0) {
  TankValue0 = 0;
}
if (TankValue0 > 100) {
  TankValue0 = 100;
```

The lower range is not too far off but as you get to the top it is out to lunch.

I have mapped the segments of MY float sensor's intervals, and have found there to be 17 distinct points-- I measured the voltage at each point and made a table (I mean like on paper) to relate the measured voltage at a given point to a distance in mm, and then converted that to the relevant metric of liters in a tank when the float switch is reading a given voltage.

V    |L
-----|--
4.04 |94
3.981|88
3.902|84
3.81 |81
3.703|77
3.637|72
3.564|69
3.483|65
3.393|61
3.293|57
3.18 |53
3.053|50
2.908|46
2.546|42
2.192|38
1.726|35

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

How do I get that information into the sketch to give me a read-out of L in my tank?

I have no programming knowledge really. I work with Arduino IDE a lot, but only using sketches other people have written.  So, I have a huge basic knowledge gap.  So, please bare that in mind.

This is the whole sketch:

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

int TankValue0;
int TankValue1;

LiquidCrystal_I2C lcd(0x27, 16, 2);   // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup() {
  lcd.init();                          // initialize the lcd
  lcd.init();
  lcd.backlight();
  lcd.setCursor(1, 0);
  lcd.clear();
  lcd.print("WORD");
  lcd.setCursor(0, 1);
  lcd.print("TO");
  delay(1500);
  lcd.clear();
  lcd.print("YO ");
  lcd.setCursor(0, 1);
  lcd.print("MOMMA");
  delay(2000);
  lcd.clear();
  pinMode(A0, INPUT);
  Serial.begin(9600);               // starting the Serial Monitor

}
void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 352, 824, 34, 94);
  TankValue1 = map(sensorTankValue1, 785, 310, 0, 100);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  lcd.print("S.V. SAVANNAH");
  lcd.setCursor(0, 1);
  delay(100);
  lcd.print("DAY TANK   ");
  lcd.print(TankValue0);
  lcd.print("%");
  lcd.setCursor(0, 0);

  delay(1000);
  lcd.clear();
}
```

title: Code for mapping voltage on a sensor and outputting a value in liters

Answers: 1

body:
Curve fitting
-------------

Well, a lazy way to do it is just to fit a curve to it, using Excel, or Libreoffice, Google Docs or whatever.  Here's gnuplot being used that way to fit a cubic polynomial to it:

"points.txt" containing your data, tab-delimited:
```txt
4.04    94
3.981   88
3.902   84
3.81    81
3.703   77
3.637   72
3.564   69
3.483   65
3.393   61
3.293   57
3.18    53
3.053   50
2.908   46
2.546   42
2.192   38
1.726   35
```

Gnuplot session:

```txt
gnuplot> f(x) = A*(x**3) + B*(x**2) + C*x + D
gnuplot> fit f(x) "points.txt" via A, B, C, D
iter      chisq       delta/lim  lambda   A             B             C             D
   0 1.8323200047e+01   0.00e+00  9.28e+01    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
   1 1.8323200047e+01  -4.65e-10  9.28e+00    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
iter      chisq       delta/lim  lambda   A             B             C             D

After 1 iterations the fit converged.
final sum of squares of residuals : 18.3232
rel. change during last iteration : -4.6534e-15

degrees of freedom    (FIT_NDF)                        : 12
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 1.23569
variance of residuals (reduced chisquare) = WSSR/ndf   : 1.52693

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
A               = 2.81842          +/- 1.156        (41.02%)
B               = -11.0015         +/- 10.22        (92.86%)
C               = 14.4765          +/- 29.11        (201.1%)
D               = 28.7358          +/- 26.52        (92.27%)

correlation matrix of the fit parameters:
                A      B      C      D
A               1.000
B              -0.998  1.000
C               0.990 -0.997  1.000
D              -0.974  0.987 -0.996  1.000
```

And here's what looks like against the actual data with `plot "points.txt" with linespoints, f(x)`:
[![Curve fitting with data.][1]][1]

So you have a function:
```c++
float f(float x) {
  static const float A =   2.81842;
  static const float B = -11.0015 ;
  static const float C =  14.4765 ;
  static const float D =  28.7358 ;
  const float x_squared = x * x;
  const float x_cubed   = x * x_squared;

  return A * x_cubed + B * x_squared + C * x + D;
}
```

If you don't care about the code size and the slowness of `float` arithmetic, then that might be okay.

Otherwise you may want to convert that function to something like fixed point arithmetic.

A cubic polynomial may be overkill, but then whole technique may be also.

Peicewise Linear
-----------------

You can make a table of you points and just do what graphing programs typically do, linear interpolation between the points.

```c++
float f(float x) {
  static const struct pt {
    float v;
    int l;
  } points[] = {
    {0.0  ,  0},  // I put this here for testing, but put a better value here.
    {1.726, 35},
    {2.192, 38},
    {2.546, 42},
    {2.908, 46},
    {3.053, 50},
    {3.18 , 53},
    {3.293, 57},
    {3.393, 61},
    {3.483, 65},
    {3.564, 69},
    {3.637, 72},
    {3.703, 77},
    {3.81 , 81},
    {3.902, 84},
    {3.981, 88},
    {4.04 , 94}
    // you should probably have another entry here so that readings up to 5V work.
  };
  static const size_t table_len = sizeof points / sizeof points[0];

  for (size_t i = 0; i < table_len - 1; ++i) {
    if (x >= points[i].v && x < points[i + 1].v) {
      return
            (x - points[i].v)
          / (points[i + 1].v - points[i].v)
          * (points[i + 1].l - points[i].l)
          + points[i].l;
    }
  }

  return -1;
}
```

Sitting in the center of this in the `return` statement is basically a crude implementation of Arduino's `map()`, but for floating point, which again, you don't really need floating point, even if you want to use this piecewise approach.

In short, you find which two entries of the table you're sitting between, and apply what amounts to `map()` on the line segment formed by the two table entries.

PROGMEM
--------

Either of the curve fitting or piecewise approach could be used to generate a much larger lookup table out of which you could just chose the nearest point.

If you're doing this on an AVR-based Arduino, the table for the piecewise linear approach or a pure lookup table approach could use [`PROGMEM`][2] for the array.

Regarding float and fixed point
-------------------------------
Any of these techniques could be adapted to fixed-point math.
Which ever you use, if you're on AVR based Arduino, keep in mind that there's no hardware floating point support at all, and although `double` exists as a type it is implemented in avr-gcc as a single precision `float`.

If you're using one of the non-AVR based Arduinos, it may have support for `float` (and maybe for `double`), in which case the generated code may not be so bad, though may still be slower than using integers.

If you can do everything with integers, resulting code should be a lot smaller and faster.  I'm guessing for what you're doing, if either of them are more important, it's probably being smaller.

For using integers, you may be able to keep your input "voltage" as an ADC count, not having an intermediate voltage calculation.  And even if you want single digit liters when you're done, the intermediate interpolation, curve fitting, or table lookup may require that you work in something like centiliters, milliliters, so that values like the `A` constant from the curve-fitting example can be represented as an integer, e.g.  2818 mL  rather than a cruder 3 L.  If you're not using a plain lookup table and finding the nearest entry, that is if you're using the curve or piecewise linear approach, doing everything in integer arithmetic from ADC count to mL.  Although you'll need to run another curve fitting, since the `A`, `B`, etc will representing mL-per-ADC-count not L-per-Volt.  Or scale them from the value given.

And there are other options, piecewise cubic splines, etc.

  [1]: https://i.stack.imgur.com/w0Tgc.png
  [2]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


body:
I am trying to send data from one arduino to another over ethernet using udp protocol.
In arduino writing data over udp is like this

    UDP.write(buffer, size);
where buffer is an array to send as a series of bytes and size is the size of the array.

Now, i am reading a sensor value from a0 pin of the arduino it will be stored either in int or float type variable. As mentioned earlier udp only sends byte type array. so all i want to do is convert the value stored in the variable to the byte type array.
my variable will be.

    pinMode(A0,INPUT);
    int data;
    byte data_array[Size];

and in loop

    data=analogRead(A0);
now i have convert this value in data_array;

Please provide the suggestion with proper explanation.
Thank you

title: converting int or float into bytes array in arduino

Answers: 0


body:
Arduino suddenly stopped being recognized.
It is not listed in `/dev` and
`dmesg -w` shows no activity at all when un/plugged.

I'm on Fedora 33. The Arduino is MKR-Zero. The cable is ok - other devices work well. I tried it on windows machine - same result - in Arduino IDE the option for port is greyed out.

Very weird thing happened before this issue- when I was trying to flash sketch, audio connected to docking station switched to speakers in laptop and keyboard + mouse connected to the docking station powered down (back light on keyboard went off and could not be turned on) however the Num lock light was on.

I'm afraid that I burned the Arduino - how do I verify if that is the case.
The "ON" LED is lit up when plugged in

title: Arduino stopped showing up in /dev and dmesg without response

Answers: 1

body:
Ok, I have no idea what the hell is this, but when I double-press the reset button (while connected/powered on ofc) it works again.
This can be seemingly cycled - press once and it goes wrong, press twice and it's ok again... round and round. Seems more like some retarded "feature"


body:
I'm using an Arduino Mega and two RGB Led Panels to plot some data. The problem is that the data plotted in the first panel is duplicated in the second as well. What I want is to plot the data on both using just one Arduino Mega. Is it possible? I've read that you can achieve it using one Mega for each panel or using a more powerful controller for both. This question was asked before here

<https://arduino.stackexchange.com/questions/67431/join-two-rgb-ledpanel-32x64-in-order-to-get-one-64x64-how-to>

but no clear answer about commands or changes to made in the code were given. Any idea?

Thanks in advance

title: Connect two 64x32 RGB P4 panels Arduino Mega

Answers: 0


body:
I’m new to arduino and I want to build myself smart switch that can be turned of both manualy and via wifi, is there any way to change position of relay based on if another wire is live or not? Im from europe so we have 230V  outlets.

Thanks for the answer.

[![This is "diagram" of my design][1]][1]

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

title: Arduino changing output based on wire voltage

Answers: 1

body:
Maybe a wire coil wound around the wire could pick up the frequency. Though I won't write about this, since I don't know much about how you would measure this, and because I think, that you are looking the wrong way.

You want to switch one device with multiple switches (how these switches are operates is not important for now). You can look at how this is normally done in eletrical installations. Here the switches are all connected to your breaker box. And there is one component, that waits for trigger signals from the switches and will switch the target device (the light in this case) accordingly. So in the end there is only one place, where the light is switched: in the breaker box. The switches in the room are only triggers. The current for the light does not flow through them. Also they don't necessarily need to carry mains voltage (triggers could also be low voltage) (though it seems they are in fact just using mains voltage, for which I don't know the reason. Maybe to avoid additional voltage conversion).

So I propose the following solution: The mains wires (230V) are only connected to the light and a (suitable) relay board. The relay board is connected to the Arduino, which can act as a Smart Switch (switching via WiFi, time based or whatever). For manual switching you can connect a switch or button to the Arduino and program the Arduino to read it and control the relay accordingly.

This solution is way easier, than trying to sense the live voltage on the lines, and this will most likely make it more reliable . It comes down to controlling an relay board and reading a button/switch, both things with tons of tutorials on the web

Note: Since mains voltage is always really dangerous, you should be really really caution. Don't use mains voltage, when developing your device. A simple LED with current limiting resistir connected to the power line of the Arduino through the relay is sufficient to check the complete functionality. Only connect mains voltage, if you are really really sure, that you did everything correct


body:
I have recently purchased the [Brushless DC-Flat Motors Series 2610][1] from Faulhaber and I am honestly new to this type of motor as it’s pins are not like any other I have used before. I would appreciate any help on how to connect and code this motor to rotate on an arduino using the integrated speed controller in the motor.

  [1]: https://www.faulhaber.com/en/products/series/2610b-sc/

title: Controlling a flat brushless DC motor with integrated speed controller

Answers: 0


body:
Dear friends I have written a code to identify the caller and send a reply SMS to them using sim 800L and pro mini. My program is to identifying the caller number but continuously sending the SMS in an infinite loop. I am not getting what is the reason, kindly help me, thanks in advance. Code is attached

```
#include <SoftwareSerial.h>
SoftwareSerial Serial1(4,3);
String a;
String CellNumtemp;
String CellNum;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.println("AT");
  delay(1000);
  Serial1.println("AT+CSMP=17,167,0,0");
  delay(1000);
  Serial1.println("AT+CLIP=1");
  delay(1000);
   }

void loop(){
   if (Serial1.available() > 0){
   String a = Serial1.readString();
   String  CellNumtemp = a.substring(a.indexOf("+91"));
    CellNum = CellNumtemp.substring(0,13);
     Serial1.println("ATH");
     delay(500);
     Serial.println(CellNum);
     delay(500);
    if (a.indexOf("+91") >= 0){
        sendSMS();
       }
     }
  CellNum = "\0";
}

void sendSMS(){  // Function that sends SMS
     Serial1.println("AT+CMGF=1\r");
     delay(1000);
     Serial1.print("AT+CMGS=");
     Serial1.print("\"");
     Serial1.print(CellNum);
     Serial1.print("\"");
     Serial1.println("\r"); // to send SMS
     delay(1000);
     Serial1.println("Happy to see your call. I am good");
      delay(1000);
     Serial1.println((char)26);
     delay(1000);
     Serial1.println();
     delay(5000);
     Serial1.flush();
     delay(2000);
    }
```

title: Serial.available is giving data even input data is not coming

Answers: 0


body:
I'm using this board in my robotic arm project:
**Adafruit PCA9685 16-Channel Servo Driver** (
https://learn.adafruit.com/16-channel-pwm-servo-driver/using-the-adafruit-library)

I've connected all of my servo and now I'm trying to calibrating each one.

This is my configuration:

---

**Setup**

    pwm = Adafruit_PWMServoDriver(0x40);
    pwm.begin();
    pwm.setOscillatorFrequency(27000000);
    pwm.setPWMFreq(50);

**Movement**

    pwm.setPWM(pinPosition, 0, power);

The `power` is mapped using `map` and **minPulse** and **maxPulse** based on this data structure:

    ServoSettings servo0 = ServoSettings{
       0,   // pinPosition
       125,  // minPulse
       400, // maxPulse
       125  // currentPWM
    };

I'm using `minPulse` and `maxPulse` for calibration and `currentPWM` to store data for each servo.
Data is sended through iPhone via BLE.

---

My servo, start rotating from **125** to **~280** and returns to back and stopped working. I need to power off my board and move the servo from its 0 position just to make movements again.

I don't understand two things:

 1. why the rotation is not 180° but about 45°?
 2. why after 45° servo come back home and stop working?

I suppose that is due to a wrong Adafruit library configuration but of course I'm not sure.

---

Using a manual loop instead of BLE data, result is the same:
`moveServo` is a wrapper of `pwm.setPWM(pinPosition, 0, power)`

      delay(1500);
      servoMgr.moveServo(0, 90);
      Serial.println("0");
      delay(1500);
      servoMgr.moveServo(0, 125);
      Serial.println("A");
      delay(1500);
      servoMgr.moveServo(0, 145);
      Serial.println("B");
      delay(1500);
      servoMgr.moveServo(0, 190);
      Serial.println("C");
      delay(1500);
      servoMgr.moveServo(0, 220);
      Serial.println("D");
      delay(1500);
      servoMgr.moveServo(0, 250);
      Serial.println("E");
      delay(1500);
      servoMgr.moveServo(0, 280); // <<<--- here servo come back home and die.
      Serial.println("F");
      delay(1500);
      servoMgr.moveServo(0, 300);
      Serial.println("G");

---

The **Adafruit board** is powered with an **external 9V battery**.
**Arduino** is powered with **USB** cable.

Can be something **related to voltage**?
What's wrong with the library configuration?

The board now have only 1 servo attached, just for test.

These are the used servo: https://www.amazon.it/dp/B07KD6NVPM

thanks for your suggestions.

title: Servo make partial rotation and stop working automatically

Answers: 0


body:
**EDIT**
This seems to be something to do with the oscillators. Switching to the internal oscillator and writing straight avr-c allows me to run a basic blink program. Writing the same basic blink in arduino and flashing with the IDE (through serial or usbasp) results in a non functional program. I'd like to be able to use the oscillator because it doesn't look like I can get everything done in time at 8MHZ

I have an arduino mega 2560 which a few weeks ago was working fine. Now, I'm trying to output some data from it, and 've broken it down to a very, very basic proof of concept:

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

    void loop() {
       // put your main code here, to run repeatedly:
       Serial.println("hello");
    }

This prints:

    hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

indefinitely on the screen. If I change the baud to 115200, I get the "hello" and the newline, and slowly start getting garbage afterwards. If I switch to 234500, I get a few prints, and then nothing.

Adding a delay after the print does not change the frequency of the serial prints:

    void loop() {
    // put your main code here, to run repeatedly:
        Serial.println("hello");
        delay(100000);
    }

They still come in immediately.

I have a feeling this has something to do with timing of an interrupt, but I'm not setting anything up. I plan to reflash and fix the fuses, but my usbASP cable is broken right now. Any other input on what might be going on here?

Edit:
This occurs on two different boards. I originally had some i2c devices (mag/gryo/barometer) on board, but those have since been removed. I have tried two different usb cables in two different USB ports. This might be on the host side?

Edit:
Both the TX and Rx lights are solid this whole time. Almost as if there's a loopback. My other laptop won't even boot right now. I'm concerned a surge from a storm last night might have taken out both of these machines

More testing:
Looking at the output on a scope, the board is actually only outputting an "h" character. If I do:

    Serial.println('U');
    delay(1000);
I get a square wave, so the delay doesn't run at all.
If I do:
    Serial.println('U');
    Serial.println('U'); //or any other character
    delay(1000);

I get a U character over the scope, and then an empty serial frame. The delay still doesn't run, but it looks like the second println is exiting.

Even burning a new bootloader fails on these boards

title: Weird serial behavior on atmega2560

Answers: 1

body:
Answering my own question - a bit of a walk of shame here.

I had disabled the internal TIMER0_OVF_vect in the arduino core code, so that I could write my own (for another project). I wrapped in in an #if 0 so I could go and bring it back when I needed it.

Today, I learned that the atmega interrupts aren't filled with an IRET by default, but instead hit the reset vector, resetting the board. Anything I compiled on this library would reset whenever TIMER0 overflowed, because my ifdefs didn't cover the TIMSK setting in the arduino core either

The "Serial.println isn't exiting" was actually "the board is resetting before it can complete" and explains why faster bauds could print more data.

Not much smarter than hairless apes, sometimes.


body:
How easy is it to create a code using an RTC to rotate the stepper motor one way at a specific time and back the other way at a specific time? and that time being charged different months of the year. how would I go about this?

I want to make an automatic chicken door, to open in the morning and close at night.

Thanks

title: Coding for RTC and stepper motor

Answers: 1

body: I am assuming that you want to make a clock. To do that you need to find a gear ratio where 1 revolution of the motor equals 60 seconds, and then make the gear ratios for the minutes and horse from that. Then you can use the RTC to spin the motor by 6 degrees every second. If you are not making a clock, please be more descriptive.


body:
I am a NOOB. I admit to a huge lack of understanding of programming. I just need my machine to work.

I cannot wrap my head around getting independent speed control of 2 steppers since it seems that controlling the speed is dependent upon adjusting the length of delay between sending pulses to the motors, however sketches only contain one Loop and any delay in that loop has a global effect.

Here is my code so far
```// Author Robert Baker
// My sketch to control 1.8 degree stepper motors operating the Gizmoto V3 Braiding Machine
// One 10k Pot speed-controls 2 braiding steppers,
// Second Pot speed-controls 3rd stepper which operates the take-up capstan

// Rev 1.0  March 10 2021

// Defines pins numbers

const int braidStepPin = 3;
const int braidDirPin = 2;

const int capstanStepPin = 5;
const int capstanDirPin = 4;

//Define variables here

int braidDelay; // Controls the speed of the braiding drive according to braidSpeed function
int capstanDelay; // Controls the speed of the capstan drive according to capstanSpeed function

void setup() {
  // Sets the pins as Outputs
  pinMode(braidStepPin,OUTPUT);
  pinMode(braidDirPin,OUTPUT);
  pinMode(capstanStepPin,OUTPUT);
  pinMode(capstanDirPin,OUTPUT);

  digitalWrite(braidDirPin,HIGH); // Sets the braid motors' direction
  digitalWrite(capstanDirPin,HIGH); // Sets the capstan motor's direction
}
void loop() {

  digitalWrite(braidStepPin, HIGH); // Sends the braid motors one pulse
  digitalWrite(braidStepPin, LOW);
  delayMicroseconds(braidSpeed);

  digitalWrite(capstanStepPin, HIGH); //Sends the capstan motor one pulse
  digitalWrite(capstanStepPin, LOW);
  delayMicroseconds(capstanSpeed);
}
// Function for reading the Braiding Potentiometer
int braidSpeed() {
  int braidDelay = analogRead(A0); // Reads the potentiometer
  int newBraidDelay = map(braidDelay, 0, 1020, 200, 700); // Converts the read values of the potentiometer from 0 to 1023 into desired delay values
  return newBraidDelay;
}
// Function for reading the Capstan Potentiometer
int capstanSpeed() {
  int capstanDelay = analogRead(A1); // Reads the potentiometer
  int newCapstanDelay = map(capstanDelay, 0, 1020, 200, 700); // Converts the read values of the potentiometer from 0 to 1023 into desired delay values
  return newCapstanDelay;
}
```

title: Need help with independent speed control on multiple steppers

Answers: 0


body:
I was wondering if the following type of wire adapter existed. Because I have some small JST pins and I need to connect them to some JST XH pins. (Preferably on amazon):
[![JST to JST XH adapter][1]][1]

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

JST to JST XH adapter

title: Do these types of wires exist?

Answers: 0


body:
I can't compare for the condition Error "sensors not int type" translate to int type does not work. Please tell me the solution to this problem
```
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define ONE_WIRE_BUS 2
#define Rele 5

OneWire oneWire(ONE_WIRE_BUS);
LiquidCrystal_I2C lcd(0x27,16,2);
DallasTemperature sensors(&oneWire);

int tmp;
int PotenciometrPin = A0;
int val;

void setup(void)
{
 pinMode(Rele, OUTPUT);
 digitalWrite(Rele, HIGH);

 lcd.init();
 lcd.backlight();
}

void loop(void)
{
 lcd.setCursor(0, 0);
 sensors.requestTemperatures();
 val = analogRead(PotenciometrPin);
 lcd.print("Ustonovit`: ");
 val = map(val, 0, 1023, 0, 100);
 lcd.print(val);
 int(sensor);
 // if(val = sensors){ <-- THIS PROBLEM
 //digitalWrite(Rele, LOW);
 // }
 lcd.setCursor(0, 1);
 lcd.print("Fakt: ");
 lcd.print(sensors.getTempCByIndex(0));
 delay(1000);
}
```

title: 18b20 dallastemperature

Answers: 0


body:
I'm trying to making a traffic light for my school project but my button for the traffic light doesn't work. The traffic lights should light up normally but when the button is pressed all LEDs should go to LOW but that does not happen. Did I connect my buttons incorrectly?

Code:
```code
int Pins[] {2,3,4,5,6};
int red =2;
int yellow=3;
int green = 4;
int GruenF =6;
int RotF=5;

int blaulichtTaster = 12;
int blaulichtTasterStellung = 0;

void setup() {
  for(int i=0;i<9; i++) {
  pinMode(Pins[i], OUTPUT);
}
  pinMode(blaulichtTaster, INPUT);

}
void loop() {

  blaulichtTasterStellung = digitalRead(blaulichtTaster);

  if(blaulichtTasterStellung == 0){
    digitalWrite(red, HIGH);
  delay(3000);
  digitalWrite(GruenF, HIGH);
  digitalWrite(RotF,LOW);
  delay(4000);
  for(int i =0;i<4;i++) {
    digitalWrite(GruenF,LOW);
    delay(500);
    digitalWrite(GruenF,HIGH);
    delay(500);
  }
  digitalWrite(GruenF,LOW);
  digitalWrite(RotF, HIGH);
  delay(3000);
  digitalWrite(yellow,HIGH);
  delay(4000);
  digitalWrite(red,LOW);
  digitalWrite(yellow,LOW);
  digitalWrite(green, HIGH);
  delay(10000);
  digitalWrite(green, LOW);
  delay(500);
  for(int i = 0; i<3; i++) {
    digitalWrite(green, HIGH);
    delay(500);
    digitalWrite(green, LOW);
    delay(500);
  }
  digitalWrite(green, HIGH);
  delay(500);
  digitalWrite(green, LOW);
  digitalWrite(yellow, HIGH);
  delay(4000);
  digitalWrite(yellow, LOW);
  }

  else{
    digitalWrite(red,LOW);
    digitalWrite(yellow,LOW);
    digitalWrite(green,LOW);
    digitalWrite(RotF,LOW);
    digitalWrite(GruenF,LOW);
  }

}
```

My circuit:
[![enter image description here][1]][1]

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

title: Why is my button not working?

Answers: 0


body:
https://arduino.stackexchange.com/questions/75846/im-trying-to-use-a-e18-d80nk-but-the-output-is-always-1/81953#81953

Referring to the above link. I am facing the same problem. But unfortunately there is no solution in the given link. My code goes as follows:
```
#define SENSOR 2 // define pint 2 for sensor
void setup() {
  Serial.begin(9600);// setup Serial Monitor to display information
  pinMode(SENSOR, INPUT_PULLUP);// define pin as Input  sensor
}

void loop() {

  int L =digitalRead(SENSOR);// read the sensor

      if(L == 0){
    Serial.println(" Obstacle detected");

     }else{

     Serial.println("  === All clear");

     }
  delay(500);

}
```
Wiring:
```
Brown = 5V
Black = INPUT
Blue = Gnd
```
This is always giving me '=== All clear' as output. Also, would like to mention that, I bought a new sensor recently. Now i doubt is it a defective piece.
Could you please help.

title: Trying to interface E18-D80NK sensor but the output is always one - what to do?

Answers: 0


body:
I'm working on an ESP8266 module that needs to fetch date data from [worldtimeapi](http://worldtimeapi.org/api/timezone/Region/City), everything works fine but the problem is **How do I strip of the time field off the datetime JSON response without loop**.

**Note:** Arduino JSON library was used in deserializing the response data and it seems the library only supports `char` data type.

``` lang-c++
void loop ()
{
  // Initialize the request object
  HTTPClient request;

// Make a http request
  request.begin(dateTime);
  delay(2000);

  // Check the request status code.
int  responseCode = request.GET(); //Get the api host response code.
  Serial.print("Response code is: ");
  Serial.println(responseCode);
  if (responseCode == 200); // If the server returned OK
  {
      String responseData = request.getString();
      Serial.println("Response from the server is:");
      Serial.println(responseData);
        // Deserialize the JSON response data
       StaticJsonDocument<715> result; // Declare data storage to stack

      //Check for error during data deserialization
      DeserializationError error = deserializeJson(result, responseData);

      if (error)
      {
        Serial.print(F("Response deserialization failed with reason: "));
        Serial.println(error.f_str());
        return;
      }

      else
      {
        char abbreviation = result["abbreviation"];  // Returns the current time zone abbreviation
        char timezone = result["timezone"]; // Returns the current time zone
        char datetime = result["datetime"]; // "2021-03-12T17:04:0
        char date = datetime.remove(9,22); // This line throws error : request for member 'remove' in 'datetime', which is of non-class type 'char'

        Serial.print("Current time is ");
        Serial.print(datetime);
        Serial.print(" ");
        Serial.print(abbreviation);
        Serial.print(" ");
        Serial.println(timezone);
        delay(2000);
      }

  }

}
```

title: Remove unwanted characters from char type

Answers: 1

body:
You can use `strtok` to split the string on the T character:

```c++
char *datepart = strtok(datetime, "T");
char *timepart = strtok(NULL, "T");

Serial.print("The current date is: ");
Serial.println(datepart);
Serial.print("The current time is: ");
Serial.println(timepart);
```

An alternative is to just find the `T` and turn it into the NULL terminating character:

```c++
char *T = strchr(datetime, 'T');
*T = 0;
```

----

If you need to copy the string data into a temporary string first you can do:

```c++
char temp[strlen(datetime)+1];
strcpy(temp, datetime);
```

Then operate on `temp` instead of `datetime`.


body:
I'm using the keypad library to return a number 1-9. (im fairly sure this returns an int)
I have an array (data) showing the state of each button press.
so i would like the number returned by the keypad (key) to be the index number that gets edited from 0 to 1 and from 1 to 0.

```c++
    //REMOTE KEYPAD TO CONTROL OUTPUTS OVER SERIAL

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},

};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int iAm = 1;                                    //this is device number 1
float checkSum = 0.00;                          //check sum to send as serial
float voltage = 5.26;                           //system voltage
bool data[8] {0, 0, 0, 0, 0, 0, 0, 0, 0};       //keypad output call

void setup() {
  Serial.begin(9600);
}

void loop() {

  int key = keypad.getKey();

  if (key) {
        data[key] = 1;

    //checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
    //Serial.print(iAm);
    //Serial.print("/");
    Serial.print(data[1]);
    Serial.print("/");
    Serial.print(data[2]);
    Serial.print("/");
    Serial.print(data[3]);
    Serial.print("/");
    Serial.print(data[4]);
    Serial.print("/");
    Serial.print(data[5]);
    Serial.print("/");
    Serial.print(data[6]);
    Serial.print("/");
    Serial.print(data[7]);
    Serial.print("/");
    Serial.print(data[8]);
    Serial.print("/");
    Serial.print(data[9]);
    Serial.print("/");
    Serial.print(voltage);
    Serial.println("/");
    //Serial.println(checkSum);

  }

}
```

i can edit the index location by typing data[1] = 1 but not as a variable so i suspect an index cant be addressed as int? but i don't know what it should be addressed as or how to change it to that.

title: using a variable to index an array

Answers: 1

body:
not going to pretend i understand why all my keypad numbers are 48 higher than the number printed on the keypad but:

    int key2 = key -48;

works


body: Is there any option how to control amplification ratio of operational amplifier by some logic signal which can be produced by arduino? I am talking about some clasic op amp like lm356 or ui741 in basic inverting or non-inverting circuit (i would like to use non-inverting circuit in my application). I know only about digital potentiometer like solution but i think that it isn't profesional and most eficient solution, so I want to know your opinion. Thanks for reply.

title: Controlling op amps amplification ratio by arduino

Answers: 1

body:
The basic principle is easy to implement.  A non-inverting configuration has a resistor Ri from the inverting input to ground, and a feedback resistor Rf from the same input to the output.  The signal is applied to the non-inverting input.  The gain is 1+Rf/Ri.  You can control the gain by changing Ri, which can be done via a CD4016 quad analog switch and 4 resistors.
HOWEVER, the Arduino is a 0-5V device.  The CD4016 can handle 15V, but to switch it the digital input must pass through half the supply.  The op-amps you mention will require bipolar supplies to handle AC signals (which I assume is what you want), so you could run them with +/-7.5V, with the CD4016 powered between them.  Then to get the Arduino 0-5V to toggle the CD4016 you'd need some level-shifting transistors to get it to +/-7.5.  The upshot is that this is surely going to be more trouble than it's worth.

However, if you are willing to drop the ancient op-amps and use a modern single-supply type (MCP6021, LT1013, etc) that runs on 0-5V, you can use input and output capacitors to convert the signal to AC, then just use the CD4016 as-is. Or JFET transistors, or even bipolars to switch the gain resistor under Arduino control if you don't need audiophile quality.


body: Atmega 328PU crash on 5v/1A. Why? It works on 5V/400ma but when i switch it to 5V/1A power it crash. Any idea or solution for this?

title: Atmega 328P U crash on 5V/1A

Answers: 1

body:
Nothing wong, if your power supply is trustworthy enough, then , if u even provide 100000 Amps of current with 5 volt,
 your IC won't burn, in your case , it burnt because your power supply seems to be defective, and please check the voltage of the power supply which is supposed to be defective, so it output more than 5 volts burning or crashing your ic...

Note:

I have personally worked with 5 volt 6 amp power supply which is very well precise and my ic is working full fledged without any problems.


body:
I'm having trouble with these variables. As you can see they're uint32_t type, so they should have a maximum value of 4 million or so, but they're rolling over and going negative at 32,767 like a signed int. Here's the relevant code:

```
byte lPin = 7;
char buff[100];
uint32_t loAvg = 0;
uint32_t hiAvg = 0;

void setup() {
  pinMode(lPin, OUTPUT);
  digitalWrite(lPin, HIGH); // Active LOW, so this is off

  Serial.begin(9600);
  // Generate high/low averages
  for(int i = 0; i < 100; i++) {
    loAvg += analogRead(A0);
  }
  loAvg /= 100;

  digitalWrite(lPin, LOW);
  delay(500);

  for(int i = 0; i < 100; i++) {
    hiAvg += analogRead(A0);
  }
  hiAvg /= 100;

  digitalWrite(lPin, HIGH);
  delay(500);

  sprintf(buff, "loAvg=%d, hiAvg=%d", loAvg, hiAvg);
  Serial.println(buff);

  Serial.println(hiAvg);
  digitalWrite(lPin, LOW);
  hiAvg = 0;
}

void loop() {
  sprintf(buff, "test=%d", hiAvg);
  Serial.println(buff);
  hiAvg+=100;
}
```

I removed a bunch of stuff from the code to save posting the whole (much longer) thing. If it ends up being relevant I can though, I just think I narrowed the problem down to this. Observing the serial monitor I get this on startup:

```
loAvg=287, hiAvg=0
933
test=0
test=100
test=200
...
```

The `test=#` repeats until 32700, then continues at -32736. I'm confused by the hiAvg=0 followed by the 933, showing that it totally is getting a high average, because that's around what it should be. Even if it's the sprintf() messing with it, in the setup function the value should only be around the 900 range so it wouldn't overflow there. Any ideas anyone?

title: Strange behavior from uint32_t, acting like signed int (Nano clone)

Answers: 2

body:
`%d` expects a signed int. `%u` expects an unsigned int. Insert the `l` modifier to expect a long in each of those cases. So you need a format code of `%lu` to print a uint32_t.

The following code:

    #include <Arduino.h>

    void setup()
    {
     uint32_t x=110000;
     char buf[50];

       // Open console
       Serial.begin(115200);

     sprintf(buf, "%%d: %d\n", x);  Serial.print(buf);
     sprintf(buf, "%%u: %u\n", x);  Serial.print(buf);
     sprintf(buf, "%%ld: %ld\n", x); Serial.print(buf);
     sprintf(buf, "%%lu: %lu\n", x); Serial.print(buf);
    }

    void loop() {
       ;
    }

prints this:

    %d: -21072
    %u: 44464
    %ld: 110000
    %lu: 110000

body:
*`printf` and bit-width specified types
---------------------------------------

`#include <inttypes.h>` or C++'s `#include <cinttypes>` counterpart (when you have it; not on AVR-based Arduinos) gives access to macros defined for the format specifiers for each of the fixed, fast, and least versions of these types.  All of these macros expand to some string literal or another.

For `uint32_t` the macro defining to its format specifier is `PRIu32`.  For an AVR, this is `"%lu"`.  It needn't be `"%lu"` in  the general case.  `uint32_t` is one of the types where you can often get away with using `"%lu"` and have it either work out being exactly correct for the platform or somewhat incorrect but working anyway because it's a platform where `unsigned int` and `unsigned long` happen to have the same representation.

In C and C++, and so Arduino, adjacent string literals are concatenated into one logical string in the early phases of compilation that follow the macro preprocessor.  So, the intention is that you choose the correct macro and you put them following something like `"%"` or `""` if you wanted a minimum-width of 12.  As in `"%" PRIu32` and `"" PRIu32` respectively.  So, in your case,  having included (directly or indirectly) `<stdint.h>` for `uint32_t` and `<inttypes.h>` for `PRIu32` or their C++ counterpart headers, and then your code looks something like:

```c++
snprintf(
  buf,
  sizeof buf,
  "loAvg=%" PRIu32 ", hiAvg=%" PRIu32,
  loAvg,
  hiAvg
);
```

There's little to no reason to not use the s**n**printf.  The reason why the non-n version exists at all is mostly that `snprintf` showed up in 1999, instead of circa the mid 1970s.  I'd say it's pretty safe to use `snprintf` now.  There probably hasn't been an Arduino that doesn't support it.  About the only reason to use `sprintf` would be if you were calling it with a null pointer for the buffer argument to get it to do a dry run and tell how much memory you need for the result, and you just didn't want to supply a limiting size.

There are `PRI...` [macros for all of the combinations][1] of standard bit width and choice of signed decimal, unsigned decimal, lowercase hex, uppercase hex, etc.  E.g `"%" "PRId16"` is  for `int16_t` in decimal, `"%" PRIX64` for `uint64_t` in hexadecimal with uppercase alphabetics.  The are ones for the `fast` and `least` bitwidth types, and whole show is repeated with macros starting with `SCN` for the `scanf` specifiers, not that you should use the `scanf` family functions for anything really.

`snprintf` and `sprintf` are variadic functions.  After the format specifier there's no type information available to the compiler to know what conversions to apply.  It will convert types smaller than `int` rank up to `int` on `unsigned int`, but that's about it.  E.g. it will not reliably down-convert an `unsigned long long` into an `unsigned int`, the way it would if the types were known.  Modern compilers will sometimes warn you if you grossly misapply format specifiers, but they're not required to.  They're not expected to dissect the format string and attempt to recover type information.  So it's up to you to make sure whatever you pass in for arguments matches with the format specifiers.  As you've seen it's confusing if you get it wrong with `printf`-type functions, but it doesn't cause real problems unless you, you know, don't limit it to stay within the output buffer with the s**n**printf version.  In the case of passing in an `unsigned long long` where an `unsigned int` was expected, in practice, for a little-endian system like AVR, it may appear to do that for one argument.  But then it may fail on the next argument, because the size of the last argument was in correct, it is now reading from the wrong place.

`Print`/`Stream`/`Serial` concatenating and buffering
-----------------------------------------------

The way you're using `sprintf` in your code isn't taking advantage of any of its features that `Serial`/`Print` doesn't do.

```c++
Serial.print(F("loAvg="));
Serial.print(loAvg);
Serial.print(F(", hiAvg="));
Serial.println(hiAvg);
```

Despite taking four lines, this is actually smaller, faster, more reliable code than the `sprintf` one-liner.

Putting the output into a buffer first might make sense if you were going to put it into a packet, like for UDP or nRF24L01.  But, `Print`/`Stream`/`Serial` already concatenates and buffers things for you.

---

Incidentally, if you're going to use `printf` functions and you're doing it on an AVR-based Arduino, look at the avr-libc [documentation for the `_P` variants][2] that take their format strings from PROGMEM and the [`PSTR` macro][3].

It is also possible to complete the implementation of `<stdio.h>` for `stdout` and `stderr` through libc-specific means.  So, if you really want to, you can have the regular `printf` function pushing data out through `Serial` (among other things) such that you *don't* need to buffer repeatedly with `sprintf`.

  [1]: https://en.cppreference.com/w/cpp/header/cinttypes
  [2]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html
  [3]: https://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html#ga05ca900ebf7cd121be73c654d9ccb3eb


body:
I just bought a KS0354 ESp8266 board to make a remote control for my iot project. Not sure why I keep on getting a wdt error. Even before I can complete my entire code I start getting this error. Below is my code:

    int PIN_BUTTON_A = 2;
    int PIN_BUTTON_B = 3;
    int PIN_BUTTON_C = 4;
    int PIN_BUTTON_D = 5;
    int PIN_BUTTON_E = 6;
    int PIN_BUTTON_F = 7;

    void setup() {
      Serial.begin(9600);
      pinMode(PIN_BUTTON_B, INPUT);
      pinMode(PIN_BUTTON_E, INPUT);
      pinMode(PIN_BUTTON_C, INPUT);
      pinMode(PIN_BUTTON_D, INPUT);
      pinMode(PIN_BUTTON_A, INPUT);
    }

    void loop() {
       Serial.print("Buttons A:");
       delay(5000);

    }

This seems to be a very simple code. Not sure what is wrong here. Below is the error I am getting @115200 baud rate:

     ets Jan  8 2013,rst cause:4, boot mode:(3,6)

    wdt reset
    load 0x4010f000, len 3584, room 16
    tail 0
    chksum 0xb0
    csum 0xb0
    v2843a5ac
    ~ld
Does anyone has any idea what could be wrong?
Thanks

title: ESP8266 wdt reset

Answers: 0


body:
I did a project with an Arduino Leonardo and a fingerprint sensor (DY50).
When I uploaded the ```enroll``` example from the ```Adafruit Fingerprint Library``` and saved my fingerprint, everything worked. But when I upload my code, it doesn't print anything.

**My Code**
```
#include <Keyboard.h>
#include <Adafruit_Fingerprint.h>
#define mySerial Serial1

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
int fingerprintID = 0;
String inData;
bool isRight;
int pos;

//Number of services to log in
#define servNum 5

//Login URLs for Google, Amazon, Stackoverflow, Arduino and Github
String LogInURL[] = {"https://accounts.google.com/signin", "https://www.amazon.de/ap/signin", "https://stackoverflow.com/users/login", "https://login.arduino.cc/", "https://github.com/login"};
String LogInUser[] = {"user.name@gmail.com", "user.name@example.com", "user.name@example.com", "username", "username"};
String LogInPwd[] = {"password", "password", "password", "password", "password"};

void donothing() {};

void StepsBefore(int serviceNum){
  switch(serviceNum){
    case 0: donothing(); break;
    case 1: donothing(); break;
    case 2: for(int k=0; k<18; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 3: for(int k=0; k<2; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 4: donothing(); break;
    default: Serial.println("Error: Number not recognized."); break;
  }
}

void StepsAfter(int serviceNum){
  switch(serviceNum){
    case 0: Keyboard.println(); break;
    case 1: Keyboard.println(); break;
    case 2: Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 3: Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 4: for(int k=0; k<2; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    default: Serial.println("Error: Number not recognized."); break;
  }
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with confidence of ");
  Serial.println(finger.confidence);
  return finger.fingerID;
}

void askForFingerprint() {
  fingerprintID = getFingerprintIDez();
    delay(50);
    if(fingerprintID == 1){
      isRight = true;
    }
}

void delAfterChar(String inString, String fromToKill){
  pos = inString.indexOf(fromToKill);
  inString.remove(pos, 1000);
  inData = inString;
}

void setup() {
 Serial.begin(115200);
 Serial.println("Debug 1");
 Keyboard.begin();
 Serial.println("Debug 2");
 finger.begin(57600);
 Serial.println("Debug 3");
    if(finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
    }
    else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
    }
}
void loop() {
  inData = Serial.read();
  delAfterChar(inData, "?openid"); //Amazon
  delAfterChar(inData, "/v2/"); //Google
  delAfterChar(inData, "?ssrc"); //Stackoverflow
  delAfterChar(inData, "login?state"); //Arduino
 for (int i=0; i<servNum; i++){
     if(inData == LogInURL[i]){
        askForFingerprint();
        if(isRight == true){
           StepsBefore(i);
           Keyboard.print(LogInUser[i]);
           StepsAfter(i);
           Keyboard.println(LogInPwd[i]);
        }
        else Serial.println("Finger not recognized");
     }
 }
}
```
**What I've tried so far**

 - I changed the baud rate from ```9600``` to ```15200```, didn't help
 - Added a few debug points in the ```setup``` to check for an error there, nothing changed
 - Uploaded a simple Hello World via Serial Monitor sketch, worked perfectly

**Question**

What could be the issue? It compiles with no error message. If you see any coding mistakes, feedback would be great.

**EDIT**

Using ```SoftwareSerial``` instead didn't help either.

title: Arduino Leonardo doesn't print anything to Serial Monitor with my specific code

Answers: 1

body: As @Juraj pointed out, I just forgot to use ```while (!Serial)``` in the ```setup```, probably because I use other boards that don't need this more often.