message:
Why ESP8266 slower than Arduino nano?

I'm using the same script(and standard wire and serial library only) one uploaded to Arduino nano one uploaded to ESP8266. However, despite ESP8266 running at 160MHz, 10 times faster than nano, it's taking 3.5 ms to complete the loop, compare to 2.5 ms than that of nano.

How could that be?  why ESP8266 was slower?

body:
> However, despite ESP8266 running at 160MHz, 10 times faster than nano, it's taking 3.5 ms to complete the loop, compare to 2.5 ms than that of nano.

There's a number of reasons for that. Chiefly:

1. The ESP8266 has no I2C hardware, so has to use software "bit-banging" to emulate I2C. That is slower to execute.
2. The ESP8266 also has to manage the WiFi hardware which takes a portion of the processing power away from the user

The result is slower execution for I2C operations and "jitter" added to timings of loops and such.

> will the same thing (wire) happen to esp32?

No (or not as much). The ESP32 has hardware I2C so it doesn't need to use bit-banging to emulate it, so it will be faster. Also it is dual core and one core is used for "system management" including managing the WiFi and Bluetooth, while the second core is used to execute your sketch, so there is no (or little1) interruption by the WiFi slowing down your sketch.

----

1: Two cores accessing the same area of RAM causes some contention as only one core can access the same block of RAM at a time, so it's not perfect. You may still get slight delays, but they will be minuscule compared to the processing needed for the ESP8266's WiFi code.


sender: user

message:
How to calculate the RZERO value in MQ135 sensor, I have already burned it for 24 hours?

![enter image description here](https://i.stack.imgur.com/lV1ig.jpg)![enter image description here](https://i.stack.imgur.com/MO6Xp.jpg)
I've already burned it for 24 hours and it is now giving the constant value of 932.36,pls tell me how to calculate the RZERO value.

sender: assistant

body:
From the datasheet here --->[MQ135 datasheet][1], It is the value of Sensing resistor at 100 PPM of Ammonia(NH3) or from the graph in Fig. 3, you can use gases that has y intercept as 1 and appropriate concentration, i.e you need atleast some known parameter to get it. The legend in the graph is also not clear (as far as getting the values from the Log - Log graph, there are tutorials in youtube).

I'm also in need of solution to this, so far this is what I read on the internet... You need a chemistry lab to do it !!!

  [1]: https://www.olimex.com/Products/Components/Sensors/Gas/SNS-MQ135/resources/SNS-MQ135.pdf


message:
loop() either stops working, or lcd stops working | buttons don't work

I'm using a Let's Start Coding Ultimate Kit 1 (it was a christmas present, don't ask) and I'm trying to use this as a typing sort of thing. I haven't implemented the actual letters though.
```c++
#include <MakerScreenXVI.h>;

MakerScreenXVI lcd;

int currentNumber = 1;
int ms = 0;
int totalMS = 0;
bool first = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, INPUT);
  pinMode(A3, INPUT);

  lcd.begin();
  lcd.print("Success");
  lcd.setCursor(0,1);
  lcd.print(currentNumber);

}

void loop() {
  delay(200);
  changeNumber();
  delay(200);
}

void clearLCDLine(int line) {
        lcd.setCursor(0,line);
        for(int n = 0; n < 16; n++) // 20 indicates symbols in line. For 2x16 LCD write - 16
        {
                lcd.print(" ");
        }
}

void changeNumber() {
  if (digitalRead(A0) == LOW) {
    if (first == false) {
      clearLCDLine(1);
      first = true;
    } else {
      first = false;
    }
    currentNumber++;
    if (currentNumber == 27) {currentNumber = 1;}

    lcd.print(currentNumber);
  } else if (digitalRead(A3) == LOW) {
    currentNumber = currentNumber - 1;
    if (currentNumber == 0) {currentNumber = 26;}
    //clearLCDLine(1);
    lcd.print(currentNumber);
  }
}
```

For some reason, after it deletes the 1, it stops. Nothing is printed onto the screen, and nothing is cleared from it. How can I fix this?
Also, the buttons always return the ```LOW``` value. How can I fix this?

body:
The buttons will send a LOW signal when pressed if they are set with pinMode INPUT_PULLUP.

The issue with currentNumber not displaying is that after you clear the screen with the 'for' loop, you need to reset the cursor to position 0,1 with `lcd.setCursor(0,1);` . Otherwise, the numbers are printing out of view.

If I add `lcd.setCursor(0,1);` just above each line with `lcd.print(currentNumber);` , I think the code has the behavior you're looking for.

**Edit from the person who asked the question:**
<br> You also have to add a delay of around 150-200, or else one push will count as many.


message:
How to find the peak value of analog signal?

I have a question .. Please help me I don't know how Arduino can read the peak value of the sensor signal. The value I want is in the ADC value .. What I want is ... for 5 seconds there will be 1 average value from the highest peak value of the sensor, and the ADC value. I will use pin A0, but I don't know how to code the program that I want. Please help me What is the code?

body:
See if I understand this correctly: For a given time period you want to find the peak.

```
void setup()
{
  unsigned long int cur_time = 0 ;
  unsigned long int time_elapsed = 0;
  int peaks[20]; // say you want to find 20 peaks , 1 peak for data arriving between 5 secs
  int time_period = 5000;
  int data = 0;
  int mx=0;
}

void loop()
{
   for(int i = 0 ; i<20;i++)
   {
      cur_time = millis();
      while(cur_time - time_elapsed <=time_period)
      {
             if(mx==0)
              { mx = analogRead(A0); }
              else:
               {  data = analogread(A0);
                  mx = max(data , mx);
               }
              cur_time = millis();
        }
         time_elapsed = cur_time;
         peaks[i] = mx;
         mx = 0;
        }
  }
```
Hope this helps!!


message:
Why doesn't pin 19 work when powering the EzSBC Esp32 board from batteries?

I recently got an [ESP32-01 Breakout and Development Board][1] from EzSBC.com.  It is advertised as a board specifically designed for use with batteries because of it's low current draw when in sleep.

As a test I loaded the basic Arduino `blink` sketch onto the board using pin 19 as the built in test LED.  When I power the board from the computer through the USB connection the LED blinks as expected, but when I connect a battery accross VIN -> GND nothing happens.

What am I doing wrong?

  [1]: https://www.ezsbc.com/index.php/featured-products-list-home-page/wifi01-35.html

body:
There is a subtle design choice in this board that took be hours to figure out.

According the [connection schematic][1] the blue leg of the LS3528RGB LED is connected to `IO19` through a 1k resister (`R2-1`).  However the power leg is connected to `Vusb` *not* `3.3V` like the other RGB LED.  This means that the LED connected to IO19 is only usable when the board is connected through the micro-USB port and not when connected directly to battery.

This can be useful for programmatically reading whether the board is running on battery or USB.

  [1]: http://www.ezsbc.com/index.php/productattachments/index/download?id=30


message:
Reading 4-20ma signal on arduino

I want to read a 4-20 mA analog signal from a 24V flowmeter. I've read the simplest way is to convert it into 1-5V signal using a 250 ohm resistor. The thing is I want my reading to be precise so my question is; is there any resolution loss when converting it to 1-5V?

I've also looked up on current to voltage converting boards similar to this one: https://www.sparkfun.com/products/14544

but I don't think they can detect 4mA signal.

I am a beginner in this so need some guidance here.

body:
Using a resistor is the "Normal" way, yes. 250Ω will give you 1-5V, yes, which means that you get 4/5 of the actual resolution of the ADC at your disposal.

That means instead of 0-1023 you're actually reading 204-1023, or 819 possible values. Spread over 16ma (or 4V, which are the same thing) that gives you about 20µA resolution.

If you really really care about that extra 1/5 of the resolution you can instead use a 300Ω resistor to give you 1.2 to 6V, then pass that through a subtracting amplifier (see [this post](https://electronics.stackexchange.com/a/18265/4245)) and subtract 1.1V from it (you need to create that 1.1V, of course).  That will give you 0.1 to 4.9V, which then covers more of the ADC's available range (20-1002, or about 16µA resolution).

Is it worth it? Probably not. Any increase in resolution will likely be swamped by the inaccuracy of the resistor and potential drift though self heating.


message:
Does Keyboard.begin() and Keyboard.end() make my code slower?

I'm making an IR Macro keyboard, and about 10% of the code is dedicated to the `Keyboard` commands, would having `Keyboard.begin()` and `Keyboard.end()` in the method responsible for typing make any difference to the speed or size?
My code:

    void decodeCode(){ // send the macros.
      int pos = 0;
      for(int i = 0; i<output.length(); i++){
        if(output.charAt(i) == '$' && i!=output.length()-1){ //the $ is a symbol for "$pecial" characters
          i++;
          specialDecodeChar(output.charAt(i));
        }
        else if(output.charAt(i) == '%'){
          Keyboard.releaseAll();
        }
        else{
          Keyboard.press(output.charAt(i));
        }
      }
      Keyboard.releaseAll();
    }

I currently have `Keyboard.begin()` in `setup()`.

body:
The `Keyboard::begin()` and `Keyboard::end()` functions,  if you actually [look at the code](https://github.com/arduino-libraries/Keyboard/blob/master/src/Keyboard.cpp#L69-L75) are empty functions. They do nothing.

In theory the compiler should just optimise them out.


message:
How to use tinygps.h library to measure distance? using NEO6mv2

any reference site for the format code for tinygps.h to measure distance?
or any codes for tinygps.h for measuring distance i'm just a beginner in learning arduino thank you

body:
You don't use the `tinygps.h` library to measure distance. You use the `tinygps.h` library to get coordinates. Over short distances those coordinates (longitude and latitude) can be equated to x,y coordinates on a plane (over greater distance - hundreds or thousands of miles - it gets a whole lot more complex).

Two sets of x,y coordinates form a line. A line is one side of a right-angled triangle (the hypotenuse).

Pythagoras (remember him from math class? That rubbish you thought you'd never need? Well, now you do...) says that the square of the hypotenuse is equal to the sum of the squares of the other two sides.

You know the other two sides - they're just the difference between the two x coordinates and the two y coordinates.

We're not going to write the code for you, and Google is probably better at finding websites with example code on than we are.


message:
Wire multiple SW-420 Vibration sensors to a single pin

I am working on installing an alarm system using Konnected IO on a NodeMCU esp8266. I have multiple bay widows which will use 4 SW-420 vibration sensors. I would like to wire all 4 of the SW-420 vibration sensors to a single pin. When any of the 4 sensors detect vibration the pin will go to high. I attempted to simply wire the d-outs from all four together and all four sensors stoped working. I'm out of ideas on how to do this any help would be greatly appreciated. I believe sensors send out a low signal when no vibration is detected and high signal when vibration is detected. Link to sensors: https://www.amazon.com/XLX-Vibration-Normally-Sensitive-High-Efficient/dp/B07V8FJRN1/

body:
Two ideas came to my mind, first is to connect each output to four digital pins and then do something like this:

    if(digitalRead(pinOne) == HIGH || digitalRead(pinTwo) == HIGH || ...){
    do something
    }

Or you can use an opamp or comparator for that purpose:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/WcjaE.png)

<!-- End schematic -->

 In above configuration if any of the sensors output is HIGH, op amp will drag it's output to the positive rail (~5V). otherwise output is LOW (~0 V).


message:
Does flashing ESP8266/ESP-01 firmware mean uploading a new 'sketch' and why different firmware?

Hi I am new to IOT and I am now in love with this. However I'm a little confused right now with the jargon. My question is similar to [this][1]. But I do have some extra questions though.

1. When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?

2. On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing [this][2] but for different firmwares such as AT, NodeMCU and Micropython?

3. For the NodeMCU dev boards, is the default firmware on the module [NodeMCU firmware][3]? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?

4. To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the [Thonny IDE][4]. And there is no way to code in micropy or LUA from the Arduino IDE.

5. Is the reason for using other firmware is because of how the code is compiled and the language used?

If someone could clear things up for me I would greatly appreciate it. Thanks!

  [1]: https://arduino.stackexchange.com/questions/43446/when-uploading-a-sketch-to-an-esp8266-isnt-that-the-same-as-flashing-firmware
  [2]: https://www.instructables.com/id/Flash-or-Upgrade-Firmware-on-ESP8266-ESP-01-Module/
  [3]: https://github.com/nodemcu/nodemcu-firmware
  [4]: https://thonny.org/

body:
> When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?

Yes. "Firmware" is application code running on the microcontroller.

> On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?

Yes. "Firmware" is application code running on the microcontroller.

> For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?

Yes. "Firmware" is application code running on the microcontroller.

> To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.

No. The Arduino IDE is for coding in C++ with the Arduino API extensions.

> Is the reason for using other firmware is because of how the code is compiled and the language used?

The firmware is just what runs on the chip. If that firmware provides its own programming language then you can use that to execute that programming language.

If you write your own firmware in the Arduino IDE then the chip runs that firmware. If you upload the AT firmware then the chip runs the AT firmware and you can control it with AT commands. If you upload the NodeMCU Lua firmware then the chip runs the NodeMCU Lua firmware and you control it using Lua commands and scripts.


message:
Will a pull up resistor help the UART transmission accuracy on Arduino nano?

On [A post from Arduino forum][1] , someone mentioned that a pull up resistor over RX/TX pin could help the reliably of UART communication.

Is that really the case for nano and uno board?

  [1]: https://forum.arduino.cc/index.php?topic=282291.0

body:
No. That is not the case. Adding a pullup resistor on a normal UART will do nothing except maybe reduce your reliability.

You only want pullup resistors on something which is "open drain" (AKA "open collector") which has no way of raising the voltage of a signal line, only lowering it - such as I2C signals, or a shared open-drain, interrupt signal.


message:
Is it permissible to connect 3.3V powered devices to the 5V I2C bus?

I have several devices on the I2C bus:

 1. RTC [DS3231SN][1]
 2. [TMP100][2] temperature sensor
 3. EEPROM [24LC256][3]

All devices are powered by 3.3V. The voltage on the I2C bus is 5V.

**Question:**
Is the voltage difference on the bus and device power normal?

  [1]: https://eu.mouser.com/datasheet/2/256/DS3231-1513891.pdf
  [2]: https://www.ti.com/lit/ds/symlink/tmp100.pdf
  [3]: http://ww1.microchip.com/downloads/en/DeviceDoc/21203N.pdf

body: There are 3.3V devices that have 5V-tolerant inputs; that may be the case for your devices, but I would not risk it. Use a level converter designed for I2C, such as https://www.adafruit.com/product/757. Or you can make your own; https://cdn-shop.adafruit.com/datasheets/an97055.pdf explains how such a level converter works. Use a BSS138 if you are comfortable with soldering SMT components; otherwise use a 2N7000.


message:
How can I make a Parallax Servomotor move a water tap correctly and prevent from vibrations?

I am using Arduino Mega 2560

I have built an structure with plastic 3D pieces to move this water tap.:

![water_tap](https://i.stack.imgur.com/HRnLpm.png)

I am using the ["Servomotor Parallax Inc 140 mA, 4 6 V"](https://es.rs-online.com/web/p/servomotores/7813058/) to rotate the tap:

![servomotor](https://i.stack.imgur.com/10NJcm.png)

Some more images to show how I mounted it:

![mounted](https://i.stack.imgur.com/cT9mf.jpg)
![piece_for_thetap](https://i.stack.imgur.com/WNLZ8.jpg)
![another_piece](https://i.stack.imgur.com/qBehg.jpg)

[Video 1](https://youtu.be/vkz76wxOnTA). I tried to use the power of the arduino directly (5V). But the motor is not steady in all the positions I set, in some positions the noise you hear in the video do not stop, and my impression is that the motor will burn soon because it keeps pusshing all the time.

[Video 2](https://youtu.be/Szx_OhX2ELU). Without almost any load, the motor is also making a small sound. I don't know if you can appreciate it in the video. They are like cracks or clicks

Possible solutions:

* Is there a way to cut the power supply when the motor already moved the tap? Or just to stop the motor to keep pushing?
* Using a external power should solve the problem? I found [this tutorial](https://www.instructables.com/id/Arduino-How-to-Use-a-Servo-Motor-With-an-External-/) where they use that system. Which will be the benefits of that? It will fix the problem?
* Using another stronger servomotor?
* A [stepper motor](https://www.adafruit.com/product/324)?
* Is my servomotor faulty?
* Would I need some controller?

Any other suggestion?

body:
When you set a servo motor to be in a specific position it is constantly and actively striving to keep in that position. The feedback from the internal potentiometer is constantly being processed and the motor adjusted to ensure that it remains at the right position.  Potentiometers, of course, aren't 100% perfect, and there will always be a certain amount of "noise" in the signal that means the motor will always be making really tiny adjustments.

That's perfectly normal.

The simple way to stop it trying to keep precisely to one position is to stop telling it to be in that position.

1. `.attach()` the motor
2. Move it to the desired position
3. Wait long enough for the motor to get to that position
4. `.detach()` the motor

When you call `servo.detach()` the PWM signal is terminated and the motor no longer has a position to keep to - so it just stops doing anything and goes to sleep.

The down-side of this is that if you have a load under tension (for example if you are lifting a weight with the servo) the tension is then free to move the motor.


message:
How to connect to MQTT broker with TLS?

I have ESP8266 which is connecting to MQTT broker and it is working ok using user+pass with following code:

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

    const char* ssid = "WIFINAME";
    const char* password = "WIFI_PASS";

    const char* mqtt_server = "SERVER_IP";
    const char* mqttUser = "user";
    const char* mqttPassword = "pass";

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

    void setup_wifi() {

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

      WiFi.begin(ssid, password);

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

      randomSeed(micros());

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

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

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

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

    void setup() {
      pinMode(BUILTIN_LED, OUTPUT);
      Serial.begin(115200);
      setup_wifi();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);
    }

    void loop() {

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

As this is insecure usage I have setup TLS on MQTT broker and I can connect over command line:

    mosquitto_sub --cafile ca.crt -h server_ip  -t "#" -p 8883 -d --cert client.crt --key client.key

Problem is that I cannot find any working (for me) sample with using TLS connection on ESP8266 client.

I have tried generating self-signed certs by manually script and over LetsEncrypt.

Thank you

body:
You could make the following changes to your code by making use of WifiClientSecure (which is already part of the ESP8266 Wifi library).

The tricky part is finding out the SHA1 fingerprint for your own MQTT server and hard coding it into the __*fingerprint PROGMEM = "..."__  part (for example by examining the certificate via a PC browser and copying the SHA1 fingerprint).

Alternatively, you could set the connection to setInsecure. This means that the connection will be encrypted but it will accept any server certificate without checking.

    ...
    const char* mqttPassword = "pass";

    WiFiClientSecure espClient;     // <-- Change #1: Secure connection to MQTT Server
    PubSubClient client(espClient);

    // Change #2: Set the SHA1 fingerprint for the connection -->
    static const char *fingerprint PROGMEM = "44 14 9A 3F C3 E9 F1 F3 84 1A B4 9F B6 4D 19 8A B2 92 31 D6";
    ...
    ...
    void setup() {
        ...
        setup_wifi();

        espClient.setFingerprint(fingerprint);   // <-- Change #3: Set the SHA1 fingerprint
        // Alternative: espClient.setInsecure;

        client.setServer(mqtt_server, 8883);  // <-- Change #4: Set the port number to 8883
        client.setCallback(callback);
     ...

Good luck!


body:
There is an example of client certificates here.

https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino

I believe the answer by @StarCat should be expanded to use the ca cert and client certs.  With MQTT, we don't want clients being faked either.


message:
Why does per-led current consumption diminishes when more leds are on?

I'm rather new to Arduino. I've been performing some current consumption measurements lately, with a INA219 current sensor, on the blue LEDs from a starter kit.

I plugged three LEDs, on pins 2, 3, and 4 of my Arduino UNO, and wrote a simple script:

    digitalWrite(led1, 1);
    delay(2000);
 digitalWrite(led2, 1);
    delay(2000);
    digitalWrite(led3, 1);
    delay(2000);
 digitalWrite(led1, 0);
    digitalWrite(led2, 0);
    digitalWrite(led3, 0);

Which turns on the leds one by one, and finally turn them off at once.
I measured the current consumption of the first LED, and measured that:

 - When it's the only one on, LED 1 consumes ~23.5 mA
 - When the second one is on, LED 1 consumes ~21.7 mA
 - When the third one is on, LED 1 consumes ~20.2 mA

Could you please tell me why it behaves that way ? Is there any source I should read that would formalize that ?

Thank you

body:
If using a constant voltage source it is advisable to use current limiting resistors in series with LEDs.

If these LEDs are different colors that may explain the different current readings.

Or, if all LEDs are of the same color and you are powering the project from a source with internal resistance (a battery), the more current you draw the lower the supply voltage.  This may show up as a reduced incremental current increase.

Or, if using a poor power source or operating at the current capacity of the power supply - again - this may show up as a reduced incremental current increase.

Note that different generations of LEDs operate at slightly different voltages.  But, in general, RED, GREEN & BLUE LEDs of the same generation operate at slightly increasing voltages respectively.  Details can be found here in [this wikipedia.com page][1]:

> Typically, the forward voltage of an LED is between 1.8 and 3.3 volts.
> It varies by the color of the LED. A red LED typically drops 1.8
> volts, but since both voltage drop and light frequency increase with
> band gap, a blue LED may drop from 3 to 3.3 volts.

Use the LED current (Iled) and voltage (Vled) specifications to determine the proper resistor value for a given supply voltage (Vbatt).

The following equation from [this article][2] should prove useful for this calculation:

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

  [1]: https://en.wikipedia.org/wiki/LED_circuit
  [2]: https://www.nutsvolts.com/magazine/article/calculating_current
  [3]: https://i.stack.imgur.com/NPEJk.png


message:
Voltage at AREF pin

I find difficulties to measure correctly the voltage at the AREF pin.
I would measure voltages with a resolution not exceeding 1 mV . nda voltage divider
In one of my trials, I was using a  9V battery and a voltage divider made with a 1k resistor and a 2k one.

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

The battery voltage was about 8890 mV and the reference voltage was about 2960 mV (confirmed by a multimeter).
I  connected the output of the divider to the AREF pin of an Arduino Uno board. The output voltage value dropped to about 1800 mV. Reading the voltage value at AREF pin with a simple sketch:.

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

the serial monitor printed:

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

as if the voltage dividere did not exist.
What am I doing wrong? or what I don’t understand?
Thank you for your attention.

  [1]: https://i.stack.imgur.com/3bvsr.jpg
  [2]: https://i.stack.imgur.com/ybUtu.jpg
  [3]: https://i.stack.imgur.com/zwQ2C.jpg

body:
> I was using a 9V battery and a voltage divider made with a 1k resistor and a 2k one.

Using a battery is not a good way of getting a stable voltage. A battery's voltage will change over time.

Using a voltage divider is not a good way of generating a reliable stable voltage. The output impedance is very high and will be affected by any loading you apply to it causing it to droop.

If you want 1mV per LSB then you need a 1024mV voltage reference (since there are 10 bits of resolution, or 1024 possible divisions, in the ADC). For that you want a 1024mV voltage reference, which is a standard value for precision voltage reference chips such as the LM4140CCM-1.0/NOPB from Texas Instruments. Personally I like to use a precision DAC like the MCP4821 to provide a settable analog reference voltage.

> Reading the voltage value at AREF pin with a simple sketch the serial monitor printed 8890 as if the voltage dividere did not exist. What am I doing wrong?

You cannot read anything from the AREF pin. It is merely a voltage reference, not an active pin you can read. When you use `analogRead(EXTERNAL)` you are actually doing `analogRead(0)` since `EXTERNAL` is a macro that expands to `0`. That means you are really reading from pin A0 not the AREF pin.  And then you just map that to 8890 when it's at maximum anyway. Since A0 is (probably, since you don't show anything else in your circuit) floating it will most likely be above the voltage you are feeding in to AREF and will return 1023 all the time anyway.


message:
SIM800L - AT Commands not doing anything on Arduino Serial Monitor

I am trying to send AT commands to SIM800L through Arduino's Serial Monitor. However when I type any command in the serial monitor nothing happens. I'm using an Arduino MEGA 2560 and the TX/RX of the SIM800L is connected to 9 and 10 respectively. Here is the code:

```
#include <SoftwareSerial.h>

SoftwareSerial GPRS(9, 10);
boolean state, lastState;

void setup()
{
  pinMode(2, INPUT_PULLUP);
  state = digitalRead(2);
  lastState = state;

  GPRS.begin(9600);
  Serial.begin(9600);

  GPRS.println("AT+CMGF=1");

  delay(1000);
}

void loop()
{
  while(GPRS.available()) {
    Serial.write(GPRS.read());
  }

  lastState = state;
  state = digitalRead(2);

  if ( state != lastState ) {
    sendSMS();
  }

  delay(500);
}

void sendSMS() {
  Serial.print("Switch was turned ");
  Serial.println(state ? "on" : "off");

  GPRS.println("AT+CMGS=\"+64XXXXXXXXX\"");

  delay(500);

  GPRS.print("Switch was turned ");
  GPRS.println(state ? "on" : "off");
  GPRS.write( 0x1a ); // ctrl+Z character

  delay(500);
}
```
Any help would be much appreciated!

EDIT2: I forgot to mention but I am able to send, receive, and call from the GSM Module (with a different code). However I am not able to read the the received messages, since I only get a +CMT "SM", <index> message and I can't exactly use AT+CMGR or CMGL commands because the serial monitor does nothing with them. here's the code for that:
```
#include <SoftwareSerial.h>
SoftwareSerial sim(9,10);
int _timeout;
String _buffer;
String number = "+639XXXXXXXXX"; //-> change with your number
void setup() {
  delay(1000); //delay for 7 seconds to make sure the modules get the signal
  Serial.begin(9600);
  _buffer.reserve(50);
  Serial.println("Lets go!");
  sim.begin(9600);
  delay(1000);
  Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
}
void loop() {
  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        RecieveMessage();
        break;
      case 'c':
        callNumber();
        break;
    }
  if (sim.available() > 0)
    Serial.write(sim.read());
}
void SendMessage()
{
  Serial.println ("Sending Message");
  sim.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  Serial.println ("Set SMS Number");
  sim.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Wala kang jowa!";
  sim.println(SMS);
  delay(100);
  sim.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}
void RecieveMessage()
{
  Serial.println ("SIM800L Read an SMS");
  delay (1000);
  sim.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
  Serial.write ("Unread Message done");
}
String _readSerial() {
  _timeout = 0;
  while  (!sim.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (sim.available()) {
    return sim.readString();
  }
}
void callNumber() {
  sim.print (F("ATD"));
  sim.print (number);
  sim.print (F(";\r\n"));
  _buffer = _readSerial();
  Serial.println(_buffer);
}
```

body:
Do not use `SoftwareSerial` on a Mega2560 unless you *absolutely know what you are doing*.

SoftwareSerial does not work on many of the pins of the Mega2560, and since there are other *hardware* serial ports available there is seldom any reason to resort to using SoftwareSerial anyway.

Connect your SIM800L to the TX1/RX1 pins of the Mega2560 then communicate using the pre-defined `Serial1` object.


body:
 1. Make sure the RX of your arduino board is connected to TX of GSM and the TX should be connected in RX of GSM module.
 2. Next try to do this

```
   GPRS.begin(9600);
   Serial.begin(115200);
```
 3. Also double check your wirings, if you have a tester you might wanna check if both end are connected with each other. And in the loop try to print this `Serial.println(GPRS.available())` if it is not greater than 0 then you have a problem with your connection.

```
    #include <SoftwareSerial.h>
    SoftwareSerial sim(2,3);

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

    void loop() {
      // put your main code here, to run repeatedly:
      while(Serial.available() > 0){
        sim.write(Serial.read());
      }

      while(sim.available() > 0){
        Serial.write(sim.read());
      }
    }
```
> diagram reference. [![enter image description here][1]][1]

Hope this help.

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


message:
Initialize object with PROGMEM constants

I have a class which has a `const char *` property:
```c++
    class A
    {
    public:
     const PROGMEM char* text;
    };

    void setup()
    {
     // A a{"Hello World!"};
     // A a{PSTR("Hello World!")};

     A a;
     a.text = PSTR("Hello World!");

     Serial.begin(9600);
     delay(30);
     Serial.println(a.text);
    }

    void loop()
    {
    }
```

I’d like to spare some RAM using `PROGMEM`.

How to initialize `a` object then?

Obviously, it can’t be like this:
```c++
    A a{PSTR("Hello World!")};
```
This will do:
```c++
    A a;
    a.text = PSTR("Hello World!");
```
However, I need to pass string to the constructor.

body:
`const char* text;` is a pointer to constant not a constant pointer (`char * const text` is a constant pointer). So you can assign a pointer to a constant char array to `const char* text;` even a pointer to an array in PROGMEM.

The compiler doesn't know the difference between a PROGMEM pointer and a pointer in SRAM. It is on you to work in code with a pointer to PROGMEM the right way.

so remove PROGMEM from `const PROGMEM char* text;`

----------

add constructor to initialize an object.

    A(const char* _text) {
      text = _text;
    }

and then

    A a(PSTR("Hello World!"));

----------
EDIT:

you could use Arduino's F() macro and __FlashStringHelper type, because it is supported by Serial print and co.

    class A
    {
    public:
      A(const __FlashStringHelper* _text) {
        text = _text;
      }
      const __FlashStringHelper* text;
    };

    void setup()
    {
        A a(F("Hello World!"));

        Serial.begin(9600);
        delay(30);
        Serial.println(a.text);
    }

    void loop()
    {
    }

__FlashStringHelper type is trick to distinguish PROGMEM strings from char arrays in SRAM..


body:
It is a shame that gcc only supports the `__flash` qualifier in C mode,
not in C++, so we have to use `PROGMEM` instead. Unlike `__flash`, which
qualifies a variable just like `const`, the `PROGMEM` attribute only has
effect when allocating room for a variable. Once the allocation is done,
the compiler forgets about the attribute. In particular, a declaration
such as

```c++
const PROGMEM char* text;
```

does not allocate flash space, so it generates the warning

```text
warning: ‘__progmem__’ attribute ignored [-Wattributes]
     const PROGMEM char* text;
                         ^
```

You can thus forget the attribute when declaring a pointer, as there is
no such thing as a “pointer to `PROGMEM`”. You just use a `const char *`
instead.

Now, the second issue is that, as far as `Serial.println()` is
concerned, the pointer above is a plain `const char *`, so it will
interpret it as an address in RAM, and print garbage. If you want
`Serial.println()` to know you are giving it an address in flash, you
should provide it with a `const __FlashStringHelper*` pointer.

Here is the solution I propose. Tested on an Uno-compatible board:

```c++
class A
{
public:
    A(const char* s)
        : text(reinterpret_cast<const __FlashStringHelper *>(s)) {}
    const __FlashStringHelper* text;
};

void setup()
{
    A a{PSTR("Hello World!")};
    Serial.begin(9600);
    Serial.println(a.text);
}

void loop(){}
```

------------------------------------------------------------------------

**Edit**: After seeing the last version of Juraj’s answer, I must say
that I agree with him. Since we are using the Arduino API, it makes more
sense for the constructor to take a `const __FlashStringHelper*`, and
for the caller to use the `F()` macro.


message:
Gauss solver for IIR filter

I write a piece of code in online GDB using c++, the code calculates some coefficients for a IIR filter which tries to approximate a fractional derivative and integral for a fractional PID control. The code works as expected in the online IDE, but when I try to execute it in a Arduino Due, the results and only overflows and nan, and really don't know what's the problem so,

Here is the code in GDB online https://onlinegdb.com/rycwt62XL which gives the expected results:

Array A, Array B

 1.41421,1

-0.707107,0.5

-2.12132,-1.5

0.883883,-0.625

0.883883,0.625

-0.265165,0.1875

-0.0883883,-0.0625

0.0110485,-0.0078125

And here is the code for the Arduino Due, which only change the printing method using the serial commands, https://onlinegdb.com/ByAs5xyVU, and the results are:

Array A, Array B

ovf,1.00

ovf,ovf

ovf,0.00

inf,ovf

ovf,0.00

inf,ovf

ovf,3.89

inf,ovf

And really don't know where to start for fix this results, thanks. The Method is  exactly the same.

body:
I can't find the root cause of the problem - it's probably because the Due is possibly the worst board that Arduino ever made, and the compiler / linker / support libraries barely work at the best of times.

However, some things you need to look at in your code:

```
    double* h = new double[L];
    for(int n = 0; n <= L; n++){
        for(int k = 0; k <= n; k++){
            h[n] += pow(operador,-alpha-n+k)*pow(1.0-operador,n-k)*Binomial_E(alpha,k)*Binomial(-alpha,n-k);
        }
    }
```

There you allocate `L` (15) doubles in an array. But then you go on to access array slices 0-15. That's 16 entries in an array of size 15, so you're overflowing it and corrupting other memory.

Also you have no `delete` to balance the `new`, so you have a memory leak.  You would be better using:

    double h[L+1];

instead of `new`.


message:
Which board to use for wireless communication of small packages?

I was hoping to get your advice on what Arduino boards to look at for a project I'm working on. The project involves two separate boxes in different rooms of my apartment (~ 5-10 feet away from each other) and needs to allow wireless communication of very small amounts of information (think like 5 bytes). However, this transfer needs to be very rapid (within 200 milliseconds).

While I have worked a good bit with the Arduino Uno, I haven't worked with boards with Wifi capabilities.

The boards I know of are: Esp32, Esp8266, Arduino MKR 1010, Arduino Mega RobotDyn.

What would be the best board for a project like this / are there other boards that are well-suited for a project like this?

Thanks!

body:
WiFi round trip time is about 2-50 ms (50 is the worst case), so, you can use the ESP's and the UDP/TCP.

On the other hand, you can use the NRF433 module, but in this case, you have to develop your own channel level protocol, with error detection/correction and so on.

Also, there are [ZigBee][1] module. They developed for home automation specially.

  [1]: https://en.wikipedia.org/wiki/Zigbee


message:
Stepper motor is only moving one step at a time with an IR sensor

I am trying to get both the motors to run simultaneously once the motion detector senses an obstacle. Both motors run fine by themselves but when I implement the sensor the motors only move one step per motion detected.

- Arduino Mega (ATMega 2560)
- (2) NEMA 17 stepper motor/ A4988
- Digital IR Sensor Module

~~~
#include <Arduino.h>
#include <avr/io.h>
#include <AccelStepper.h>

AccelStepper stepper(1,5,4); // w/Driver (1,Step, Direction)
AccelStepper stepper2(1,9,8);

const int pin_ir_in = 3;
int prev_state = 1;
int curr_state = 1;
int counter =0;

void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT); // Enable
  pinMode(10,OUTPUT);

  digitalWrite(6,LOW); // Set Enable low
  digitalWrite(10,LOW);
}

void loop() {
  digitalWrite(6,LOW); // Set Enable low
  if (stepper.distanceToGo() == 0)
  {
    delay(1000);
    stepper.moveTo(100);
    stepper.setMaxSpeed(200);
    stepper.setAcceleration(100);

  }

   digitalWrite(10,LOW); // Set Enable low
     if (stepper2.distanceToGo() == 0)
  {
    delay(1000);
    stepper2.moveTo(100);
    stepper2.setMaxSpeed(200);
    stepper2.setAcceleration(100);

  }

int curr_state = digitalRead(pin_ir_in);
if (curr_state != prev_state)
{
  if (curr_state == 0)
  {
    stepper.run();  // Actually makes stepper move
    stepper2.run();
    delay(500);
  }
  prev_state = curr_state;

}

}
~~~

body:
As chrisl said, you need to call `run` repeatedly.

I tried to rewrite the code you've given, though I'm not entirely sure what it is you try to achieve.

    void loop()
    {
      stepper.run();  // Actually makes stepper move
      stepper2.run();

      int curr_state = digitalRead(pin_ir_in);
      if (curr_state != prev_state)
      {
        if (curr_state == 0) // Motion sensor activated
        {
          stepper.moveTo(100);
          stepper.setMaxSpeed(200);
          stepper.setAcceleration(100);
          stepper2.moveTo(100);
          stepper2.setMaxSpeed(200);
          stepper2.setAcceleration(100);
        }
        prev_state = curr_state;
      }
    }


message:
Which libraries for DS1302 real time clock and WS2811 LED strip do not conflict?

I am making a custom wall-clock, and need the Arduino (Uno or Nano) to connect to a DS1302 real time clock module and a WS2811 LED chain.

So I’m using [DS1302](http://www.rinkydinkelectronics.com/library.php?id=5) for the clock, and [FastLED](https://github.com/FastLED/FastLED) for the lights. Individually these two libraries work fine, so I can either echo the time to the serial console, or I can drive the LEDs as I need.

But when I combine them there is some conflict happening and I get no LED output. The LED data goes over pin 6 and the clock uses pins 2,3,4 (these pins are customisable in code).

Even just adding a DS1302 initialisation to a working FastLED sketch causes no more LED output

    #include <FastLED.h>
    #include <DS1302.h>

    #define NUM_LEDS 50
    #define DATA_PIN 6

    // Init the DS1302 - stops LEDs working
    DS1302 rtc(2, 3, 4);

    CRGB leds[NUM_LEDS];

    void setup() {
      FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
    }

    void loop() {
      for (int i=0; i<NUM_LEDS;i++) {
        leds[i] = CRGB::Red;
      }
      FastLED.show();
      delay(100);
    }

What are my troubleshooting steps - should I try alternative libraries, or could I dig into the libraries themselves and see what hardware resources they might be using?

I guess as both the lights and the clock probably operate over a serial protocol, it could be a conflict with the serial drivers - maybe both using the same time-critical operations.

Edit: inserted sketch which demonstrates the issue

body:
I installed a library from within the IDE as StarCat suggested.

https://github.com/Makuna/Rtc

    #include <FastLED.h>
    #include <ThreeWire.h>
    #include <RtcDS1302.h>

    #define NUM_LEDS 50
    #define DATA_PIN 6

    ThreeWire myWire(3,4,2); // IO, SCLK, CE
    RtcDS1302<ThreeWire> Rtc(myWire);

    CRGB leds[NUM_LEDS];

    void setup() {
       FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
       Rtc.Begin();
    }

    void loop() {
       RtcDateTime dt = Rtc.GetDateTime();

       for (int i=0; i<NUM_LEDS;i++) {
         leds[i] = CRGB::Red;
       }

    FastLED.show();
    delay(100);
    }

I am able to get and use the time, and the LED output works.


message:
NEO-6M is working but it doesnt show data

So I'm having a little bit of difficulty here in my NEO-6M. `The problem is it doesn't show any data in my serial monitor.` My NEO-6M Led is already blinking so its already ok.

    RX -> Pin3 , TX -> Pin4 , VCC -> 3.3v , GND -> GND

>Serial Monitor:
[![enter image description here][1]][1]

Code:
_<https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino>_

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

body:
I found a solution to my problem. On my first setup, I separate my GND of NEO-6M to Arduino and put connect it in breadboard that has powerboard on it because I thought it is only for electrical purposes but it doesn't since I encounter it.

Solution:
>The GND of every module must still connect on the Arduino.


message:
upload sketch via bluetooth for android

How can i convert file .ino to hex file so that i can compile new sketch via bluetooth. Can you help me to figure out the way to do this? thanks for helping

body:
It is very hard to understand exactly what you want to do, but from what I can gather you want to:

1. Write an Android application that lets you edit sketches
2. Compile those sketches on an android device, and
3. Upload those compiled sketches to an Arduino over Bluetooth

While what you are asking is *technically* possible, it is not *realistically* practical.

Writing a text editor in Android is easy enough. That's not a problem. It's the compilation of the code that is not practical.

You would need to port the compiler (a very large project written in C) to Android. That would essentially need to remain as compiled C code, and so you would have to individually port it to each possible platform you want it to run on (various different types of ARM, Intel, etc) and for different versions of android.

Unless you're a genius at Android and C programming that's just not going to happen.

A more practical way would be to write a web-based application that allows you to edit your sketches, which can then run the compiler on a real computer (no porting needed then), which can then download the compiled HEX file to your Android device, then use a pre-existing application to program that HEX file over bluetooth.

Alternatively, just use the Arduino Create website to compile and download your HEX file.


message:
ESP-12 + FTDi + platformio

I have 2 questions.

 1. Why we have to put our functions before void loop and void setup into VScode+platformio?
 2. I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

I have this Warning: ```src\main.cpp:46:24: warning: large integer implicitly truncated to unsigned type [-Woverflow]
 const byte menuColor = 0XF206;```

[EDIT]The problem comes from these lines:

```
attachInterrupt(digitalPinToInterrupt(enA), enAin, RISING);
attachInterrupt(digitalPinToInterrupt(enB), enBin, RISING);
attachInterrupt(digitalPinToInterrupt(enBtn), enBtnIn, FALLING);

body:
> Why we have to put our functions before void loop and void setup into VScode+platformio?

Because that is how C works. The Arduino IDE hides it from you by adding *function prototypes* at the start of your code.

> I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

    const byte menuColor = 0XF206;

That can never work. The value 0x06 will be assigned to menuColor since a byte is only 8 bits.  You need to learn to use data types that are suitable for the values you are trying to store in them.


message:
MB-102 BreadBoard Power Supply Limitation

>Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v? If yes, does 9v battery is enough? If no, please suggest me what should I use that uses only 1 barrel jack(if possible).

Im afraid that I might fry it if I try cause I dont have enough knowledge about electric currents.

body:
> Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v?

You mean because the current requirements? The answer is yes and no. No, because the needed current must not flow through the Arduino. The SIM900 draws up to 2A, that current would fry the protection diode/voltage regulator on the Arduino (though you may get away with a bit less than that by using a big capacitor to accommodate current spikes). Depending on the version of the Uno, it can provide 200mA or 1A (in case of rev3)(including what is needed for the Uno to operate). You need to provide the 5V of these modules from outside of the Arduino, via an extra voltage regulator, which can handle the big current.

> does 9v battery is enough?

If you mean the standard 9V block battery, then no, never. These batteries are meant for low power applications and are almost never a good choice for an Arduino project (unless you have really a low power application). You need to use different batteries, for example a series of AA batteries or a LiPo pack (including the needed circuitry for such a pack).


message:
Can I control a 28BYJ-48 5V stepper with a DVR8825 driver?

I have a stepper motor **28BYJ-48** rated 5 V and I want to use a **DVR8825** driver so I can use the 1/32 micro-stepping feature. My problem is that DVR8825 has a minimum operating voltage of 8.2 V. Would the 28BYJ-48 stand a 10 V input?

Is there any alternative to the DVR8825 that operates at 5 V and has at least 1/32 micro-stepping?

body:
Stepper motors are rated in two different ways. Some provide a "rated voltage" in combination with a "DC resistance", others provide a "phase current" and a "phase resistance". The way they operate is identical.

Stepper motors such as your 28BYJ-48 are usually intended to be driven with a fixed voltage, their rated voltage. At this voltage, the maximum permittable current flows in the steppers windings - determined mostly by cooling and wire thickness. If you exceed that voltage, more current will flow and will damage / destroy the stepper motor.

The DRV8825 is a current controlled stepper motor driver - it always uses the full available supply voltage - 8.2V+ - but uses PWM to limit the current actually flowing in the stepper. This is possible because the stepper motor coils are inductors, which inhibit the flow of current.

To use your stepper motor with a DRV8825 driver, you'll have to calculate the steppers equivalent "maximum phase current". According to [this datasheet][1], it's rated 5 V at 50 Ohms, giving us a current of 0.1 A. You can then set this current via the potentiometer on the driver chip. The Vref voltage should be set so that `Vref = Imax / 2`.
Start at a Vref of 50 mV, and see how warm the motor gets and whether it's as strong as you would expect it to be.

  [1]: https://www.digikey.at/de/datasheets/mikroelektronika/mikroelektronika-step-motor-5v-28byj48-datasheet


message:
Reading from 2 serial ports

I have 2 Arduino Nano, they are connected via ports 2 and A2

While I use only one port to receive, it works properly. But if I activate the second port, system crash (and even first port don't work properly)

Code of first Arduino:

    #include <SoftwareSerial.h>
    SoftwareSerial SerialPort2(2,A2);
    SoftwareSerial SerialPort3(3,A3);

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

    void loop() {
      delay(500);
      SerialPort2.listen();
      if(SerialPort2.available()){
        char value = SerialPort2.read();
        Serial.print(value);
        Serial.print(" First port\n");
      }
      // IF YOU REMOVE PART BELLOW, THE 'SerialPort2' WILL WORK PROPERLY
      SerialPort3.listen();
      if(SerialPort3.available()){
        char value = SerialPort3.read();
        Serial.print(value);
        Serial.print(" Second port\n");
      }
      // END OF THIS PART
    }

Code of second Arduino:

    #include <SoftwareSerial.h>
    SoftwareSerial SerialPort2(2,A2);

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

    void loop() {
      SerialPort2.write('a');
      delay(1000);
    }
PS in real system I need to listen 6 ports

body:
`SoftwareSerial` can only listen to one port at a time. You cannot listen to both, no way. To really listen to both, you need an Arduino with more hardware Serial ports, where most of the protocol is done in hardware, thus can receive without CPU intervention. The Arduino Mega has 4 hardware Serial ports.

Or you could impose a protocol on the Serial stream to make the listening Arduino the master. You would listen to the first serial interface, send a start byte over this interface, that tells the slave Arduino to start sending. It sends and the listening interface receives (The transmission has to be delimited by either a time limit, e.g. listen for a specific time, or by a stop byte). Then you listen to the next interface, send again the start byte and receive. And so on.

With such a protocol, you could even use a single serial interface. The protocol makes sure, that only one slave is transmitting at a time. Though you should add resistors to every slave to protect their TX pins.

> in real system I need to listen 6 ports

Serial (UART) is really not the best interface type for such topology. You should consider using interfaces like SPI. It doesn't need additional electronics and is better fit for multiple slaves.


body:
SoftwareSerial is only a "good" choice (for certain values of "good") if you only use *one* instance, and that is the *only* serial port in the system.

Using SoftwareSerial to read from 2 ports simultaneously is not possible.  Using SoftwareSerial to read data in tandem with any other hardware serial ports *will result it data loss*.

SoftwareSerial is only any real use when you are using it to request data from another device and times when you command it to happen.

To receive data in an "unsolicited" fashion SoftwareSerial is not good.

Instead you need a hardware serial port for *each* incoming signal. And obviously you can't do that with a small board like a nano.  So you need to think more creatively.

If you have one real serial port you can talk to one device. But there are other communication channels at your disposal. So you take one board and have that communicate to one of your serial devices. Then you take the data read and convert it into another communication protocol that is capable of sharing time with other boards. Then that, and 5 other boards, all send their data (or get data from) one central "master" board.  In effect you have 6 "UART to Protocol X" converter boards, and one "Protocol X" master board.

Alternatively choose a board that has 6 UARTs. There are many higher-end chips like some ATSAMD, SAMX, and PIC32 chips, that have 6 UARTs available to you.


message:
How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port

.

I am using a black pill to read RFID-rf522 to read a tag (SPI) and send it to raspberry pi through a USB (using DM and DP pins).

Quick responses are welcomed.

body:
You can use the one provided by generating it with [STMCubeMx][1]. This is going beyond arduino though. But it is highly feasible.

  [1]: https://www.st.com/en/development-tools/stm32cubemx.html


message:
Arduino Analog to Digital Conversion from 56V DC Batteries

I have a problem, I am using 56V DC combined batteries system. I get ADC values comes to Arduino like 211, 217 etc... I have to find out when the DC volt drop to 42V. How do i know the digital value for the ADC from Aruino.

body:
I'll assume you're using Li-Ion batteries in 14s configuration. You'll want to measure voltages up to around 60 V while charging. With a bit of safety margin, I'd set it up to measure up to 72V without damaging the Arduino - which can measure voltages up to 5 V, but the input on that pin should never exceed 5.5 V.

To bring your battery voltage down to something the Arduino can use, you'll need to use a voltage divider, as [chrisl suggested][1].

[![Schematic, allaboutcircuits.com][2]][2]

With R1 = 10 kOhm and R2 = 680 Ohm, you'd get readings up to an input voltage of 78 Volts.

With `analogRead()` returning values between 0 and 1023, your 42 V cutoff would be around 546.

  [1]: https://arduino.stackexchange.com/questions/72739/arduino-analog-to-digital-conversion-from-56v-dc-batteries#comment159022_72739
  [2]: https://i.stack.imgur.com/ZqJpf.png


body:
**Warning: this is going to get math-heavy**

Ok. So you have a battery with a voltage divider on it, and you are using the Aruino ADC to read the output of that voltage divider. And you want to "back-calculate" the battery voltage from the ADC reading.

First let's look at exactly what happens with a voltage divider and just how it works. For that we'll turn to good ol' Ohm's Law.

Rule number one is that two resistors in series *sum* their resistances. So if you have a 10kΩ and 680Ω resistor in series (as suggested in @towe's answer) the total resistance is 10680Ω.  We'll use this arrangement as our example.

Now Ohm's Law states that the current flowing through a resistive load is directly proportional to the voltage across it. So for a fixed resistance and a given voltage we can calculate the current that will be flowing through the resistors.  That formula is:

# ***I=V/R***

So for a voltage of 56V and a resistance of 10680Ω we can say that the current is 56/10680 amps - or about 5.24mA.

Great. But so what? Well, now we can reverse the formula and find the voltage across a given resistance for that specific current. Which we can do for, for example, the 680Ω resistor.  We know that the same current is flowing through both resistors (since they are in series), so flipping the formula around we get:

# ***V=I×R***

So at 0.00524 amps and 680Ω that's 0.00524×680 = 3.57V.  We can do the same for the 10kΩ resistor: 0.00524×10000 = 52.43V.  And oh look - if we add those two voltages together, what do we get? We get 56V. The resistors have divided the voltage into two portions.

You can combine those two formulae together to give you:

# ***VOUT = VIN × (R2 / (R1 + R2))***

And if we move the VIN to the left hand side we get:

# ***VOUT / VIN = (R2 / (R1 + R2))***

And that is known as the *transfer function*, or the ratio of the input to output voltage of the voltage divider.

For a 10kΩ (R1) and 680Ω (R2) resistor pair we get 680/10680 = 0.0637.

And that is the "magic number" we want to calculate back from the ADC to the battery voltage.  Whatever the voltage we read at the ADC the battery voltage is the reciprocal of that number times bigger (reciprocal is "one over the value").  The reciprocal of 0.0637 is 15.7.  So if you read the value from the ADC then convert that into a voltage relative to the internal reference voltage (approximately 5V for a normal Arduino) then multiply that voltage by 15.7 you will get your battery voltage.

So next is to get the ADC voltage. And again, it's all ratios.  The ADC gives you a number that is a ratio of the incoming voltage to the reference (5V) voltage.  At 1023 you get "5V minus 1 LSB", so about 4.995V. We don't need that kind of accuracy for this, really, so we'll just call it 5V.

Say you read 482 from the ADC, if you convert that into a voltage you take the ratio 482/1024 and multiply it by the reference voltage (1024 is the range of a 10-bit ADC - you would change that for other types of ADC):

# ***VIN = 482 / 1024 × 5 = 2.35V***

Multiply that by our "magic number" 15.7 and you get 36.95V - and that's the battery voltage.


message:
Read amount of I/Os in code

I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists.

Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?

body:
It depends on the core, but most provide the macro `NUM_DIGITAL_PINS` which tells you the number of digital pins the board has.  In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence).

So you can use:

    if (pinNumber < NUM_DIGITAL_PINS) {
        digitalWrite(pinNumber, HIGH);
    } else {
        Serial.println("Invalid pin number");
    }

In tandem with that you also usually have `NUM_ANALOG_INPUTS`.


body: The number of the GPIO pins available depends on how the chip is wired on the Arduino Board and which microcontroller one is running on. For example, an Arduino Uno with a ATMega328p chip has 14 Digital I/O pins, whereas an Arduino Mega 2560 with a chip has 54 digital I/O pins.


message:
What to do with Arduino floating pins?

I have some unused pins, should I connect them together and to the ground or leave them floating?

[![][1]][1]

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

body:
The simplest thing to do is set them to INPUT_PULLUP.  If you want a purely hardware solution then you could connect them to GND through some resistors (10kΩ or whatever you have in that kind of order of magnitude will do).

You don't want to just tie them directly to ground, and you don't want to link them directly together - that could lead to short circuits and dead IO ports if any of the pins happened to get set as output and HIGH in software.


body: Leaving them floating in most cases won't do any harm. Even touching the pins won't destroy anything. Tying extra external hardware is just unnecessary (though a 10k resistor would be harmless as well). Of course, you could also think about potential extra usages for those pins if you want to make your design a bit "future-proof". For example, adding 4k7 pull-up resistors to A4 and A5 and a connector could allow you to use the I2C interface for additional functions.


body: I saw instability with a kiosk audio player I built years ago, when I left the unused pins floating.  Once I grounded them through a 10k resistor, all was OK.  This was in a very dry environment so I suspect static was the problem.


message:
Decoding RF receiver signals

By using the following draft i decode the signals from an RF receiver

    #define CH1 2
    #define CH2 3
    #define CH3 4
    #define CH4 5
    #define CH5 6
    #define CH6 7

    int ch1Time, ch2Time, ch3Time, ch4Time, ch5Time, ch6Time = 0;
    void channels()
    {
      TCNT1 = 0;
      ch1Time = 0; ch2Time = 0; ch3Time = 0; ch4Time = 0; ch5Time = 0; ch6Time = 0;

      while ((PIND & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
      {
        if (PIND & (1 << CH1))
          ch1Time = TCNT1;

        if (PIND & (1 << CH2))
          ch2Time = TCNT1;

        if (PIND & (1 << CH3))
          ch3Time = TCNT1;

        if (PIND & (1 << CH4))
          ch4Time = TCNT1;

        if (PIND & (1 << CH5))
          ch5Time = TCNT1;

        if (PIND & (1 << CH6))
          ch6Time = TCNT1;
      }
    }

The issue is that i need also to use the 6 PWM's of the nano board.
So i thought of moving the channels 1-6 to the analog pins like so..

    #define CH1 A0
    #define CH2 A1
    #define CH3 A2
    #define CH4 A3
    #define CH5 A4
    #define CH6 A5

    while ((PINC & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
      {
        if (PINC & (1 << CH1))
          ch1Time = TCNT1;
    etc...

but it simply does not work. Any thoughts please?

body:
I see two immediate problems:

1. The macros A0-A5 are the numbers 14 to 19, not the numbers 0 to 5 - so you're looking at (1 << 14) for CH1 not (1 << 0).
2. The analog pins are port C not port B, so you need to use `PINC` not `PINB`.
3. Your `ch?Time` variables should be `volatile`.


message:
serial 1 was not declared in the scope

#include <LiquidCrystal.h>
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    #include <SoftwareSerial.h>

    char Mob[20]="+923319020922";
    String stringGPS = "";
    String stringGPS1 = "";
    char c=0;
    int t=0,i;
    int buzzer = 9;
    int buttonState = 0;

    SoftwareSerial mySerial(10, 11); // RX, TX

    //const int buttonPin1 =9 ;
    int buttonState1 = 0;
    int helmetstate=0;
    const int relay=8;
    char inByte=0;

    void setup()
    {
      lcd.begin(20, 4);
      lcd.setCursor(0, 0);
      pinMode(relay, OUTPUT);
      pinMode(buzzer, OUTPUT);
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial2.begin(9600);
      digitalWrite(relay, LOW);
      delay(15000);
      lcd.print("Config modem....");

      Config();

      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Smart helmet      ");
    }

    void loop()
    {
      if(Serial2.available())
      {
        inByte = Serial2.read();
        //Serial.write(inByte);
        if(inByte=='A'||inByte=='B'||inByte=='C'){
        inByte=0;
        SMS(Mob);

        while(Serial2.available()>0)
        {
          i = Serial2.read();
        }
      }

      if(inByte=='D')
      {
        digitalWrite(relay, LOW);
        inByte=0;
      }

      if(inByte=='E')
      {
        digitalWrite(relay, HIGH);
        inByte=0;
      }
      else
      {
      }
    }

     //buttonState = digitalRead(buttonPin);
     // if (buttonState == LOW) {
     //Serial.print("ok");
     //lcd.clear();
     // lcd.setCursor(0, 0);
     //lcd.print("Sending msg       ");
     // lcd.setCursor(0, 0);
     //lcd.print("Smart helmet      ");
     // checkGPS();
     // SMS(Mob);

     //helmet();
     checkGPS();
     lcd.setCursor(0, 1);
     lcd.print(stringGPS1);
     //Serial.println(stringGPS1);
    }

    /*
    void helmet()
    {
      buttonState1 = digitalRead(buttonPin1);
      if (buttonState1 == HIGH)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("SWITCH ON  .......    ");
        digitalWrite(relay, HIGH);
      }
      else
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("SWITCH OFF .......    ");
        digitalWrite(relay, LOW);
      }
    }
    */

    void checkGPS()
    {
      // Serial.print("check gps");
      // while (Serial.available())
      // {
      if (Serial.available()>0)
      {
       // c = Serial.read();
       // stringGPS  = c;
       //Serial.print(c);
       while (c != 'R')
       {
         c = Serial.read();
         // Serial.print(c);
       }
        // if (c== 'R')
        // {
        //   Serial.print(c );
             while(t!=41)
             {
               if (Serial.available())
               {
                 c = Serial.read();
                 stringGPS += c;
                 t++;
                 //Serial.print(stringGPS );
              }
      }
      stringGPS1= stringGPS.substring(15, 41);
      // Serial.println(stringGPS1);
      t=0;
      c=0;
      stringGPS = "";
        // }
      }
      }

    void SMS(char Mob[20])
    {
       digitalWrite(buzzer, HIGH);
       lcd.setCursor(0, 0);
       lcd.print("Sending msg       ");
       Serial1.print("AT+CMGS=\"");     // send the SMS number
       Serial1.print(Mob);/// Send mobile number
       Serial1.print("\"\r");
       delay(4000);
       Serial1.print(stringGPS1);// send the SMS Data
       Serial1.print("\r");
       delay(2000);
       Serial1.write(0x1A);  ///Ctrl+Z
       delay(1000);
       Serial1.write(0x0A);  ///Carrige return
       delay(1000);
       Serial1.write(0x0D);    ///line feed
       delay(1000);
       stringGPS1 = "";
       lcd.setCursor(0, 0);
       lcd.print("Smart helmet      ");
       digitalWrite(buzzer, LOW);
    }

    void Config()/////configuration for sim900
    {
      delay(4000);
      Serial1.print("ATE0\r"); ////Disable Echo
      delay(4000);
      Serial1.print("AT\r"); ///checking echo
      delay(4000);
      Serial1.print("AT+CMGF=1\r");///msg format
      delay(4000);
    }

when i run this code it give me error that serial1 was not decleared in the scope

body:
The only **SoftwareSerial** you a declaring is `SoftwareSerial mySerial(10, 11); // RX, TX
`
(And you you didn't use it afterwards).

If the hardware serials `Serial1`, `Serial2` or `Serial3` are available
(and already declared in the `arduino.h` header depends on the board you are using.


message:
MCore(Arduino) - Python bluetooth communication

Pc and Mcore with bluetooth module are paired. The port is COM9 outgoing in PC. However, when I send message Arduino does not get anything. I just disconnect arduino from pc and write simple code in Mcore that turn on LED when input message is 1. However still nothing. These are the codes in python and arduino side:

    import time
    import serial

    port="COM9"          #This will be different for various devices,COM port.
    bluetooth=serial.Serial(port, 9600)         #Start communications with the bluetooth unit
    bluetooth.flushInput()      #This gives the bluetooth a little kick
    bluetooth.write(b'1')       #These need to be bytes not unicode
    bluetooth.close()          #Otherwise the connection will remain open until a timeout

Arduino code:

    char a;

    void setup()
    {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
    }

    void loop()
    {
    if(Serial.available()){a = Serial.read();}

    if (a == '1'){
      digitalWrite(13, HIGH);
      }

      else{
      digitalWrite(13, LOW);}

      delay(100);
    }

I have tried to install Pybluez for WIN10, however, there was error. Do you think that this is the reason?

Thanks in advance

body: kindly add a serial print before the if statement(```if (a == '1')```) to see what value of a is recieved so we can debug it


body:
Probably because you never called `bluetooth.open()`.

What would be much easier to do is use [pySerialTransfer][1] and [SerialTransfer.h][2] to guarantee reliable and robust serial communication between Python and your Arduino.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs and come with examples.

  [1]: https://github.com/PowerBroker2/pySerialTransfer
  [2]: https://github.com/PowerBroker2/SerialTransfer


message:
Line not printing int in Serial Monitor

I'm trying to make a kernel for a macro-key maker, this is the starting page's code:

    char m[] = "What do you want to do? Type the following commands in this "
          "terminal:\nnew  --> Creates a new Keybinding\ndelete  --> Deletes a "
          "previous Keybind\nlookup --> Find what is bound to a key\n\nTurn off the "
          "switch to go back to the normal mode.";
    Serial.println(m);
    Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

When I run it, the screen displays:

    What do you want to do? Type the following commands in this terminal:
    new  --> Creates a new Keybinding
    delete  --> Deletes a previous Keybind
    lookup --> Find what is bound to a key

    Turn off the switch to go back to the normal mode.

 The last line is missing.  Is this a problem with object casting? `takenKeybind` is an `int`.

body:
You should never do this:

    Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

Yes, it *should* cope with it and append the strings, but that's really nasty even if it does work. And there is absolutely no call to ever do concatenation when printing to serial.

Instead just use:

    Serial.print(takenKeybinds);
    Serial.println(F("/64 Keybinds taken."));

Note also the use of the `F()` macro when printing a string literal. This keeps the string in flash and prevents it being copied to RAM, which is just wasteful.

The same with your big long string - it's wasting RAM, and if you never want to modify it, why have it in RAM? Better is:

    Serial.println(F("What do you want to do? Type the following commands in this terminal:"));
    Serial.println(F("new  --> Creates a new Keybinding"));
    Serial.println(F("delete  --> Deletes a previous Keybind"));
    Serial.println(F("lookup --> Find what is bound to a key"));
    Serial.println();
    Serial.println(F("Turn off the switch to go back to the normal mode."));


message:
Arduino NANO (CH340) error while flashing bootloader

Ok. So I'm close to tearing me hair out on this one.

I have a batch of cheap Arduino Nano clones, that just straight up won't work. (I HAVE gotten one of them to work, but I suspect that was by pure coincidence)

Anyway, I feel like I've tried everything to make them work.
I am consistently getting

> Device signature = 0xffffff

errors from avrdude, which I believe is a hardware problem. Up til now I have tried:

 - Installed CH340 drivers, no difference
 - Tried to burn bootloader using Uno as an ISP (with 10uF cap between reset and ground!)
 - Tried the "(Old Bootloader)" option in the IDE

All I have left is to desolder the entire board and troubleshoot each single component, but... no, I want to keep my sanity intact, thaaank you!

Any ideas on how I should move forward here?

body: Hit reset randomly in the first few seconds of uploading/burning.


message:
ESP32 HTTPS server - how to get POST request string

I'm trying to set up an ESP32 (DOIT ESP32 DEVKIT V1 in the Arduino IDE, with Espressif's WiFi libraries) with the following includes so far:
```
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <HTTPSServer.hpp>
#include <SSLCert.hpp>
#include <HTTPRequest.hpp>
#include <HTTPResponse.hpp>
```
Now, if I have a callback routine that's set up with
```
ResourceNode * nodeEchoPost = new ResourceNode("/cmd", "POST", &handleEcho);
```
how can I parse out the POST request string? On the serial console I get
```
[HTTPS:I] Request: POST /cmd
```
which is a debug output from the HTTPSRequest library itself. But I have no clue how to get that '/cmd' string for my own use!
I've tried the example code of
```
byte buffer[256];
size_t s = req->readBytes(buffer, 256);
```
getting a buffer that only returns garbage, probably because all the request is in the POST statement and the body is empty.

Since all I need is the request-info
```
'/cmd?command1=foo&command2=bar&etc'
```
to chop up and use, well.. how do I get that out from the library? I've been googling around, and looking in the library header files, without much luck.

Also, is there any advantage to using the WiFiClientSecure library instead, since everything already goes over HTTPS? That's more of a side question, though if it makes it easier to grab the Request string that way, I'm totally fine with accepting that.

body:
I think I found the answer, by looking through examples in the github repo of Hessel's HTTPS library.

In short, this seems to be it:
```
void handleEcho(HTTPRequest * req, HTTPResponse * res) {

Serial.print("in handleEcho. request is:");
Serial.println(req->getRequestString().c_str());
```
Output from serial console:
```
"in handleEcho. request is:/cmd?command1=foo&cmd2=bar"
```
Now I have a plain-text string that I can use plain string commands on to chop up in parts with strtok or similar. I don't mind the extra hassle of finding keywords in the string, I'm happy to just have _gotten_ the damn thing.

Since I have all the data I want in that request, I'll just use req->readBytes as mentioned in examples to empty the buffer and discard all 'body' data.

And someone's gotta agree with me that adding the .c_str() to an already existing function just seems extra complicated. :/


body:
That's a GET and not a POST, so variables are accessible with

    auto params = req->getParams();
    std::string command1;
    std::string cmd2;
    bool hascommand1 = params->getQueryParameter("command1", command1);
    bool hascmd2 = params->getQueryParameter("cmd2", cmd2);

See example at
https://github.com/fhessel/esp32_https_server/blob/master/examples/Parameters/Parameters.ino

The `.c_str()` is required to transition from std::string to what println needs, not a problem related to the getRequestString() function itself

I came across this question while looking for ways to read actual POST variables, which is not documented (and the source code does not show sign of it)


message:
Arduino Ethernet shield frequently drops its IP address

Im working on a sketch that needs to display some internal variable values and analogue reads in a simple webpage. The only catch is that it *needs* to be as reliable as possible.

Im getting some odd behaviour across multiple shields where the sketch will work briefly (sometimes as long as 5-6 minutes) before cutting out and setting the IP to something weird (commonly 0.0.0.0 or something similar)

My main loop has some other code in it for reading buttons, values, sensors, etc, but the bulk of it is basically

    void loop()
    {
      ... do some stuff ...
      // listen for incoming clients
        EthernetClient client = server.available();
        if (client) {
            Serial.println("new client");
            // an http request ends with a blank line
            boolean currentLineIsBlank = true;
            while (client.connected()) {
                if (client.available()) {
                    char c = client.read();
                    Serial.write(c);
                    // if you've gotten to the end of the line (received a newline
                    // character) and the line is blank, the http request has ended,
                    // so you can send a reply
                    if (c == '\n' && currentLineIsBlank) {
                        // send a standard http response header
                        client.println("HTTP/1.1 200 OK");
                        client.println("Content-Type: text/html");
                        client.println("Connnection: close");
                        client.println();
                        client.println("<!DOCTYPE HTML>");
                        client.println("");
                        // add a meta refresh tag, so the browser pulls again every 5 seconds:
                        client.println("<meta http-equiv=\"refresh\" content=\"5\">");
                        // output the value of each analog input pin
                        client.println(getStrDivByTag("MyWebPage", "h3"));
                        client.println("
");

                        client.println("");
                        break;
                    }
                    if (c == '\n') {
                        // you're starting a new line
                        currentLineIsBlank = true;
                    } else if (c != '\r') {
                        // you've gotten a character on the current line
                        currentLineIsBlank = false;
                    }
                }
            }
            // give the web browser time to receive the data
            delay(1);
            // close the connection:
            client.stop();
            Serial.println("client disconnected");
        }

      ... do some more stuff ...

    }

When the server is working as expected, my serial output gives me something like:

> new client

>GET / HTTP/1.1

>Host: 192.168.1.17

>User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:73.0)
Gecko/20100101 Firefox/73.0

>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

But just before it stops working, I get two back to back requests:

> GET / HTTP/1.1 Host: 192.168.1.17 User-Agent: Mozilla/5.0 (X11;

> Ubuntu; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0 Accept:

> text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

> Accept-Language: en-CA,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip,

> deflate Connection: keep-alive Upgrade-Insecure-Requests: 1

> Cache-Control: max-age=0

>

> client disconnected Current Draw: -0.341

> 192.168.1.17 new client GET /favicon.ico HTTP/1.1 Host:
192.168.1.17 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux
x86_64; rv:73.0)

> Gecko/20100101 Firefox/73.0 Accept: image/webp,*/* Accept-Language:

> en-CA,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate Connection:
> keep-alive Cache-Control: max-age=0
>

> client disconnected Current Draw: -0.048

> 0.0.0.0

>Accept-Language: en-CA,en-US;q=0.7,en;q=0.3

>Accept-Encoding: gzip, deflate

>Connection: keep-alive

>Upgrade-Insecure-Requests: 1

>Cache-Control: max-age=0

>client disconnected

What is that request, something about favicon.ico? After these back to back requests, the IP resets to 0.0.0.0, sometimes jumping to something odd like 0.64.1.0, 0.1.0.64, etc.

Is there an issue with my network configuration, the ethernet2 library Im using?

body:
There are many Ethernet sketch examples that are not reliable at all. They basically handle the network setup in setup(), and the TCP connections in loop(). This is wrong. It just means that if there is anything wrong in your network connection, it won't restart correctly. You should check Ethernet.localIP(); and restart your sketch if it doesn't fit.
This routine should do the trick : void reset() { asm volatile ("jmp 0"); }

Also, you should be ready for requests for a favicon.ico from usual browsers (that's the small icon that comes in your tabs and favorites) and reply to it (you can use a 404 reply if you don't want to send a file). Providing a robots.txt is also good practice.


message:
How can I make the Serial Monitor work with the Serial Commands library?

I am using the library [**`SerialCommands`**](https://github.com/ppedro74/Arduino-SerialCommands) and I am just trying to print the first text message in the Serial Monitor. But this code does not work for some reason.

The expected result is that the Serial monitor prints a message ("Hello world !!") when I write "hello" and press "enter" as input. Is there something wrong or is this not working like I was expecting? Is there another way to check if these commands work? Is there anythin that I am missing?

    #include <SerialCommands.h>

    char serial_command_buffer_[32];
    SerialCommands serial_commands_(&Serial, serial_command_buffer_, sizeof(serial_command_buffer_), "\r\n", ",");

    void cmd_hello(SerialCommands* sender) {
      sender->GetSerial()->println("Hello world !!");
    }

    SerialCommand cmd_hello_("hello", cmd_hello);

    void cmd_unrecognized(SerialCommands* sender, const char* cmd) {
      sender->GetSerial()->print("ERROR: Unrecognized command [");
      sender->GetSerial()->print(cmd);
      sender->GetSerial()->println("]");
    }

    void setup() {
      Serial.begin(9600); // Serial comm begin at 9600bps
      serial_commands_.AddCommand(&cmd_hello_);
      serial_commands_.SetDefaultHandler(&cmd_unrecognized);
      Serial.println("Ready");
    }

    void loop() {
      serial_commands_.ReadSerial();
    }

body: You defined, that every command will end with `\r\n`. So you need to choose "Both NL & CR" as line ending in the Serial monitor, so that it appends the line ending to your command. If you don't send the correct line ending, the library will think, that the command hasn't finished yet, and thus will do nothing, until it receives the correct line ending.


message:
How to connect MPU6050 with Arduino Uno without using A0-A5 pins?

Connecting MPU6050 with Arduino without using A0-A5 pins.

body:
You could use a Software I2C library, like [this one on github][1], which can be used on almost any pin of a board. But keep in mind, that doing such communication in software imposes some limits (for example the linked library can only be a master). Keeping it in hardware is often the better choice, depending on your requirements.

  [1]: https://github.com/felias-fogg/SoftI2CMaster


message:
Reading sensor with current ouput with Arduino

I am having diffuclt times with this sensor, so I kndliy ask for your help!
The sensor is named "SPUVA-CS-C3535-A", datasheet here.
The sensor I use (cs3535) has just two pins (+ and -).
From my undesrstanding the ouput is a current corresponding on the UV light exposed to this sensor.
Max value of the current is difficult to understand from the datasheet that also do not have a typical suggested circuit. It seems that a medium value is 200nA, it seems really low!
I have connected (+) of the sensor to 3.3V, (-) of the sensor to A0, and a 220ohm resistor from A0 to Gnd. But readings are always 0.
Any help would be really appreciated! Thanks

body:
The "sensor" is just a photodiode that is sensitive to UV. You use it the same as any photodiode.

The simplest (and crudest) way is to use a very large (eg 1MΩ) pullup resistor to 5V on an ADC pin, then connect the sensor (reverse biased) between the ADC pin and GND.


message:
How can I display text on OLED?

I'm trying to print the information, which is received from the other ESP32 by CAN transceiver, on an OLED. The CAN bus is working perfectly, as the 'HELLO WORLD' is already be received. But I can't print the received 'HELLO WORLD' on OLED (also the OLED is work). The code shows below,
<!-- language-all: lang-cpp -->

    #include <CAN.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 32 // OLED display height, in pixels

    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

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

      if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        Serial.println(F("SSD1306 allocation failed"));
        for (;;);
      }
      delay(2000);
      display.clearDisplay();
      display.setTextColor(WHITE);

      Serial.println("CAN Receiver");
      CAN.setPins(16, 17);
      // start the CAN bus at 500 kbps
      if (!CAN.begin(500E3)) {
        Serial.println("Starting CAN failed!");
        while (1);
      }
    }

    void loop() {
      // try to parse packet
      int packetSize = CAN.parsePacket();

      if (packetSize) {
        // received a packet
        Serial.print("Received ");

        if (CAN.packetExtended()) {
          Serial.print("extended ");
        }

        if (CAN.packetRtr()) {
          // Remote transmission request, packet contains no data
          Serial.print("RTR ");
        }

        Serial.print("packet with id 0x");
        Serial.print(CAN.packetId(), HEX);

        if (CAN.packetRtr()) {
          Serial.print(" and requested length ");
          Serial.println(CAN.packetDlc());
        } else {
          Serial.print(" and length ");
          Serial.println(packetSize);

          // only print packet data for non-RTR packets
          while (CAN.available()) {
            Serial.print((char)CAN.read());
          }
          Serial.println();
        }

        Serial.println();
      }
      delay(5000);

      display.clearDisplay();

      display.print((char)CAN.read());

      display.display();
    }

body:
Just guessing but looks to me like you read the `CAN` message and print it character by character to the Serial console but you don't save those characters in a buffer as you get them from `CAN.read()`.

So when you then try to `display.print((char)CAN.read());` at that point there are no more characters to available for the `CAN.read()` to read so nothing is printed by the `display.print()`.

So what you need to do is to read the characters into a buffer so that you save them after reading them so that you can use the text string for other purposes.


message:
Controlling VFD with ModBus RTU via RS485 and Arduino

I am attempting to control a Folinn VFD (Manual: [Manual][1]) with an Arduino Uno via a MAX485 module [such as this][2].

 - Pins for MAX485:
    - DI > D8
    - DE & RE > D10
    - RO > D11

VFD settings:

   - F00.01 set to 2
   - F00.06 set to 9
   - F13.00 set to 1
   - F13.01 set to 5
   - F13.02 set to 3

At this stage I am attempting a very simple code just to turn the VFD on:

    /*

       ModBus RTU control VFD

       Address               : 01H  (is the address of the VFD)
       Function              : 06H  (write function code)
       Starting data address : 20H
                             : 00H  (2000H  is the address of control command)
       Data(2Byte)           : 00H
                             : 01H  (0001H is forward command)
       CRC CHK Low           : 43H
       CRC CHK High          : CAH

    */

    #include <SoftwareSerial.h>

    #define SSerialRX        11  //Serial Receive pin
    #define SSerialTX        8  //Serial Transmit pin
    #define SSerialTxControl 10   //RS485 Direction control
    #define RS485Transmit    HIGH
    #define RS485Receive     LOW
    #define Pin13LED         13

    // From manual vfd Forward command = 01H 06H 2000H 0001H 43CAH

    byte request1[] = {0x01, 0x06, 0x20, 0x00, 0x00, 0x01, 0x43, 0xCA};

    SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
    byte byteSend;

    void setup()
    {
      // Start the built-in serial port, probably to Serial Monitor
      Serial.begin(9600);
      Serial.println("SerialRemote");  // Can be ignored

      pinMode(Pin13LED, OUTPUT);
      pinMode(SSerialTxControl, OUTPUT);

      // digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

      RS485Serial.begin(9600);

    }
    void loop()
    {
        digitalWrite(SSerialTxControl, RS485Transmit);
        RS485Serial.write(request1, sizeof(request1));

    }

With the MAX485 connected to the correct ports (S+ and S-) on the VFD, this current setup receives no response is someone able to spot where I am going wrong? I have taken the values for CRC CHK Low & High from a different example, is this the issue?

Have also tried setting F00.01 to an unlisted '3' setting that I have seen pop up in other discussions but this made no difference. Any advice would be much appreciated, let me know if I can supply further details.

(I chose this method based on [this example][3]

  [1]: https://cononmotor.com.au/wp-content/uploads/2017/09/BD600-Manual.pdf
  [2]: https://www.ebay.com.au/itm/RS485-Transceiver-Communication-Module-MAX485/283525020751?hash=item4203687c4f:g:DcoAAOSwebpdDuuf&frcectupt=true
  [3]: https://forum.arduino.cc/index.php?topic=663365.0

body:
User on other site (https://forum.arduino.cc/index.php?topic=663365.0) Might have default run conditons on VFD set differently or by hardware.

Check the VFD is listening to the ModBus Comms.  OK.

Check VFD is 'Ready to Run'. Hardwire e-stop or 'Active' inputs.
F00.22 Check Binding source
F00.05 Check Set min Hz
F01.01 Check Set min Hz

Give drive MIN Hz So when received RUN signal has default speed to goto.

Are you doing a Hard Reset on the UNO every time you want to send the Modbus string? Code runs once, does not actively transmit.


message:
Adafruit thermal printer prints weak

I am currently hooking up my arduino to an adafruit mini thermal printer. When a button is pressed, some code is executed which then sends some information to the thermal printer.

Everything works fine except the thermal printer print is very weak and can barely be seen as soon as the printer needs to print more than 3-5 chars. Any ideas why? Both, the arduino and the thermal printer are hooked up to 9V batteries.

Here is the code
```cs
#include "Adafruit_Thermal.h"

// Here's the new syntax when using SoftwareSerial (e.g. Arduino Uno) ----
// If using hardware serial instead, comment out or remove these lines:

#include "SoftwareSerial.h"
#define TX_PIN 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define RX_PIN 5 // Arduino receive   GREEN WIRE   labeled TX on printer

SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor

int buttonIn = 8;
int val = 0;

void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, LOW);

  pinMode(buttonIn, INPUT);

   mySerial.begin(19200);  // Initialize SoftwareSerial
   //Serial.begin(19200); // Use this instead if using hardware serial
   printer.begin();        // Init printer (same regardless of serial type)
}

void loop() {
  // put your main code here, to run repeatedly:
     val = digitalRead(buttonIn);
     if(val == HIGH)
     {
        printer.println("test");
        printer.sleep();      // Tell printer to sleep
        delay(3000L);         // Sleep for 3 seconds
        printer.wake();       // MUST wake() before printing again, even if reset
        printer.setDefault();

     }
}
```
Did I set up anything false? Is the power supply not enough?
The adafruit was sent with a selftest from the seller where everything seemed to be fine.

Left, seller test, second from left, my selftest, third and fourth from left are example printer and charset tests.

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

And here you can see how everything is wired together.

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

Thank you very much!

  [1]: https://i.stack.imgur.com/EkVc1.jpg
  [2]: https://i.stack.imgur.com/NwnLR.jpg

body:
The datasheet states:
Requires 5-9VDC @ 1.5Amp power supply during print.

In my experience this printer provides best results when operated at its upper limit. I am using a 9V 2A power supply for that. A bettery is definitiverly not enough.


body:
Proper care of your thermal transfer printer is critical to keeping it at peak performance for as long as possible. Keep reading for five tips to keep your thermal transfer printer running optimally so you don’t have to spend on unnecessary new parts or wasted media down the line.

1. Maintain The Right Heat And Speed Ratio
These two things are true:

High print speeds can improve throughput
Higher heat increases the darkness of your print and therefore the contrast of your barcodes.
However, the wrong ratio can lead to print issues and even damage your printhead.

We generally recommend running your printer on a relatively slow setting. This uses less heat and ensures a crisp, clear printed image. On a similar note, we recommend you avoid increasing heat settings without guidance from a professional.

If you work with a supplier who sets up and tests your printer with your media prior to shipping it to you, they have likely adjusted the heat and speed ratio to one suitable for your application.

Maintaining a proper heat and speed ratio will ensure a scannable barcode and extend the life of your printhead so you can avoid costly waste and unnecessary part replacements.

2. Keep The Print Head Clean
Keeping your print head clean is imperative to maintaining your printer. Without regular cleaning, your print head will be more susceptible to abrasion during printing. This can reduce image quality and shorten the life of your printer.

We recommend you establish a schedule for regular print head cleaning. Our technical team endorses cleaning this part whenever you replace the label roll or install a new ribbon.

3. Protect The Print Head From The Media
To safeguard the print head against abrasion, use a thermal transfer ribbon that’s slightly wider than the media.

4. Don’t Use Razor Blades Or Box Cutters
Unless you’re using a model with a peeler or applicator, you should only use tools such as the printer’s tear bar or scissors to remove labels. Razor blades, box cutters, and other inappropriate tools can easily slip and cut the driver roller. These cuts can create voids in your printed labels leading to misreads.

5. Avoid “Ribbon Wrinkles”
If you’re seeing seemingly random diagonal lines on your print you’re probably dealing with ribbon wrinkles. The main culprit of ribbon wrinkles is too much heat, so your first option is to lower the heat setting. If that doesn’t work, make sure your printer is set up properly. Check that the ribbon is loaded correctly, the media guides are set properly, and the head pressure is balanced. If you’re still experiencing issues you might want to reach out to your supplier to ensure your media and ribbon combination is ideal.

Regards,
Peter