# Question
Title: How can I do web hosting having all the code of the site stored on an SD?
I am carrying out this project in which the Arduino acts as a web server and hosts a website in which I show the constantly updated temperature of a laboratory.

The problem is running all this code in the Arduino: memory runs out easily.

```
void loop() {
  int value = analogRead(PIN_LM35);
  float temperature = value / 2.046;
  myFile = SD.open("temperature.txt");
  if (myFile) {
    Serial.println(temperature);
  }
  myFile.close();

  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {
          Serial.println(readString); //print to serial monitor for debuging

          client.println(F("HTTP/1.1 200 OK")); //send new page
          client.println(F("Content-Type: text/html"));
          client.println();
          refreshcounter = refreshcounter + 1;
          client.println(F("<HTML>"));
          client.println(F("<HEAD>"));
          client.print(F("<meta http-equiv=\"refresh\" content=\"2\">"));
          client.println(F("<meta name='apple-mobile-web-app-capable' content='yes' />"));
          client.println(F("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />"));
          client.println(F("<TITLE>TEMPERATURE SENSOR LAB01</TITLE>"));
          client.println(F("</HEAD>"));
          client.println(F("<BODY>"));
          client.println(F("<H1>TEMPERATURE SENSOR LAB01</H1>"));
          client.println(F("<hr />"));
          client.println(F("<br />"));
          client.println(F("<H2>Arduino with Ethernet Shield</H2>"));
          client.println(F("<br />"));
          if (temperature < 24) {
            client.println("<p style=\"font-size:50px; color:#8eff59; font-weight:bold; font-style:italic;\">");
            client.println(temperature);
            client.println("</p>");
          }
          else if (temperature >= 24 && temperature <= 26) {
            client.println("<p style=\"font-size:50px; color:#ffbc03; font-weight:bold; font-style:italic;\">");
            client.println(temperature);
            client.println("</p>");
          }
          else {
            client.println("<p style=\"font-size:50px; color:#ff0303; font-weight:bold; font-style:italic;\">");
            client.println(temperature);
            client.println(F("<H2>It is recommended to activate the air conditioner.</H2>"));
            client.println("</p>");
          }
          client.println(F("<p style=\"font-size:30px; color:#000000; font-weight:bold; ;\">Date/Time: <span id=\"datetime\"></span></p>"));
          client.println(F("<script>"));
          client.println(F("var dt = new Date();"));
          client.println(F("document.getElementById(\"datetime\").innerHTML = "
                "((\"0\"+dt.getDate()).slice(-2)) +\".\"+ ((\"0\"+(dt.getMonth()+1)).slice(-2)) "
                "+\".\"+ (dt.getFullYear()) +\" \"+ ((\"0\"+dt.getHours()).slice(-2)) +\":\"+ ((\"0\"+dt.getMinutes()).slice(-2));"));
          client.println(F("</script>"));

          client.println("<svg width=\"1000\" height=\"250\">");
          client.println("<rect width=\"150\" height=\"5\" fill=\"gray\">");
          client.println("<animate attributeName=\"x\" from = \"0\" to =\"10000\" dur=\"10s\" fill=\"freeze\" />");
          client.println("</rect");
          client.println("</svg>");

          client.println("<br />");
          client.println("</BODY>");
          client.println("</HTML>");

          delay(1);
          //stopping client
          client.stop();
          //clearing string for next read
          readString = "";
        }
      }
    }
  }
}

```

I put all the code of the web page on an external SD card to save memory. However, I don’t really know how to use it from the SD card.

The problem that stops me is the fact that the site is not static, but is constantly updated with new temperature data.

How can I do that?

# Answer
You wrote:

> the site does not have to be static but constantly updated with new temperature data.

A good option is to use Ajax. The basic idea is to split the site in two parts:

* a static part, potentially large, which contains all the user interface, the styling, the bells and whistles...
* a tiny, dynamic part that contains the data that is constantly updated *and nothing more*.

The static part would be served from the SD card when the client sends a `GET /` request. The dynamic part would be served from another endpoint, for example as a reply to `GET /temperature`. Serving the dynamic part should be very simple, something like:

```
client.println(temperature);

```

Yes, just send the number as ASCII, no HTML formatting. If you ever need to send more than one number (e.g. multiple temperatures, or temperature and humidity), format them in JSON. No need to use a library for that, plain `print()` should be cheaper and good enough:

```
client.print(F("{\"temperature\":"));
client.print(temperature);
client.print(F(",\"humidity\":"));
client.print(humidity);
client.print('}');

```

On the client side, `JSON.parse()` gets the data back as an easy-to-use data structure.

Here is a minimal example of what the static part could look like. Notice the JavaScript code sent to the client. This code is responsible for querying the temperature every 1000 milliseconds, and updating the Web page with the new data;

```
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ajax test</title>
</head>
<body>

<h1>Ajax test</h1>

<p>Temperature: <span id="temperature">---</span> °C</p>

<script>
var data_field = document.getElementById("temperature");
setInterval(function() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState != 4) return;
        data_field.innerText = JSON.parse(request.responseText);
    };
    request.open("GET", "/temperature");
    request.send();
}, 1000);
</script>
</body>
</html>

```

A few notes:

* This example is purposefully minimal. You may want to add some error checking, some decorations, some CSS and the such. Handling a temperature-dependent color also belongs to the client code.
* The example uses good old `XMLHttpRequest`. You may want to try the more modern fetch API instead:

```
setInterval(function() {
    fetch("/temperature")
        .then(response => response.json())
        .then(data => { data_field.innerText = data; });
}, 1000);

```
* If you are sending updates frequently enough to significantly load your Arduino, you may want to look at Server-sent events. This is a technique that allows you to significantly reduce the overhead of sending data updates. It is not as popular as Web-sockets, but has the advantage of being simpler to implement server-side.
* If you can put a reverse-proxy between your Arduino and the Internet, the proxy can handle the static content. Your Arduino then only handles the dynamic data and wouldn't need an SD card. If you reverse-proxy Server-sent events, make sure the proxy doesn't buffer the server response. See for example these tips on configuring Nginx for this purpose.
* The static data could also be served from a completely different Web site. For this to work, you have to fulfill two conditions:

1. The Arduino server has to add the header `Access-Control-Allow-Origin: *` to its responses.
    2. On the client code, you have to provide the full URL of the Arduino as an argument of `request.open()`, `fetch()` or `new EventSource()`.
* The previous trick also allows you to open the Web page directly from your local file system, which can be very handy for developing.
* Once you get the basic scheme working, Web technologies allow you to get as fancy as you want. You could create an analogue gauge (with SVG transform rotate). You could even add a graph, updated in real time, that shows the time evolution of the temperature, and is entirely handled by the client.
> 6 votes

---
Tags: sd-card, web-server
---


# Question
Title: How to use two timers 1 and 4 simultaneously in Arduino Mega 2560
I activated timer 1 and its interrupt on the 2560 board and it works properly. Now I want to run Timer 4 as well. I installed the Timer 4 library, but when I compile the program, I get the following error. This error also occurs for timers 3 and 5:

```
C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp:110:6:
note: 'void startSlowCountingTimer5()' previously defined here
 void startSlowCountingTimer5(void) {

```

Thank you for your help.

The full text of the error is as follows

```
C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp: In function 'void startSlowCountingTimer5()':

C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp:127:6: error: redefinition of 'void startSlowCountingTimer5()'

 void startSlowCountingTimer5(void) {

C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp:110:6: note: 'void startSlowCountingTimer5()' previously defined here

 void startSlowCountingTimer5(void) {

```

# Answer
This is a bug in the library that was fixed in 2017! Please upgrade.
> 2 votes

---
Tags: library
---


# Question
Title: Arduino compiler shows different value of sram memory
I have this code that shows the available sram memory

```
    int freeRam()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

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

void loop()
{
}

```

The arduino compiler shows a different value.

* the arduino compiler shows 1856 bytes and
* Serial port shows 1850 bytes

What is the correct value?

# Answer
Both are correct depending on what value you are interested in. The compiler tells you the size of the global variables. Your code tells you how much memory is free at any one time. Running code requires memory (most often the stack growing to accommodate local variables and the "stack frame" with a copy of the CPU registers in it every time you call a function).

In other words the compiler tells you how much is in your glass when it's handed to you by the barman but your code tells you how much is in there once you have taken a sip.
> 3 votes

---
Tags: arduino-uno
---


title: ESP32 Wipe Sensitive Key Data

text:
# Question
Title: ESP32 Wipe Sensitive Key Data
Is it possible to ensure that keys (e.g. ssid, ssl certs) are wiped from the memory of a esp32?

I'm new to the esp32, coming from a IoT device security perspective.

Say a person was testing an esp32 application that utilized WIFI, in which sensitive keys are embedded in the firmware. They then overwrote the esp32 with a small led blink firmware in an attempt to clear said keys.

I would like to know if flashing a small "blink" program will be sufficient to remove the keys, so the esp32 could be repurposed without worry that a firmware dump would reveal past firmware information.

This question is specifically targeting scenarios where the esp32 is for development purposes (fuse bits are never burnt - mind I think there is a security flaw where chip can be dumped anyhow).

# Answer
You can use `esptool.py` to run an `erase_flash` operation.

> **Erase Flash: erase\_flash & erase\_region**
>
> To erase the entire flash chip (all data replaced with 0xFF bytes):
>
> ```
> esptool erase_flash
>
> ```
>
> To erase a region of the flash, starting at address 0x20000 with length 0x4000 bytes (16KB):
>
> esptool erase\_region 0x20000 0x4000
>
> The address and length must both be multiples of the SPI flash erase sector size. This is 0x1000 (4096) bytes for supported flash chips.
>
> *-- esptool basic commands*

As far as copy protection goes you can encrypt the flash contents so even if the chip is read directly without the decryption key they won't be able to make any sense of the data.
> 2 votes

---
Tags: esp32, security
---


# Question
Title: Getting more Hz while working with 3 serial ports (IMU sensors)
im doing a university project where we use 2 IMU sensors and a SD card reader to save the data from sensors.

As you will probably see from the code, we specify the sensor port we listen to, save data to strings and then we open a port to SD reader and save the data. Everything is in loop.

The problem is we only get around 5Hz (10Hz with only one sensor) - visible by the timer, which is sadly not enough for our project.

I heard about using a fifo buffer, but im not so good at low level programing. Anyway you can help? Also, do you think removing all Serial.print could help with a little performance boost?

sensors - https://wiki.dfrobot.com/Serial\_6\_Axis\_Accelerometer\_SKU\_SEN0386#target\_0

uCon - Arduino Uno Rev3

```
#include <DFRobot_WT61PC.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

#define FILE_BASE_NAME "Pomiar"
#define VCC2 7

const uint8_t CS_PIN = 4;

SoftwareSerial mySerial(2, 3);
SoftwareSerial mySerial2(5, 6);
DFRobot_WT61PC sensor(&mySerial);
DFRobot_WT61PC sensor2(&mySerial2);

File myFile;
File file;

const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[] = FILE_BASE_NAME "00.txt";

void setup()
{

  pinMode(VCC2,OUTPUT);
  digitalWrite(VCC2,HIGH);

  //Use Serial as debugging serial port
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }

  //Use software serial port mySerial as communication seiral port
  mySerial.begin(9600);
  mySerial2.begin(9600);
  //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz,
  //                        FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz,
  //                        FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz.
  sensor.modifyFrequency(FREQUENCY_100HZ);
  sensor2.modifyFrequency(FREQUENCY_100HZ);
}

void loop()
{

  long timestamp = millis();

  String acc1 = "";
  String acc2 = "";
  String acc3 = "";
  String gyro1 = "";
  String gyro2 = "";
  String gyro3 = "";
  String angle1 = "";
  String angle2 = "";
  String angle3 = "";

  String acc12 = "";
  String acc22 = "";
  String acc32 = "";
  String gyro12 = "";
  String gyro22 = "";
  String gyro32 = "";
  String angle12 = "";
  String angle22 = "";
  String angle32 = "";

  mySerial.listen();
  if (sensor.available()) {

    acc1 = sensor.Acc.X;
    acc2 = sensor.Acc.Y;
    acc3 = sensor.Acc.Z;
    gyro1 = sensor.Gyro.X;
    gyro2 = sensor.Gyro.Y;
    gyro3 = sensor.Gyro.Z;
    angle1 = sensor.Angle.X;
    angle2 = sensor.Angle.Y;
    angle3 = sensor.Angle.Z;

    Serial.print("Acc\t"); Serial.print(sensor.Acc.X); Serial.print("\t"); Serial.print(sensor.Acc.Y); Serial.print("\t"); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro\t"); Serial.print(sensor.Gyro.X); Serial.print("\t"); Serial.print(sensor.Gyro.Y); Serial.print("\t"); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle\t"); Serial.print(sensor.Angle.X); Serial.print("\t"); Serial.print(sensor.Angle.Y); Serial.print("\t"); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }

  mySerial2.listen();
  if (sensor2.available()) {

    acc12 = sensor2.Acc.X;
    acc22 = sensor2.Acc.Y;
    acc32 = sensor2.Acc.Z;
    gyro12 = sensor2.Gyro.X;
    gyro22 = sensor2.Gyro.Y;
    gyro32 = sensor2.Gyro.Z;
    angle12 = sensor2.Angle.X;
    angle22 = sensor2.Angle.Y;
    angle32 = sensor2.Angle.Z;

    Serial.print("Acc2\t"); Serial.print(sensor2.Acc.X); Serial.print("\t"); Serial.print(sensor2.Acc.Y); Serial.print("\t"); Serial.println(sensor2.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro2\t"); Serial.print(sensor2.Gyro.X); Serial.print("\t"); Serial.print(sensor2.Gyro.Y); Serial.print("\t"); Serial.println(sensor2.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle2\t"); Serial.print(sensor2.Angle.X); Serial.print("\t"); Serial.print(sensor2.Angle.Y); Serial.print("\t"); Serial.println(sensor2.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc1);
    myFile.print("|");
    myFile.print(acc2);
    myFile.print("|");
    myFile.print(acc3);
    myFile.print("|");
    myFile.print(gyro1);
    myFile.print("|");
    myFile.print(gyro2);
    myFile.print("|");
    myFile.print(gyro3);
    myFile.print("|");
    myFile.print(angle1);
    myFile.print("|");
    myFile.print(angle2);
    myFile.print("|");
    myFile.print(angle3);
    myFile.println("");

    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc12);
    myFile.print("|");
    myFile.print(acc22);
    myFile.print("|");
    myFile.print(acc32);
    myFile.print("|");
    myFile.print(gyro12);
    myFile.print("|");
    myFile.print(gyro22);
    myFile.print("|");
    myFile.print(gyro32);
    myFile.print("|");
    myFile.print(angle12);
    myFile.print("|");
    myFile.print(angle22);
    myFile.print("|");
    myFile.print(angle32);
    myFile.println("");

    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
}

```

# Answer
> 0 votes
There is a memory device called FRAM, It is available in many sizes. I work with 32Kx8 which is under $5.00 US from my favorite china supplier. No write delays, works with SPI or I2C you can get either already mounted on a PCB. For you I would recommend SPI. It is non volatile memory so it will retain the date when power fails. It is good for over 1 trillion cycles.

---
Tags: arduino-uno, serial, c++, frequency, imu
---


title: how to save float with 3 decimal places

text:
# Question
Title: how to save float with 3 decimal places
i am transmitting sensor data from my atmega328p to my esp8266. The Sensordata has 3 decimal places. The esp8266 sends this data to my pc and there I see only two digits. This is because the data is saved with two digits in the float variables. Is there a way to save them with 3? The way to multiply and later to divide does not work because of some issues on my pc server so I need to hand it straight with 3 digits.

# Answer
> 1 votes
> This is because the data is saved with two digits in the float variables.

No, it's not. It's because `Serial.println()` by default prints only 2 decimal places. You can specify the number of decimal places to print in the function:

```
Serial.println(myVal, 3);

```

---
Tags: arduino-uno, esp8266, variables, float
---


# Question
Title: How to connect two LED strips (APA102/SK9822) to Arduino UNO?
So what I am trying to do is to connect two SK9822 LED strips to Arduino UNO.

I am a bit confused about how to properly set this up so I can individualy control any led. So obviously 5V should go to 5V and GND to GND, but what about the CLOCK and the DATA pin.

According to the tutorials and stuff I found here, CLOCK pin needs to be connected to pin 13 and DATA to pin 10, but they only use one strip... so what I am trying to ask is can LED strips share pins? Can they be connected to the same CLOCK pin and different DATA pins or how can i set this up to use the minimum amount of pins?

I was planning on using FastLED library, where it looks like you can specify which pin is DATA and which is CLOCK,

```
FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN>(leds, NUM_LEDS);

```

Is this because different boards have different CLK and MOSI pins or can i use any pin and set it as CLOCK or DATA? This is probably obvious but I am new to this and this is my first project.

# Answer
> 1 votes
I don't know about SK9822 LED strips, however the other type of led strips can be used with every pin; this is to support multiple LED strips.

Because every LED strip has its own CLK input (wire), it would be inconvenient to share them... I'm not sure if it is possible practically, because the timing is critical and if you have just one 'master' CLK signal than the data signals for all LED strips should be sent in time. Also writing the library would be more difficult, since there is a relation between a (shared) CLK signal and other data lines.

# Answer
> 1 votes
For minimum pins, daisychain them together, with the clock and data outputs on the tail end of the first strip connecting to the clock and data inputs on the second strip.

https://www.pololu.com/product/3089 says:

> Multiple LED strips can be chained together by connecting input connectors to output connectors. When strips are chained this way, they can be controlled and powered as one continuous strip.

---
Tags: arduino-uno, spi, rgb-led, led-strip
---


title: Calculating Amp/Hrs of a solar panel

text:
# Question
Title: Calculating Amp/Hrs of a solar panel
I am interested in calculating the amp/hour output of a solar panel using an Arduino. I am confident I can get the voltage (with a voltage divider) & the amperage (with an ACS712). My question is about the math of calculating Amp\*hour.

**Here is my plan:**

1. My plan is to pull the voltage and amperage every second.
2. I would then add this amp\*second value to a variable. I would also increment another variable for each second.
3. I would then be able to get an average or total of Amp*seconds from these 2 variables. I could also divide the amp*second by 3600 if I wanted Amp\*Hour.

**Is it too much a stretch to poll the amperage every second and call it amp/second? How can I make this more accurate?**

# Answer
> 6 votes
## How to make your own coulomb counter (Amp\*hours \[Ahr\] meter, or Watts\*hours \[Whr\] energy meter) with an Arduino

## Quick summary:

Jump straight down to the "Full coulomb counter example in code" section if you just want the final answer.

## Details

There are a lot of misunderstandings here, but here is the gist of it.

What you want to do is a perfect application of an Arduino. No need to buy a coulomb counter, instead, you should **make one** with your Arduino.

> I would then add this amp/second value to a variable.

First correction, it's an **amp\*second**, NOT an amp/second. You are multiplying amps by the number of seconds that current value existed.

amp\*seconds / 3600 = amp\*hours. Read about that here: https://en.wikipedia.org/wiki/Ampere\_hour. Multiply that by the *voltage* over that same time period and you've got amps\*hours\*volts = (amps\*volts)\*hours = Watts\*hours = units of *energy*! Remember, your house electricity it purchased in units of kilowatt hours, which is kilowatts\*hours, or kWhr. And in engineering units a **joule** is the standard unit of energy, and it is simply Watts\*seconds. So, you can convert kWhr to joules like this, where units are in square brackets `[]`.

```
Joules = kWhr * 1000 [Whr/kWhr] * 3600 [sec/hr] = [Watts*sec] = [Joules]

```

So, 1 kWhr x 1000 x 3600 = 3600000 Joules = 3600kJ

> I would also increment another variable for each second.

That doesn't make any sense. Don't do that. You've already captured the seconds by adding your new bit of amps\*seconds to your old sum of it.

DO account for voltage too! What you're really after is *energy*, which can be expressed in units of joules or kWhr, as already described above.

> Is it too much a stretch to **poll** the amperage every second and call it **amp\*second**?

(my corrections in bold)

No, absolutely not! That's *exactly* what an amp\*second is! It's the current, amps, times the number of seconds that current existed. That's a coulomb counter!

### A. Making the coulomb counter as good as possible

> How can I make this more accurate?

This is the part where the engineer and programmer (you) determines the quality of the result.

1. Don't assume 1 second elapsed because you *told it to*. *Measure it* for each and every measurement!
2. The smaller the time interval, the more accurate, since it allows you to capture the small current fluctuations, so use a *smaller time slice* than 1 second. I'd start with 10ms.
3. Measure voltage AND current AND actual time elapsed on this loop as close to the same time as possible.
4. Do NOT use blocking techniques, such as `delay()` or `delayMicroseconds()`.
5. What you're doing when you're multiplying a new amp reading x seconds, and adding it to the previous sum is called *numerical integration*. You're simply numerically integrating, or summing, the area under the Amp (y-axis)-time (x-axis) curve, or, if you're doing what I'm saying to do intead: the Watt (y-axis)-time (x-axis) curve, where the area under the curve is the total energy collected. **Don't do rectangular integration, do *trapezoidal* integration following the *trapezoidal rule*! It's more accurate!**
6. Calibrate your clock! An Arduino's clock can be off by a couple percent. Figure out how much it's off by comparing its clock output over, say, 10 minutes, and comparing it to a better clock source, say...an internet time server displaying the atomic clock in Colorado or wherever it is. Then, multiply each measurement by a scaling factor to fix it!
7. On the same lines as above, ideally you'd also compensate in real-time for temperature, as the clock frequency drifts with temperature.
8. Calibrate the voltage measurement.
9. Calibrate the current measurement.

### B. Extra: when is trapezoidal integration most beneficial?

You might call the following list my **"5 hypotheses about the benefits of trapezoidal integration".**

The merits of trapezoidal integration can be argued, and it's probably not as important as I originally made it sound, but it is *super easy* to implement, so why not!? Also, it is *most important* when:

1. The time sampling rate is *super low*.
2. The rate of change of readings (ie: their derivative, or slope) is *super high*.
3. The readings consistently have a rising slope (rectangular integration \_under\_estimates the area in this case) OR a consistently falling slope (rectangular integration \_over\_estimates in this case).
4. When you care about real-time readings *in this instant*, not just overall trends or averages. This is because trapezoidal integration instantly removes overestimation and underestimation error which can accumulate over short periods but then "de-accumulates", or is negated, over long periods, when the opposite slope occurs in the data.
5. \[*This may apply only when there is jitter in the sample rate--see @Edgar Bonet's comment here*\] When the readings consistently rise at a different rate than they fall, as this results in asymmetric accumulation of error. This means that the rectangular integration error accumulated by the values rising distance `delta_y` will NOT be fully negated by error in the opposite direction when the values fall distance `delta_y`. Therefore, even over long periods, rather than seeing the error negated, it will accumulate more and more over time. \[Note: I'd need to analytically/numerically play with this hypothesis for a while to prove it conclusively to myself, but I'm pretty sure it is correct\].

## Full coulomb counter example in code:

This code is now in my eRCaGuy\_hello\_world repo here: coulomb\_counter\_with\_cooperative\_multitasking\_macro.ino.

Here's a full coulomb counter example in code. You just need to implement a few functions to read samples and do calibrations is all.

I'm borrowing the timestamp-based cooperative multitasking part of this code from my answer about cooperative multitasking here, so go check it out for more information on that.

As written, this code compiles, but I haven't wired anything up or tested it. Here's the compilation output:

> Sketch uses 3750 bytes (12%) of program storage space. Maximum is 30720 bytes.
> Global variables use 262 bytes (12%) of dynamic memory, leaving 1786 bytes for local variables. Maximum is 2048 bytes.

**coulomb\_counter\_with\_cooperative\_multitasking\_macro.ino:**

Jump to the bottom for the `setup()` and `loop()` functions. They are both really short.

<pre><code>/// Coulomb counter example
/// By Gabriel Staples
/// See: https://arduino.stackexchange.com/questions/75932/calculating-amp-hrs-of-a-solar-panel/75937#75937

/// @brief      A function-like macro to get a certain set of events to run at a desired, fixed
///             interval period or frequency.
/// @details    This is a timestamp-based time polling technique frequently used in bare-metal
///             programming as a basic means of achieving cooperative multi-tasking. Note
///             that getting the timing details right is difficult, hence one reason this macro
///             is so useful. The other reason is that this maro significantly reduces the number of
///             lines of code you need to write to introduce a new timestamp-based cooperative
///             task. The technique used herein achieves a perfect desired period (or freq)
///             on average, as it centers the jitter inherent in any polling technique around
///             the desired time delta set-point, rather than always lagging as many other
///             approaches do.
///
///             USAGE EX:
///             ```
///             // Create a task timer to run at 500 Hz (every 2000 us, or 2 ms; 1/0.002 sec = 500 Hz)
///             const uint32_t PERIOD_US = 2000; // 2000 us pd --> 500 Hz freq
///             bool time_to_run;
///             uint32_t actual_period_us;
///             CREATE_TASK_TIMER(PERIOD_US, time_to_run, actual_period_us);
///             if (time_to_run)
///             {
///                 run_task_2();
///
///                 // OR, if `run_task_2()` needs the actual period that just occurred, for
///                 // whatever reason, you may pass it in to your `run_task_2()` function:
///                 run_task_2(actual_period_us);
///
///                 // OR, just do all your code right here instead of in `run_task_2()`
///             }
///             ```
///
///             Source: Gabriel Staples
///             https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992
/// @param[in]  period_desired_us  (uint32_t) The desired delta time period, in microseconds;
///                             note: pd = 1/freq; the type must be `uint32_t`.
/// @param[out] time_to_run     (bool) A `bool` whose scope will enter *into* the brace-based scope block
///                             below; used as an *output* flag to the caller: this variable will
///                             be set to true if it is time to run your code, according to the
///                             timestamps, and will be set to false otherwise.
/// @param[out] actual_period_us  (uint32_t) The actual period, in us, since the last time it was
///                             time to run--ie: since the last time `time_to_run` was set to true.
/// @return     NA--this is not a true function
#define CREATE_TASK_TIMER(period_desired_us, time_to_run, actual_period_us)                                            \
{ /* Use scoping braces to allow multiple calls of this macro all in one outer scope while */                          \
  /* allowing each variable created below to be treated as unique to its own scope */                                  \
    time_to_run = false;                                                                                \
                                                                                \
    /* set the desired run pd / freq */                                                                                \
    const uint32_t PERIOD_DESIRED_US = period_desired_us;                                                              \
    static uint32_t t_start_us = micros();                                                                             \
    uint32_t t_now_us = micros();                                                                                \
    uint32_t period_us = t_now_us - t_start_us;                                                                        \
    actual_period_us = period_us;                                                                                \
                                                                                \
    /* See if it's time to run this Task */                                                                            \
    if (period_us >= PERIOD_DESIRED_US)                                                                                \
    {                                                                                \
        /* 1. Add PERIOD_DESIRED_US to t_start_us rather than setting t_start_us to t_now_us (which many */            \
        /* people do) in order to ***avoid introducing artificial jitter into the timing!*** */                        \
        t_start_us += PERIOD_DESIRED_US;                                                                               \
        /* 2. Handle edge case where it's already time to run again because just completing one of the main */         \
        /* "scheduler" loops in the main() function takes longer than PERIOD_DESIRED_US; in other words, here */       \
        /* we are seeing that t_start_us is lagging too far behind (more than one PERIOD_DESIRED_US time width */      \
        /* from t_now_us), so we are "fast-forwarding" t_start_us up to the point where it is exactly */               \
        /* 1 PERIOD_DESIRED_US time width back now, thereby causing this task to instantly run again the */            \
        /* next time it is called (trying as hard as we can to run at the specified frequency) while */                \
        /* at the same time protecting t_start_us from lagging farther and farther behind, as that would */            \
        /* eventually cause buggy and incorrect behavior when the (unsigned) timestamps start to roll over */          \
        /* back to zero. */                                                                                \
        period_us = t_now_us - t_start_us; /* calculate new time delta with newly-updated t_start_us */                \
        if (period_us >= PERIOD_DESIRED_US)                                                                            \
        {                                                                                \
            t_start_us = t_now_us - PERIOD_DESIRED_US;                                                                 \
        }                                                                                \
                                                                                \
        time_to_run = true;                                                                                \
    }                                                                                \
}

// Convert microseconds to seconds
#define US_TO_SEC(us) ((us)/1000000UL)
// Convert Joules to KWh (Kilowatt*hours)
#define JOULES_TO_KWHRS(joules) ((joules)/3600/1000)

/// @brief      Obtain a corrected time measurement from a raw time measurement.
/// @details    Assuming you have done experiments to determine your microcontroller (mcu)
///             clock's error, you can correct for it with this function. Pass in a time
///             measurement the mcu has timed directly, and get back a corrected value.
/// @param[in]  raw_sec     A raw time measurement, in seconds
/// @return     A corrected time measurement, in seconds
float do_time_correction(float raw_sec)
{
    // You determine the correct calibration constant. Perhaps it is 0.9813, or perhaps it is
    // 1.19.... You will need to determine this for each individual mcu.
    constexpr float TIME_CORRECTION_CONST = 1.0; // default: 1.0
    float corrected_sec = raw_sec*TIME_CORRECTION_CONST;
    return corrected_sec;
}

/// @brief      Obtain a new instantaneous (at this moment) current reading, in Amps
/// @param      None
/// @return     Current, in Amps
float get_current()
{
    // you implement this
}

/// @brief      Obtain a new instantaneous (at this moment) voltage reading, in Volts
/// @param      None
/// @return     Voltage, in Volts
float get_voltage()
{
    // you implement this
}

/// @brief      Run the coulomb counter task to sum the total energy received from the solar panels
/// @param[out] total_energy_joules_p  (optional) A pointer to a float to receive back the total
///                         energy value acquired, in Joules (Watts*sec). Pass in `nullptr` to not
///                         receive back this value. Note that the previously-cached value is
///                         passed out in the event it's not time to calculate a new value.
///                         The return value of this function will indicate whether a new value
///                         or cached value is passed out here.
/// @param[in]  reset_sum   (optional) pass in true to reset the internally-stored "total energy
///                         acquired" value during this call (prior to performing the latest
///                         power_watts_avg calculation, if it is time for that).
/// @return     true if a new total_energy_joules value was just calculated and passed back via the
///             pointer above, or false if an old, cached value was passed out instead since it
///             wasn't time to obtain and calculate a new value.
bool run_coulomb_counter(float* total_energy_joules_p = nullptr, bool reset_sum = false)
{
    // Set this task to run at 100 Hz
    constexpr uint32_t PERIOD_DESIRED_US = 10000; // 10000us = 10ms, or 100Hz run freq

    static float total_energy_joules = 0;

    if (reset_sum)
    {
        total_energy_joules = 0;
    }

    bool time_to_run = false;
    uint32_t actual_period_us;
    CREATE_TASK_TIMER(PERIOD_DESIRED_US, time_to_run, actual_period_us);
    if (time_to_run)
    {
        // Time to obtain new samples and perform some numerical integration to obtain the total
        // energy received.

        // the previous power calculation, in watts; required for trapezoidal integration
        static float power_watts_old = 0;

        // take new samples, & calculate power from those samples
        float current_amps = get_current();
        float voltage = get_voltage();
        float power_watts = current_amps*voltage;

        float actual_period_sec = US_TO_SEC((float)actual_period_us);
        actual_period_sec = do_time_correction(actual_period_sec);

        // Perform trapezoidal integration to obtain the "area under the curve", which is equal to
        // the energy in joules. Imagine a plot where the y-axis is power and the x-axis is time. If
        // you split the x-axis up into segments of width PERIOD_DESIRED_US, then the trapezoidal
        // area under the curve, within each of those time segments, is equal to time_delta x
        // (power_old + power)/2. This is the energy (Joules) obtained during that time period.
        float power_watts_avg = (power_watts + power_watts_old)/2;
        power_watts_old = power_watts; // prepare for next iteration
        float energy_joules = actual_period_sec*power_watts_avg;

        total_energy_joules += energy_joules;
    }

    if (total_energy_joules_p != nullptr)
    {
        // output this value back to the user
        *total_energy_joules_p = total_energy_joules;
    }

    return time_to_run;
}

void setup()
{
    // do whatever you need to here
    Serial.begin(115200);
}

void loop()
{
    // Energy, in Joules, or Watt*seconds. To convert to Watt*hours, simply divide by 3600 [sec/hr]
    float total_energy_joules;
    bool new_measurements_made = run_coulomb_counter(&total_energy_joules);

    // Let's do an event-based print where we print the latest total_energy_joules value at a rate
    // of 2 Hz, which is typical for digital displays showing information expected to be read by
    // us slow humans. Since the run_coulomb_counter() task is running at 100 Hz, that means we
    // need to print the latest value every 50 runs.
    if (new_measurements_made)
    {
        static uint16_t run_count = 0;
        run_count++;
        if (run_count % 50 == 0)
        {
            float total_energy_kwh = JOULES_TO_KWHRS(total_energy_joules);
            Serial.print("total energy received (J) = ");
            Serial.print(total_energy_joules);
            Serial.print("; (kWh) = ");
            Serial.println(total_energy_kwh);
        }
    }
}
</code></pre>

## References:

1. My own answer about generic, timestamp-based cooperative multitasking: Stack Overflow: How to do high-resolution, timestamp-based, non-blocking, single-threaded cooperative multi-tasking

## See also:

1. \[my answer\] Numerical derivation and integration in code for physics, robotics, gaming, and controls

# Answer
> 2 votes
You want a device called a "coulomb counter". Such a device measures the total current that flows through it.

I've seen some for Arduino. I believe SparkFun sells one. From a quick search it looks like theirs might be too low voltage for a large solar panel though.

# Answer
> 1 votes
There are a number of good choices for a sampling device. Some like the INA2221 can do simultaneous I & V at a higher sample rate sampling and accumulate or average the results to produce a low rate data stream better suited to a processor with limited resources without sacrificing anything.

If the idea is to test the output of a solar panel the terminal voltage isn't entirely irrelevant. Panels aren't always maximally illuminated.

If this concept is tied to battery charging I think there's a dimension missing from the concept guiding the approach - the charge acceptance of a storage cell is not a constant. The implicit use for this is to monitor the battery state of charge in order to either disconnect the charger entirely or change to charge balancing and or float modes.

Simply relying on Amp-hours\_out = constant * Amp-Hours\_in would need to set the constant at the maximum value to avoid trying to drive current at a high rate into fully charged cells. That charger relies on a long low rate charge completion and balancing phase to avoid gradually walking the state of charge down to a fractional charge with maximum acceptance. The available hours of sunlight tend to limit the time available for charge balancing, and the battery's available capacity is set by the cell with the lowest state of charge, so the idea is to get as close to 100% as possible on the cell with the highest state of charge before the charge rate has to drop to avoid damaging cells.

The details are battery technology dependent, but if the idea is to know the state of charge of a battery, then a more complex formula for charge acceptance may produce a more satisfying result.

---
Tags: mathematics
---


# Question
Title: Use of ESPAsyncWebServer.h with ArduinoJson version 6 for Master-Client transactions
I want to communicate two (2) ESP32's via Json commands using ESPAsyncWeb.h. The master should have specific operations to execute and respond to the client, and the client should be able to send specific Json commands to ask questions and receive responses. I have tried the method below but is throwing me weird errors such as

> cannot bind non-const lvalue reference of type 'ArduinoJson::JsonObject&' {aka 'ArduinoJson6185\_91::OBjectRef&'} to an rvalue of type 'ArduinoJson6185\_91::enable\_if\<true, ArduinJson6185\_91::ObjectRef\>::type' {aka 'ArduinoJson6185\_91::ObjectRef'}

I am not sure how to implement the operations for sending Json and receiving response from the Server using ArduinoJson 6. If anyone could enligthen me on how to conduct such transactions I'd appreciate it.

```
 void setup(){

//start serial comm
//Broadcast as WiFi SoftAP

 server.on("/command", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &json)
          {JsonObject& jsonObj = json.as<JsonObject>();
           uint8_t command = jsonObj["C"];
           String response;
           switch(command){
                           case 0: response = "{\"SCAN\":\"received_scan\"}";
                           request -> send(200, "application/json", response);
                           return;
                           case 1: /*...similar stuff */

                           case 2: /*...*/
}});
server.begin();
}

```

# Answer
> 1 votes
> cannot bind non-const lvalue reference of type 'ArduinoJson::JsonObject&' {aka 'ArduinoJson6185\_91::ObjectRef&'} to an rvalue of type 'ArduinoJson6185\_91::enable\_if\<true, ArduinJson6185\_91::ObjectRef\>::type' {aka 'ArduinoJson6185\_91::ObjectRef'}

In other words, "cannot assign `JsonObject` to `JsonObject&`". The compiler refuses to save a reference to a temporary variable because the reference would inevitably dangle.

To fix this issue, you must remove the ampersand (`&`) after `JsonObject`, like so:

```
JsonObject jsonObj = json.as<JsonObject>();

```

And it would be best if you also did the same for `JsonVariant`.

BTW, the cast from `JsonVariant` to `JsonObject` isn't necessary in your case, so you could simplify your program to:

```
server.on("/command", HTTP_POST,
          [](AsyncWebServerRequest* request, JsonVariant json) {
            switch (json["C"].as<uint8_t>()) {
              case 0:
                request->send(200, "application/json",
                              "{\"SCAN\":\"received_scan\"}");
                return;

              case 1: /*...similar stuff */

              case 2: /*...*/
            }
          });

```

I recommend that you have a look at ArduinoJson's documentation; I heard it's pretty good ;-)

---
Tags: esp32, web-server, http, json
---


title: bh1750 lightsesor won't work

text:
# Question
Title: bh1750 lightsesor won't work
ok, im having problems with my bh1750, here is all info i got:

board: esp32s nodeMCU v. 1.1

Pins:

Wiring: (the 2 reds go to pin 21 and 22)

code:

```
#include <BH1750.h>
#include <Wire.h>

BH1750 lightMeter;

void setup(){

Wire.begin();
Serial.begin(115200);
lightMeter.begin();
if (lightMeter.begin()) {
Serial.println(F("BH1750 initialised"));
}
else {
Serial.println(F("Error initialising BH1750"));
}
}

void loop() {
uint16_t lux = lightMeter.readLightLevel();
Serial.println(lux);
delay(500);
}

```

Sorry for bad formating

Serial output:

13:01:41.926 -\> \[BH1750\] ERROR: received NACK on transmit of address

13:01:41.926 -\> \[BH1750\] ERROR: received NACK on transmit of address

13:01:41.926 -\> Error initialising BH1750

13:01:41.926 -\> \[BH1750\] Device is not configured!

13:01:41.926 -\> 65534

13:01:42.430 -\> \[BH1750\] Device is not configured!

13:01:42.430 -\> 65534

13:01:42.932 -\> \[BH1750\] Device is not configured!

13:01:42.932 -\> 65534

and that goes on forever

Hope someone got an answer :D

# Answer
> 2 votes
The SCL and SDA silkscreen was reversed on my chips.
Took an hour of faffing to figure that out.

Never "Just presume" it is correct

# Answer
> 1 votes
Your code looks good. I2C configuration is default which depends on your board manager. Then your wiring may be wrong.

1. Using a multimeter to check supply voltage on the BH1750 module. It should be 3.3V
2. Using a multimeter to check the connection between the BH1750 module with ESP32.
3. Difference ESP32 vendor may provide a difference I2C pinout. Make sure you connect everything correctly.
4. Using an oscilloscope or logic analyzer to capture data on an I2C bus.
5. If everything good, try to use another module.

From your log, I guessed, the power supply is good. I2C connection is your problem. More, you should use the different color wire for the difference signal. It helps prevent unexpected connections.

---
Tags: arduino-ide, sensors, esp32
---


# Question
Title: Using a 5 pin button with Arduino Correctly
I am trying to build a simple motor test sketch, currently, to test a NEMA 23 stepper motor and the DM542T stepper driver.

Here is the code, and I am having trouble figuring out how to properly wire the 5-lead button (+, -, Common, NO, NC)

Here is the code

```
// Pin numbers
const int buttonPin = 2;
const int directionPin = 8;
const int stepPin = 9;

// Other constants
const int NumSteps = 5000; // steps
const int Speed = 500;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(directionPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  digitalWrite(directionPin, LOW);
  digitalWrite(stepPin, LOW);
}

void loop() {
  if (digitalRead(buttonPin)) {
    // Move in one direction
    for (int distance = 0; distance < NumSteps; distance++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(Speed);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(Speed);
    }
   // Reverse direction
   digitalWrite(directionPin, !digitalRead(directionPin));
 }
  delay(5);
}

```

The button is a momentary button, so I am holding it in to simulate a latching button.

I have the buttons Common and Neg leads wired together, and connected to the Gnd pin on the Arduino (mega rev3) I have the buttons Positive and the NC wired together and connected to pin 2.

Wiring that button in that manner, works fine in the button-controlled blink sketch, but is not working here (LED on the button doesn't light up and the motor test doesn't run).

Note: I am using a 5 lead momentary button as that what the project these motors will be for will be using.

Any help appreciated.

# Answer
> 1 votes
The button's pins are as follows:

* +: The LED's anode
* -: The LED's cathode
* C: The common pin of the switch
* NC: Normally Closed - is normally connected to the C pin until the button is pressed
* NO: Normally Open - is connected to the C pin when you press the button

So to use the button as a button the two pins you care about are C and NO. Use those pins (in any order) as you would any normal button with a pullup resistor (or the internal `INPUT_PULLUP` resistor).

To use the LED can be a little more tricky. Most of this style of button have the LED set up for 12V usage. While you *may* get a slight glow from it from 5V you would probably need to switch it with a transistor and power it from 12V to get it to light up properly. However your button may be rated differently and need a different voltage.

---
Tags: arduino-mega, c++, stepper-motor
---


# Question
Title: Is it legal to "simulate" Yubikey OTP autentication with an Arduino in own product?
I found the following Github Repo that makes it possible to build your own Yubikey with an Arduino Leonardo device.

https://github.com/pagong/arduino-yksim

Pretty cool. However I am wondering if using this is legal at all?

YubiCo is a company and they sell sticks with the YubiKey OTP feature. The verification process happens through their servers. Somehow I can't quite imagine that the company YubiCo tolerates that their processes and products could be easily replaced by open source products? Maybe they have any patents or utility models? And I was not able to find any licensing information which makes sense since official firmware seems to be closed source. So I guess it makes sense that no licensing information is available since the yksim project is a reverse engineered thing?! But I'll admit quite frankly: I have no idea of all this.

I would also like to use this library and possibly also for my customer projects, but I need to know whether this is really allowed.

Hope someone can help me here and I know that the internet is no source for a 100% sure legal advice. But maybe someone has a clue or a hint for me.

# Answer
> 2 votes
According to https://www.yubico.com/blog/secure-hardware-vs-open-source/

> The YubiKey hardware with its integral firmware has never been open sourced, whereas almost all of the supporting applications are open source.

I am not a lawyer, however it would seem that providing you aren't copying their (non open source) hardware, but are merely replicating the functionality, then this would appear to be OK. **Disclaimer**: I may be wrong.

Having said that, I agree with the comment under the question, you should probably ask at https://law.stackexchange.com/

Questions about the legality of an Arduino application really are legal questions, not technical ones.

---
Tags: arduino-leonardo
---


title: Linux avrdude: stk500_getsync()

text:
# Question
Title: Linux avrdude: stk500_getsync()
When trying to flash my genuine arduino micro with avrdude from cmd on a Manjaro system I get the infamous error

`avrdude: stk500_getsync() attempt x of 10 ...`

Im adding this post to the many other that ask about this error because all of them are trying to use the IDE to flash the arduino, whereas I can use it no problem on both Linux and Windows, but when using avrdude from cmd on Linux I get this error. This confirms that the board is fine and there are no shorts on the reset pin or any other possible physical cause of this issue, something appears to be wrong in the avrdude configuration.

This is my Makefile:

```
default: build

build:
    avr-gcc -mmcu=atmega32u4 main.c -o main

flash:
    avr-objcopy -O ihex -R .eeprom main main.hex
    avrdude -F -V -c arduino -p m32u4 -P /dev/ttyACM0 -b 115200 -U flash:w:main.hex

```

Can you suggest anyway to fix this?

EDIT: Problem Solved!

The error was in the `-c` parameter, for the atmega 32u4 it's supposed to be `avr109` and not `arduino`.

# Answer
There are two common ways of resetting an Arduino into the bootloader:

1. For UART based boards (Uno, Mega2560 etc) just opening the port resets the board
2. For USB based boards (Micro, etc with the 32u4 chip) you have to manually tell it to reset

Yours is option 2 - unless you tell it to reset the board it won't do anything. The IDE normally handles that for you.

But it's simple: just cause the CDC/ACM port to be opened at 1200 baud and closed again. The simplest method is to use `stty` to do it for you:

```
stty -F /dev/ttyACM0 speed 1200

```

You should find that it then resets the board. Adding a short delay to allow the USB to reset would be good too. So your whole programming routine could look something like:

```
flash:
    avr-objcopy -O ihex -R .eeprom main main.hex
    stty -F /dev/ttyACM0 speed 1200
    sleep 1
    avrdude -F -V -c arduino -p m32u4 -P /dev/ttyACM0 -b 115200 -U flash:w:main.hex

```

In Makefiles I find it useful to set the port as an overridable variable:

```
PORT?=/dev/ttyACM0

```

Then use `${PORT}` everywhere instead of `/dev/ttyACM0` \- then you can use `make PORT=/dev/ttyACM1` if you need to without having to edit the Makefile. Great if you have multiple boards.
> 4 votes

---
Tags: linux
---


# Question
Title: What is wrong with the way I write and or read the EEPROM adresses?
Consider:

```
#include <EEPROM.h>

byte guifactor1 = 1;
byte guifactor2 = 2;
byte guifactor3 = 3;
byte guifactor4 = 4;
byte guifactorgas = 5;
byte guifactorwater = 6;

volatile unsigned long count1factor;
volatile unsigned long count2factor;
volatile unsigned long count3factor;
volatile unsigned long count4factor;
volatile unsigned long countgasfactor;
volatile unsigned long countwaterfactor;

void loop(){
if (guifactor1 > -1){
    EEPROM.write(1, guifactor1);
    EEPROM.commit();
    count1factor = EEPROM.read(1);
    Serial.println(count1factor);
  }

  if (guifactor2 > -1){
    EEPROM.write(2, guifactor2);
    EEPROM.commit();
    count2factor = EEPROM.read(2);
    Serial.println(count2factor);
  }

  if (guifactor3 > -1){
    EEPROM.write(3, guifactor3);
    EEPROM.commit();
    count3factor = EEPROM.read(3);
    Serial.println(count3factor);
  }

  if (guifactor4 > -1){
    EEPROM.write(4, guifactor4);
    EEPROM.commit();
    count4factor = EEPROM.read(4);
    Serial.println(count4factor);
  }

  if (guifactorgas > -1){
    EEPROM.write(5, guifactorgas);
    EEPROM.commit();
    countgasfactor = EEPROM.read(5);
    Serial.println(countgasfactor);
  }

  if (guifactor1 > -1){
    EEPROM.write(6, guifactorwater);
    EEPROM.commit();
    countwaterfactor = EEPROM.read(6);
    Serial.println(countwaterfactor);
  }
}

void setup(){

}

```

The problem I have with my code is that it either doesn’t write the value to the EEPROM or it doesn’t read the value as it doesn’t print anything to the monitor.

I expected to read 1 2 3 4 5 6 from the monitor as I write the bytes to the EEPROM and then transfer the value to the *unsigned long* and print the variable.

# Answer
> 5 votes
You forgot to call `Serial.begin()` in `setup()`.

As a side note, your `if` tests are useless. The compiler warns me that:

```
comparison is always true due to limited range of data type

```

**For reference**: the previous answer, valid for the initial question where `guifactor1` and co. were all `unsigned long`.

---

The program does nothing because all the actions are conditioned on tests such as

```
if (guifactor1 > -1)

```

and these tests are always false. The reason they are false is because arithmetic comparison operators such as `<` perform *usual arithmetic conversions* on their operands prior to doing the actual comparison. Since `guifactor1` is `unsigned long`, and this type has a higher conversion rank than `int` (the type of `-1`), the second operand is implicitly converted to `unsigned long`, yielding `ULONG_MAX`.

---
Tags: c++, esp32, eeprom
---


# Question
Title: Sending float values from Python to Arduino using Serial communication
I need to send an array of floating-point numbers from python to Arduino Mega. For that, I read many sources\[this this this this this\] this\] and many more links for the same I referred. But unable to solve the problem.

I tried to send the angles to Arduino through python and return these values to python to print.

Below is the Python code in which I try to send the array named angle and tries to print the values received from Arduino.

```
import cv2
import numpy as np
import serial
import struct
import time

ser = serial.Serial('COM3', 9600, timeout = 1)
time.sleep(2)
if(ser.isOpen() == False):
    ser.open()
print('com3 is open', ser.isOpen())

angle = [120.2,154.2,14.25]
ser.write(struct.pack('>fff', 10.5,11.9,48.2)) # B for interger and f for float
#ser.write(struct.pack('>f', angle)) # B for interger and f for float

time.sleep(2)
ser.flush()

data = ser.readline()
data = str(data.decode("utf"))
print(data)

ser.close()

```

Below is the Arduino code:

```
float f1; float f2; float f3;

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

Serial.println("Arduino is in parseFloat!");
}

void loop() {

  if (Serial.available() > 0)
  {
    d1 = Serial.parseFloat(); d2 = Serial.parseFloat(); d3 = Serial.parseFloat();

    ad = d1 +2.5;
    Serial.println(ad)
  }
delay(2000);
}

```

The error I got is: I got no error or warnings but there is no output also for the print commands as shown in below Figure.

I need help to send the values to Arduino using python.

# Answer
There are two things going on here.

**First** of all, if you look up the *readline()* method in Python that is referenced in the PySerial manual, you'll see the following:

```
readline(size=- 1, /)

Read and return one line from the stream. If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

```

In your program, you are actually sending more than one line back to serial port from the Arduino. The first line is the ASCII-encoded "Arduino is in ParseFloat!". The second one is the test float calculation. If you don't account for the fact you are expecting multiple "lines" from the serial port, you wouldn't see the test calculation, because you are not actually reading it. For encoded data, it states that the line ends at the '\n' char/digit (10).

**Try it out** change the "println" to "print" in your Arduino program and add another message either in the setup or the loop. Run your Python program. What do you see? Now change the "print" back to println". Run your Python program again. What do you see now?

**Secondly**, Edgar Bonet points out the second issue. The *write()* method in the PySerial API requires data to be a bytes array, but it's the way you are encoding it. It seems that the Arduino Serial class expects a ASCII-encoded byte-array, rather than a float byte-array (the floats encoded as a single-precision floating point number), which is what you are sending.

If you change your code to something like this (for example):

```
angle = [120.2,154.2,14.25]
ser.write(str(angle).encode('utf-8'))

```

you should be able to see your test calculation come back, granted that you read what I wrote in the first part of this answer.
> 2 votes

---
Tags: serial, arduino-mega, python
---


title: Why the led is always on in proteus?

text:
# Question
Title: Why the led is always on in proteus?
I am simulating a circuit with arduino, which determine if there is current at input, then turn the led on at the output. The problem is the light is always on even when the button is open at the input.

This is my code:

```
void setup() {
  pinMode(7, OUTPUT);
  pinMode(8, INPUT);
  digitalWrite(7, LOW);
}

void loop() {
  int on = digitalRead(8);
  digitalWrite(7, on);
}

```

Why does this happen and how do I solve it?

Any help would be appreciated.

# Answer
> 2 votes
Microcontroller inputs don't detect the presence of current. They compare a voltage to a threshold.

In reality the input pin is closest to a capacitor. You press your button and it charges that capacitor to above the threshold voltage for "HIGH". Then you release the button but that capacitor remains charged and still reading "HIGH". You need something to reduce the charge on that capacitor to below the "LOW" threshold voltage.

This is most normally done with a resistor between the GPIO pin and GND which will "bleed off" that charge and give you a LOW reading when the button is released.

This is a "pull down" resistor (you can also reverse it and have a "pull up" resistor and the button connected to GND) and is an essential part of any input that doesn't itself generate both the HIGH and LOW voltages required (any switch or button).

Also 10V on a GPIO pin **will** destroy your Arduino.

---
Tags: arduino-uno, simulator
---


title: How to use Sim7020_mini NB-IOT module

text:
# Question
Title: How to use Sim7020_mini NB-IOT module
> I bough Sim7020\_mini module. I put IOT Sim card, and plug-in antenna, connect Rx,Tx into USB-TTL, then put supply into VIN (5 volt), LED power was lid on. Arduino Serial Monitor set into 115200, but no character appear, also I enter AT, no answer. I already making sure my wiring. Measuring STATUS pin 42 showing 1.8 volt, means not active.
>
> Schematic look like wrong, according to sim7020 Hardware design v1.02, to put SIM7020 to On we should give LOW pulse 1 second into PWRKEY. But STATUS pin still 1.8 volt.
>
> May anyone has successful using this such module? Any clue?

First question about using SIM7020\_mini Module

Thank you @hcheung for clue about 1.8 volt.

The SIM7020\_mini module already equipped with logic level shifter between 1.8v and 3.3v.

I know SIM 7020C already Up, pin `STATUS` (42) is HIGH, pin `NETLIGHT` (41) blinking.

Here is my schematic, I just want to enter AT Command first. But on my Serial Monitor (Arduino) doesn't show any character received.

simulate this circuit – Schematic created using CircuitLab

When I type 'AT' it's echoed back to screen Serial Monitor. When I reverse Tx/Rx between SIM7020\_mini module and USB-TTL, no character echoed. When I restart SIM7020\_mini module, there is no character received by Serial Monitor.

# Answer
> 0 votes
My fault, AT command on Serial Monitor (Arduino IDE) should be ending with `Carriage Return`, while my Serial Monitor using `New Line`

Thank you for responses.

---
Tags: serial, communication
---


# Question
Title: Arduino + Solar Charger Shield V2.2: Battery and Solar panels selection
first of all I would like to apologize for the, probably very basic and stupid questions for you, but I'm not an electronic expert..

I'm implementing my project using an Arduino Mega 2560 (I need more pins.. this is the most important reason that it drives the Arduino choice) I'll put my project in an external environment without the electricity source. For this reason my idea is to use a battery with a solar panel as power input to charge the battery. I also applied some low-power techniques in order to reduce energy consumption as much as possible. Regarding the solar panel and battery connections I purchased this Arduino Solar Shield.

Solar Charger Shield V2.2 - Seeed Wiki

And here I'm a bit (a lot) confused about the choice of the battery and the solar panel(s) to be purchased. First of all, my idea is to use multiple (2 or 4) solar panels in order to exploit as much as possible the solar light (multiple positions) but I'm not able (I'm not sure) about the solar panel selection to purchase. Considering that the maximum current that the solar shield could be delivered is 700mA can I use 4 solar panels like this https://www.seeedstudio.com/1W-Solar-Panel-80X100.html (applying also 4 applying 4 diodes to avoid reverse current)?

About this the possible number or size of the solar panels Do I need to consider the amount of th Current at Peak Power? For example, using 4 solar panels with 170mA as Current at Peak Power, 4\*170 = 680 that it's \> of the current of the solar shield. So, is this wrong? Do I reduce the amount of the panels or do I use a different panel?

About the Solar input voltage it's 4.8~6V. These are the specifications about the solar panel:

Dimensions: 100x80x2.5(±0.2) mm Typical voltage: 5.5V Typical current: 170mA Open-circuit voltage: 8.2 V Maximum load voltage: 6.4V Maximum load voltage, Open-circuit voltage are \> Solar input voltage. Is it a risk? About the lipo battery, can I use a battery 3.7v and about the mAh value as high as possible (for example this https://www.amazon.it/2100mAh-Lithium-Polymer-Replacement-Bluetooth/dp/B095BTSMYH/?th=1 ?) What about the maximum current value (in this case 5A)? Is it ok? In case, can you suggest me something else?

\** \*********** EDIT \*********** \**

As suggested I'm updating my question in order to give additional info about my scenario.

My project will be installed in an external environment (with some atmospheric protections IP67). The location, from solar irradiation point of view, it's a good place: https://globalsolaratlas.info/detail?m=site&c=40.283716,17.586365,9&a=18.056138,39.997805,18.056138,40.420456,18.535172,40.420456,18.535172,39.997805,18.056138,39.997805&s=40.11799,18.382874

About my project:

* I'll have to take the measurements from more sensors:
* starting from 1 to 10/15 humidity/temperature (DHT22) sensor;
* starting from 1 to 10/15 load cells (4 load cells for each HX711);
* I'll send the data using some transmissions using a LORA Shield.

I don't need to retrieve the measurements continuously or in very short periods.

The idea is to sleep my Arduino (in low power with all power sensors disconnected) and, using a RTC DS3231 module, to wake-up it on regular intervals, read the data, send it via LORA and go to sleep again.

The idea is to wake-up every 15 minutes. The time that I imagine about the measurements and the send will take a few seconds (around 30s in case I can approximate it to 1 minute).

And at the moment I don't have the exact measurements about the used current (because I can connect all here.. but I need to purchase the solar panels and the battery in order to make a real test also)..So, the idea now is to approximate.. In case I can adjust something later.

At the moment, measuring the current I have.

around 0.35mA when the Arduino is sleeping.

I probably can reduce it again because I have to remove 2 power led indicators (1 on my DS3231, one on my LORA shield... and, in case, also the power led on my Arduino).

When the Arduino works (live mode) probably I can consider around 90/100mA (probably this is too much) for 30s).

I'm not expert but, using this values I calculated the average about the used current in 1 hour:

((100mA * 4 minutes) + (0,35mA * 56 minutes)) /60 = 7mA/m 420 mA/h

I'll need 5v about the voltage.

I don't have any limitation about the size or the space.

I think that considering 7days without solar power supply or bad water conditions could be enough (in my opinion it's too much)

# Answer
> 1 votes
This is a question that's better suited for the electrical engineering SO, but I can give you some pointers to reword and re-post your question so it's not as broad.

Right now you have a few unknown variables to juggle, so you should be jotting down your thoughts on all of the following:

* Where will the unit be placed and/or located? How long do you expect it to go without needing to have its battery recharged?
* What is the continuous power consumption? You should know your approximate continuous current consumption and at which voltage you will be running the Arduino and the sensors that you connect to it
* What environmental conditions do you expect the unit to experience? Do you have a limiting factor on size or space?
* How much are you willing to pay?

You can definitely use multiple solar panels, but you'd have to connect them in parallel (so they maintain the same voltage), and even then, the linked charger shield can only go up to 900 mA of charging current. The 600-700 mA is the supported power output of the battery, or the max current that the shield can provide to your system thru the shield. It can be larger if you lower the system's voltage and stay within the maximum limits of the charger shield.

With regards to your second question, yes, current at peak power is a good metric for your approximations. If you go thru my questions, you will know how much your systems consumes in a day and choose a battery that can discharge no more than X amount of percent per day (depending on the type of battery). Your goal is to be able to charge that battery back at least close to its full capacity--your solar panels or the amount of thereof, as well as your charger, will be dictated by that.

For the Voc of the solar panel - ideally, it would be less than the solar input voltage. It's the voltage of the panel without a load connected to it. Of course, you will have a load connected to the solar panel and thus the typical voltage will be around what's stated, but if you don't want to damage your charger, you have to make sure your SP will be properly loaded under most conditions! It will be safer to connect multiple smaller SPs to get the current that will keep the system up and charge your battery.

With regards to the battery current - you have to check which current it is. Is it the charging current? Output current? Be mindful that you are limited by your charger in this case (3W output, 900 mA charging current).

Hope this gives you a start! It's a good question, but you need to do some more reading and you need to have a better idea of the design for your system before we can be more helpful.

Edit:

Per the updated information...

I will use your estimates, but do consider that for sensors that require power, you can add them and make your calculations more accurate. Also, while LoRA is low-power, it will consume some power too, and you can factor that in.

Let's assume your numbers are correct and the average current consumption averages out to ~ 420 mA/h. Then, if you want to keep the system alive for 7 days, you'll need a battery with a capacity of 420 mA/h * 24 hours/day * 7 days -\> 70,560 mAh or 70.560 Ah. At 5 volts, your system effectively requires 0.420 A/h * 5 V -\> 2.1 Watts/hour (finicky units here, eh?). That would translate to ~353 Watts/week. Also, 5V means you will need a battery that can provide that voltage - a lower voltage battery will not support your system.

The next thing you have to consider then is the battery type - there are a few, but the ones I'd go for are either Li-ion or VRLA (valve-regulated lead acid). There is a tradeoff between cost - Li-ion batteries cost more, but they are typically better in the majority of factors rather than SLA (sealed lead acid) batteries. Doing some googling, you could get a 70-100 Ah SLA/VRLA for ~$200-300 and a Li-ion for ~$400-500. Do note, however, that you can discharge Li-ion batteries more deeply than VRLA ones - it's recommended to keep the charge on the VRLA batteries around ~50% and preferably around ~75% to extend its life. You can discharge Li-ion batteries up to 80% or a bit more and that's fine, they don't suffer as extensive reduction in their lifetime like SLAs.

To put that into perspective, if you have an application that requires ~8 Ah, then ideally for a VRLA you'd need to size a battery such that it doesn't go below 50% for your worst-case application scenario. That is, if you think you'll need the device to run for 7 days without any sun, then you'll need a battery of a 16 Ah capacity or more. Even bigger if you want to extend its lifetime. For Li-ion, aiming at a bit higher than 8 Ah should be fine. For your application, that means getting a SLA battery that's \> 140 Ah (unless it's a deep discharge SLA battery) or a Li-ion battery that's close to 70 Ah.

Now, it must be noted that most batteries that provide those capacities typically come in 12V, so you would have to add a buck-converter to convert from 12V to the battery voltage your charger needs (3-4.5V). The charger you linked states that it can provide up to 3W out, which is 600 mA max at 5V. That would support your application as your average current draw is less than 600 mA.

For charging, however, you have to keep in mind that your system, on average, draws 420 mA/hour. So the charger's charging capabilities would actually be 900 - 420 -\> 480 mA/hour. That means that based on worst-case considered direct solar irradiation hourly data in the link you provided, you'd get ~ 8 hours of direct sunlight (again, worst case!). So 8 hours you can charge -\> 480 * 8 = 3840 mAh and you'll lose 6720 (420 * 16) mAh. That is not good, because you're losing the charge on the battery each day.

That means 2 things - you have to get a charger that permits a larger charging current within the maximum charging current of the battery rating AND you have to get enough panels (OR a big enough panel) to be able to provide that current. With the panels that you linked, the max current per panel is ~170 mA for the typical voltage of 5.5V. To provide a charging current of ~ 900 mA, you'd need 5 panels, but as mentioned above, that still wouldn't be enough. So, back to the drawing board...

I hope this is enough to help you make more progress on your design.

---
Tags: shields, battery, atmega2560, solar, charging
---


# Question
Title: What is the default baud rate without calling Serial.begin?
I cannot find the answer from official document and also surprised no one asked the same question.

What is the default baud rates if I didn't call `Serial.begin`?

# Answer
There is no default baud rate. When the sketch starts, the serial port is disabled (thus non-functional). Calling `Serial.begin()` enables the port.
> 7 votes

---
Tags: serial
---


# Question
Title: Using a Microchip Fubarino with the Arduino IDE, how to acces and configure all pins
I recently got a Microchip Fubarino, contains a PIC32MX250F128D and I'm totally new to the Arduino IDE, i uploaded the blink sketch all fine and well. Schematic: FubarinoMini\_v15\_sch

```
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
//pinMode(LED_BUILTIN, OUTPUT);

//asm ("BSF PORTA,10");
//pinMode(RA10, OUTPUT);
//TRISA10 = 0;
TRISAbits.RA10 = 0;
//PORTAbits.RA10 = 1;
//PORTAbits.RA10 = 0; // set to output
//mapPps(20, PPS_OUT_SDO2)
}

// the loop function runs over and over again forever
void loop() {
//digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
PORTAbits.RA10 = 1;
delay(500); // wait for a second
//digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
PORTAbits.RA10 = 0;
delay(500); // wait for a second
}

```

restults in:

```
 Blink:45:12: error: 'volatile union __LATAbits_t' has no member named 'RA10'
LATAbits.RA10 = 0;

```

changing:

```
void loop() {
  //digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  PORTAbits.RA10 = 1;
  delay(500);                       // wait for a second
  //digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  PORTAbits.RA10 = 0;
  delay(500);                       // wait for a second
}

```

doesn't work either.

I also tried this example code: https://github.com/fubarino/fubarino.github.com/wiki/Fubarino-Mini-pps
It does work.

```
#define LED 1
#define SCK2 4
#define SDI2 18
#define SDO2 20

```

The led on the Fubarino board is not connected to pin 1, but to RA10. Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 & SDO2 to the above defined numbers.

Normally on a PIC16F84 or so, you would do something like this.

```
bank1
movlw b'00000001'
movwf TRISA

movlw b'11110000'
movwf TRISB
bank0

```

the Arduino "code" seems a bit abstract. I Would like to experiment with the button.
The Chipkit pps example shows you can use the Microchip keywords from the devices datasheet.

Can the Fubarino be setup like a classic PIC device in the Arduino IDE? Configuring all the pins before going in to loop, using the Keywords from the datasheet.

# Answer
The entries in the "bits" structures are named after the bits.

It's not

```
TRISAbits.RA10

```

but

```
TRISAbits.TRISA10

```

The same goes for

```
LATAbits.LATA10

```

The only exception is the "port" one

```
PORTAbits.RA10

```

Which is a hangover from the old PIC16 chips that didn't have a LATx register.

---

> The led on the Fubarino board is not connected to pin 1, but to RA10.

Pin 1 is RA10. If you look in the file `Board_Data.c` for the Fubarino\_Mini variant (`packages/chipKIT/hardware/pic32/2.1.0/variants/Fubarino_Mini/Board_Data.c`) you can see all the pin mappings. There's a bunch of arrays there that define how everything fits together.

The second entry in most of those arrays (pin 1, starts counting at 0) is for RA10. As for

> Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 & SDO2 to the above defined numbers.

the PPS is a whole other mess on those chips. Pin 18 is not the 18th pin on the board, but digital IO pin number 18, which is the 19th entry in those pin array tables - RA4. Mapping RA4 is done through the file `packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/pingroups_1xx2xx.h` which contains an entry:

```
#define _PPS_RPA4       (2 + _PPS_SET_C)

```

and the file `packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/peripherals_1xx2xx.h` which has:

```
PPS_IN_SDI2     = (35 + _PPS_SET_C + _PPS_INPUT_BIT),

```

Those are then used by the mapPps() function to map RA4 to SDI2. Something which is perfectly possible.

Yes, it's convoluted and a bit of a mess, but the best we could come up with given how limited the PIC32MX2xx IO multiplexer is.
> 1 votes

---
Tags: arduino-ide, ide
---


# Question
Title: How to receive data from Xbee in AT mode on Arduino Nano
I need to print data on the Arduino serial monitor received from the Xbee in AT mode. I have searched on most forums and have not found anything on how to do this.

I have my Xbee tx connected to Arduino nano Rx and rx connected to tx.

# Answer
> 1 votes
You connected the Xbee to the single hardware serial interface that the Nano has. Is is also used by the USB to Serial chip, which connects to the Serial Monitor. So what you are sending to the Xbee is also sent to the Serial Monitor. What the Xbee sends is only sent to the Arduino (since the Xbee TX pin is connected to RX of Arduino and also TX of the Arduino's USB to Serial chip).

But you can separate then by using a `SoftwareSerial` interface on any other pins of your liking. Then you can connect the Xbee to it. Then forward the output of the `SoftwareSerial` interface to the `Serial` interface. To see how this works have a look the first example of the `SoftwareSerial` library. It's basically checking both interfaces, reads available data from one interface and writes it to the other (note the `write()` in contrast to `print()` since when forwarding you don't want to interpret the data again to another format like `print()` does).

Also there are plenty examples and tutorials about `SoftwareSerial` on the web. An important restriction is that only one `SoftwareSerial` interface can listen to data at any time. The Hardware `Serial` interface doesn't have such a problem.

---
Tags: serial, arduino-nano, xbee
---


# Question
Title: Arduino Leonardo/Pro Micro sleep and USB
I am using an Arduino Pro Micro (basically a Leonardo in a smaller form factor) in a mobile application where power consumption is really important.

To reduce power consumption, I put the Arduino to sleep, but that disconnects USB. That's not really acceptable in this application, since reconnecting USB after the Arduino wakes takes pretty long (a second or two).

Is there some way to keep the USB connection alive while still conserving energy? E.g. by waking the ATMega32u4 frequently to keep the connection alive? Or is there some not-as-deep sleep moden where the USB connection stays alive?

Edits for clarification:

The device is an USB HID device. If the device goes to sleep after a few minutes of inactivity, having to reconnect after the user pressed a button causes quite a long delay between pressing the button and a reaction on the device.

I am using the ATMega32u4's native USB implementation, so no V-USB or anything similar.

I am putting the device to sleep like so:

```
Keyboard.end();
USBCON = 0;
LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF);

```

This is how I wake it up again:

```
USBDevice.attach();
delay(50);
Keyboard.begin(KeyboardLayout_en_US);

```

# Answer
> 4 votes
The Arduino has several sleep modes. They differ mainly by the clocks that are kept running, the peripherals that are enabled, and the possible wake-up sources. All these modes are described in the datasheet of the ATmega32U4 microcontroller, section 7: *Power Management and Sleep Modes*.

You may see here that “Power-down” is one of the deepest sleep modes: all clocks are disabled, the main oscillator is turned off, and only asynchronous wake-up sources are available. As you have experienced, the USB port is not functional in this mode.

In contrast, “Idle” is a somewhat shallow sleep: the CPU is halted but the peripherals remain clocked. Any enabled interrupt can be used as a wake-up source. This is a good option if you want the USB link to remain connected while sleeping, and you can get it with the `LowPower.idle()` function.

If you are worried about the sleep mode to be too “shallow” and not save enough energy, note that the parameters if `LowPower.idle()` let you specify which peripherals you want to keep running during sleep. If you keep running only those that are needed, this should limit the power consumption to what is strictly needed.

# Answer
> 2 votes
This would better serve as a comment, but I can't post comments (yet)...

* What is your application doing? Is it supposed to be asynchronous? Why are 1-2 seconds too long?
* By the "USB" connection, you mean the UART/Serial peripheral?
* How are you putting the board to sleep? Are you using the Arduino Sleep Modes? If so, which one are you using?

I'll speculate a bit: if you are using the ASP, then you might have to change the source code for the functions you are using to accommodate for keeping that peripheral awake. Do note that it might make the application more power-hungry than you want it to be.

Waking up more often could be done, but ideally you would need a synchronization mechanism, because at least eventually you'll run into an issue where you might miss the data or you'll wake up the device so often, you'll lose your power savings.

---
Tags: usb, arduino-leonardo, sleep, arduino-pro-micro
---


# Question
Title: Please help me navigate the stepper motor object definition in the documentation
I am trying to use the stepper library and the stepper object is documented like this

> This function creates a new instance of the Stepper class that represents a particular stepper motor attached to your Arduino board.
> Use it at the top of your sketch, above setup() and loop(). The number of parameters depends on how you’ve wired your motor, either using two or four pins of the Arduino board.
> Syntax
> Stepper(steps, pin1, pin2)
> Stepper(steps, pin1, pin2, pin3, pin4)
> Parameters
> steps: the number of steps in one revolution of your motor. If your motor gives the number of degrees per step, divide that number into 360 to get the number of steps (e.g. 360 / 3.6 gives 100 steps).
> pin1, pin2: two pins that are attached to the motor.
> pin3, pin4: the last two pins attached to the motor, if it’s connected to four pins.
> Returns A new instance of the Stepper motor class. Example Stepper myStepper = Stepper(100, 5, 6); """

The problem is that "two pins" and "last two pins" do not tell me anything about which pins go where on the motor driver. I am using a DM320T stepper driver

Can anybody tell me what "pin1 pin2 pin3 pin4" actually correspond to?

# Answer
> 1 votes
The standard `Stepper` library does not support stepper drivers, which only have a step (in this case labels "PUL" for pulse) and a direction pin (labeled "DIR"). So you need to use a different library. I suggest using the `Accelstepper` library, which is also more capable than the standard `Stepper` library. Then you can define the `AccelStepper` object like this:

```
AccelStepper stepper(AccelStepper::DRIVER, STEPPER_DIR_PIN, STEPPER_STEP_PIN);

```

About the connections: The shown driver is meant to be connected with twisted wire pairs, so in this case one wire for signal and the other for ground or 5V. Look at the documentation for your stepper driver. There you should be able to find a wiring diagram.

---
Tags: library, stepper, stepper-motor, documentation
---


# Question
Title: Why does oscilloscope trigger look shaky when using delayMicroseconds?
I'm new to electronics but I have a Rigol DS1054Z oscilloscope and I'm experimenting to help learn. I've created an incredibly simple sketch using an ESP32 and Arduino IDE:

```
void setup() {
  pinMode(32, OUTPUT);
}

void loop() {
  delayMicroseconds(10);
  digitalWrite(32, LOW);
  delayMicroseconds(10);
  digitalWrite(32, HIGH);
}

```

However, the square wave is incredibly "shaky" or unstable looking. Why is that?

# Answer
> 1 votes
The display moving is what we call jitter. It is normal with the Arduino and expected. The pulses are not even because of the background tasks such as the interrupt service routine (that does the millies etc whether you use them or not). When an interrupt occurs it causes the processor to stop, save its state, do a new task, then restore its state and continue. During the interrupt service routine (ISR) the processor uses time to execute instructions, this delay causes the jittering. Trust your scope, as usual it is correct. If you use one of the timer outputs the jitter will go away because they are not normally adjusted the just keep going. PWM is one of the more common modes of doing this but there are many others you can also use.

# Answer
> 0 votes
This isn't an answer, but you could compare it to hardware PWM to test the limits of the rest of the system.

### Simple ESP32 PWM per https://www.electronicshub.org/esp32-pwm-tutorial/

```
int freq = 48000;
int ledChannel = 0;
int resolution = 8;  // 48000*2^8 < 80Mhz on channel 0 per https://www.electronicshub.org/esp32-pwm-tutorial/

void setup() {

  ledcSetup(ledChannel, freq, resolution);
  ledcAttachPin(32, ledChannel);
  ledcWrite(ledChannel, 127);
}

void loop() {
}

```

# Answer
> 0 votes
Jitter like that is usually caused by the different amount of time it takes to go through loop(). Remember that the tick timer takes time away from loop() at an interval that is not synchronized to the loop() time.

---
Tags: esp32
---


title: Joystick reading erroneous values

text:
# Question
Title: Joystick reading erroneous values
Under normal operation, the value of a joystick's ADC range on my board is from 0 to 1023 (10-bits). However, my graph for either axis is not continuous. Rather, there is more than one min and maximum for both axis. I am running this thread on a MSP432P401R however the code isn't any different than an Arduino.

```
int jumpFlag;
int backwardsFlag;
int forwardsFlag;
int selPin = P5_1; //Select digital pin location
int xOutPin = A14;
int yOutPin = A13;

void setupPlayerActions() {
  pinMode(selPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(selPin),jumpISR,RISING);
  //pinMode(xOutPin, ); //Analog X pin setup
  //pinMode(xOutPin, ); //Analog Y pin setup
}

void jumpISR() {
  Serial.println("Jump Detected!");
  jumpFlag = 1;
}

void loopPlayerActions() {
  int x_adc_val, y_adc_val;
  int leftThreshold=50,rightThreshold=900;
  float x_volt, y_volt;
  x_adc_val = analogRead(xOutPin);
  y_adc_val = analogRead(yOutPin);
  x_volt = ( ( x_adc_val ));  /*Convert digital value to voltage */
  y_volt = ( ( y_adc_val));  /*Convert digital value to voltage */
  if (x_volt < leftThreshold){
    Serial.println("Move Backwards");
  }
  else if (x_volt < rightThreshold){
    Serial.println("Move Forwards");
  }
  Serial.println("X_Voltage = ");
  Serial.print(x_volt);
  Serial.print("\t");
  //Serial.print("Y_Voltage = ");
  //Serial.println(y_volt);
  delay(100);

  //delay(250);
}

```

The graph goes to zero for all positive x and y integers however it briefly reaches a maximum past a small value on the -x and -y axis then sinks to about ~420. What could be causing this?

# Answer
A 10 bit ADC may not have 10 bits of resolution for a given sample. It might only have 5 or 6 bits due to random noise and other factors. Consult the chip manufactures specifications / recommendations if you need a specific number.

What can be done?

* If response time is not an issue, consider averaging the ADC reading. A common coding practice is to use an exponential moving average.
* Consider a better ADC. Many times a dedicated ADC chip (not integrated into a processor) will have better specifications.

For more in depth reading this NXP (aka: Motorola, Freescale) application note discusses "How to Increase the Analog-to-Digital Converter Accuracy in an Application".
> 0 votes

---
Tags: joystick
---


title: parseFloat() function

text:
# Question
Title: parseFloat() function
I have noticed that the parseFloat() function returns decimal numbers, but only up to 2 decimal places. Would it be possible for it to return the numbers with more decimal places? In case we need more precision

# Answer
> 2 votes
> the `parseFloat()` function returns decimal numbers

No, it doesn't. It returns a **binary** (not decimal) floating point number.

> only up to 2 decimal places

The number returned by `parseFloat()` has 24 significant digits. Binary digits, that is, also called “bits”. This is roughly equivalent to 7 decimal digits.

That being said, beware of `Serial.print()`. This function converts binary floating point numbers to decimal, and defaults to showing only two digits after the radix point. You can ask for more:

```
Serial.println(x, 6);  // display x with 6 digits after the radix point.

```

If you want to gain some basic understanding of how floating point numbers work, I recommend reading The Floating-Point Guide - What Every Programmer Should Know About Floating-Point Arithmetic.

---
Tags: float, functions
---


# Question
Title: Problem deseralizing some fields in JsonRequest
I'm almost successfully able to GET a json blob and print it to the console. It seems to be failing on *some* string fields I am guessing because of the length. Any thoughts/ideas/suggestions to make this work?

The requested json blob (I can see this entire string from the console, it is spaced out here for readability). The entire length of the original string happens to be 597 characters.

```
{
    "expand":"schema,names"
    ,"startAt":0
    ,"maxResults":50
    ,"total":2
    ,"issues":[{
         "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
        ,"id":"94245"
        ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9425"
        ,"key":"BP-4349"
        ,"fields":{
            "summary":"QM: API Timeout Error on Checkout "
        }
    }
    ,{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
        ,"id":"93129"
        ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9319"
        ,"key":"BP-4078"
        ,"fields":{
            "summary":"Search \"term\" options - broken in loader see sproc"
        }
    }]
}

```

The code I'm using to fetch this json object reduced as much as possible:

```
JsonRequest request(2048);
//...snip...// (inside JsonRequest object)
WiFiClientSecure *client = new WiFiClientSecure;
HTTPCliernt download_client;
download_client.begin(*client, url);
download_client.collectHeaders(headerKeys, 5);
download_client.setAuthorizationHeader(authValue);
download_client.setUserAgent( HARDWARE_NAME );
int httpCode = download_client.GET();
if(httpCode == HTTP_CODE_OK)
{
    String result = download_client.getString();
    download_client.end();
    client->stop();
    dsError = deserializeJson(*this, (uint8_t*) (result.c_str()) );  //this refers to this object which is the JsonRequest
    if(!dsError)
    {
        ...
        return true;
    .....
(outside JsonRequest object, request is a deseralized `SpiRamJsonDocument` )
//...snip...//

int total = request["total"].as<int>();                         //working: 2
int startAt = request["startAt"].as<int>();                     //working: 0
int maxResults = request["maxResults"].as<int>();               //working: 50
int totalRecords = total + startAt;
for(; startAt < totalRecords && maxResults > 0; startAt++, maxResults--)
{
    log_i("%s: %s - %s"
        ,request["issues"][startAt]["key"].as<String>()                 //working: BP-4349
        ,request["issues"][startAt]["fields"]["summary"].as<String>()   //broken? (garbage string)
        ,request["issues"][startAt]["self"].as<String>()                //broken? (garbage string)
    );

}

```

I don't know why some strings worked and some did not. I assume that the length of the string is the problem ? How would you suggest I retrieve the longer strings ? How do I know when the length dictates the use of `.as<String>()` vs something else?

# Answer
Turns out there is a arduino json troubleshooter specifically for this type of issue here: https://arduinojson.org/v6/troubleshooter/ wow awesome. If you are having an similar issue I would start there.

This didn't fix my problem, for myself if I cast the types to `const char *` meaning

```
...snip...
const char* x = request["issues"][startAt]["self"].as<const char *>()
log_i("%s", x);
...snip...

```

this worked every time for every string
> 0 votes

---
Tags: esp32
---


# Question
Title: How to read data directly from lcd display
Referring to post: LCD data read and show on computer It was not clear what the final code is. Could you post the code and schema again, and if possible, an explanation of how it works?

My problem:

I need to read the information of a lcd 20x4 display, which is controlled by a PLC (which has the protected hex code), and send the data through the serial port.

For this I am using an arduino one to do the reading. I connected the arduino in parallel with the display data bus, to try to read the bits and convert later.

This is the schematic I'm using:

Note: I have placed 1k resistors to make the pulldown on each pin, to avoid reading errors.

With this code:

The problem is that I'm having these results in reading:

No matter what appears on the screen, they are always invalid characters. If someone identifies where my problem is, I'll be very grateful.

# Answer
> 1 votes
I would recommend ditching the the digitalRead in this case - it is performed sequentially, and is rather slow. As you only need to read 8 input lines, consider using Port register: The Arduino Uno comes with a total of three Ports which "hold" all of the I/O pins. Those are

* PORTB = Digital Pins 8 through 13 plus the crystal pins
* PORTC = Analog Input 0 through 5, reset pin
* PORTD = Digital Pin 0 through 7

Since you need the RX and TX lines (Digital pin 0 and 1) for your serial communication, you will have to split the signal onto two registers.

I would recommend connecting D0 through D3 to Digital Pins 8 through 11 for the first four bits (meaning they'll go to bits 3 to 0 of Port B), and D4 through D7 to Analog Pins 0 To 3 (meaning they'll go to bits 3 to 0 of Port C). RW goes to Pin 7, RS to Pin 6, E to Pin 5.

The code you would then use to read the data would be this: uint8\_t byte\_displaydata = 0x00; uint8\_t RW = 7; uint8\_t RS = 6; uint8\_t E = 5;

```
void setup() {
  Serial.begin(1200); //perhaps increase this a bit
  pinMode(RW, INPUT); //some speed is lost compared to register manipulation, but that is likely insignificant
  pinMode(RS, INPUT);
  pinMode(E,INPUT);
  DDRB &= ~((1 << DDRB0) | (1 << DDRB1) | (1 << DDRB2) | (1 << DDRB3)); //technical not necessary since they're initialized with 0
  DDRC &= ~((1 << DDRC0) | (1 << DDRC1) | (1 << DDRC2) | (1 << DDRC3));
  PORTB &= ~((1 << PORTB0) | (1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3)); //disable internal pullups
  PORTC &= ~((1 << PORTC0) | (1 << PORTC1) | (1 << PORTC2) | (1 << PORTC3));

}

void loop() {
  if(digitalRead(RS) == HIGH && digitalRead(E) == HIGH){
    byte_displaydata = 0x00; //reset byte_displaydata
    byte_displaydata = PINB << 4; //push PINB bits 3 to 0 to bits 7 to 4
    byte_displaydata |= (PINC & 0x0F); //filter PINC bits 3 to 0 and OR them into result bits 3 to 0
    Serial.println(byte_displaydata,BIN);
  }
}

```

Please note that I have not tested this, and only recently have gotten started in AVR / Arduino. If anyone can look this over, I'd greatly appreciate it.

Source: Microchip ATmega328P datasheet, Arduino pin mapping

# Answer
> 0 votes
It is probably too late for the OP but there is a protocol sniffer for such LCD screens which use the HD44780 series LCD driver as, for example, the common LCD1602 does. The code is published here:

https://forum.arduino.cc/t/lcd-1602-and-similar-databus-sniffer/675769/11

The data rate would be too fast for Serial.print() to print each character received in real time so a queue is used to consolidate the data.

---
Tags: lcd
---