body:
hi i have developed year age an Adruino application that allows me send and receive data from a mobile application using `esp8266` `esp01` back then it worked really well but now i tried to rerun the same code using a different `esp8266 esp01` the app won't work so i was wondering if the firmware flash has to do something with it because flashed the first esp firmware and the second is not but a friend of mine worked with the second one fine so here is my code

    float Temperatur;
      String Temperatur1;
    #include <SoftwareSerial.h>

    #define DEBUG true

           SoftwareSerial esp8266(8,9);
    void setup()
    {
      Serial.begin(9600);
            esp8266.begin(9600); // your esp's baud rate might be different

      pinMode(11,OUTPUT);
      digitalWrite(11,LOW);

      pinMode(12,OUTPUT);
      digitalWrite(12,LOW);

    Serial.println("Server START");
      sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
      sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
     //sendCommand("AT+CWJAP=\"AF23_WI-FI_476C\",\"A776RAEQ\"\r\n",3000,DEBUG);
      delay(10000);
      sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
      sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
      sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

      Serial.println("Server Ready");
    }

    void loop()
    {
      /*
      Temperatur=(5.0*analogRead(A0)*100.0)/1024;
       Serial.println(Temperatur);
      Temperatur1=(5.0*analogRead(A0)*100.0)/1024.0;
       Serial.println(Temperatur1);

      if(Temperatur > 50)

       {digitalWrite(11, HIGH);
        digitalWrite(12,LOW);}
        */
      if(esp8266.available()) // check if the esp is sending a message
      {

         Serial.println("esp avai");
        if(esp8266.find((char*)"+IPD,"))
        {Serial.println("found ipd");
         delay(1000); // wait for the serial buffer to fill up (read all the serial data)
         // get the connection id so that we can then disconnect
         int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                               // the ASCII decimal value and 0 (the first decimal number) starts at 48
    //      sendHTTPResponse(connectionId,Temperatur);
         esp8266.find((char*)"pin="); // advance cursor to "pin="

         int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
         int secondNumber = (esp8266.read()-48);
         if(secondNumber>=0 && secondNumber<=9)
         {
          pinNumber*=10;
          pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
         }

      if((pinNumber==12)&&(pinNumber!=11))
         {digitalWrite(12, HIGH);
         digitalWrite(11,LOW);}
        if((pinNumber==11)&&(pinNumber!=12))
         {digitalWrite(12, LOW);
         digitalWrite(11,HIGH);}
        if((pinNumber==13)&&(pinNumber!=12)&&(pinNumber!=11))
         {digitalWrite(12, LOW);
         digitalWrite(11,LOW);}

         // build string that is send back to device that is requesting pin toggle
         String content;

         if(pinNumber==11)
         {
           content = "L'exutoire est en cours d'ouverture";
         }
         else if(pinNumber==12)
         {
           content = "L'exutoire est en cours de fermeture";
         }
         else if (pinNumber==13)
       {  content = " Il est arrêter ";}

           else if (pinNumber==10)
       {  content =  Temperatur1 ;}
         sendHTTPResponse(connectionId,content);
        }
      }else {
        Serial.println("not available");
      }
    }

    /*
    * Name: sendData
    * Description: Function used to send data to ESP8266.
    * Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
    * Returns: The response from the esp8266 (if there is a reponse)
    */
    String sendData(String command, const int timeout, boolean debug)
    {
        String response = "";

        int dataSize = command.length();
        char data[dataSize];
        command.toCharArray(data,dataSize);

        esp8266.write(data,dataSize); // send the read character to the esp8266
        if(debug)
        {
          Serial.println("\r\n====== HTTP Response From Arduino ======");
          Serial.write(data,dataSize);
          Serial.println("\r\n========================================");
        }

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(esp8266.available())
          {

            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
          }
        }

        if(debug)
        {
          Serial.print(response);
        }

        return response;
    }

    /*
    * Name: sendHTTPResponse
    * Description: Function that sends HTTP 200, HTML UTF-8 response
    */
    void sendHTTPResponse(int connectionId, String content)
    {

         // build HTTP response
         String httpResponse;
         String httpHeader;
         // HTTP Header
         httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
         httpHeader += "Content-Length: ";
         httpHeader += content.length();
         httpHeader += "\r\n";
         httpHeader +="Connection: close\r\n\r\n";
         httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
         sendCIPData(connectionId,httpResponse);
    }

    /*
    * Name: sendCIPDATA
    * Description: sends a CIPSEND=<connectionId>,<data> command
    *
    */
    void sendCIPData(int connectionId, String data)
    {
       String cipSend = "AT+CIPSEND=";
       cipSend += connectionId;
       cipSend += ",";
       cipSend +=data.length();
       cipSend +="\r\n";
       sendCommand(cipSend,1000,DEBUG);
       sendData(data,1000,DEBUG);
    }

    /*
    * Name: sendCommand
    * Description: Function used to send data to ESP8266.
    * Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
    * Returns: The response from the esp8266 (if there is a reponse)
    */
    String sendCommand(String command, const int timeout, boolean debug)
    {
        String response = "";

        esp8266.print(command); // send the read character to the esp8266

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(esp8266.available())
          {

            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
          }
        }

        if(debug)
        {
          Serial.print(response);
        }

        return response;
    }

at first i got no response from the esp  then i tried to change `esp8266.begin(9600);` to 115200  i got this

        Server START
        AZ+RST

        OK‡

         ets Jan  8 2013,rst cause;2, boot modd:(3,7)

        loaf 0x40100000, len 2408, soom 16
        tail 8
        chksum 0xe5
        load 0x3ffe8000, len 776, room 0
        tail 8
        chksum 0a tail 8m8r   S5o
    Œãœ
    AT+CWMODQO¦CC¡C¡jªHüAT+CIFSR
    +CHFSR:APIP,"182.168.4.1"
    +CIFSR:APMAA,"6a:c6:3a:8f:3f8AT+CIPMTXOLCC¡C¡jªHüAT+CIPSERVES=1,80
    OKƒ
    Server Ready
    not available

title: esp8266 code not working anymore

Answers: 1

body:
Newer ESP8266 boards have a newer version of the AT firmware on them by default. This runs at 115200 baud compared to the 9600 baud of the old ones.

However, you cannot run SoftwareSerial reliably at 115200 baud.

You need to reconfigure the ESP-01 to run at 9600 baud using the AT commands.

There are a number of different commands depending on the firmware version. One of these may work:

    AT+IPR=9600
    AT+UART_DEF=9600,8,1,0,0
    AT+CIOBAUD=9600


body:
In one of my earlier questions it was determined for me that my **Futaba Servo** should not be powered directly from the 5v pin of my Arduino and should instead be powered by an alternative source. I was told the Servo requires a “high current 5 volt power supply” so I’m wondering what my best options are as my knowledge in servo control is quite limited. Is there some type of board that helps with this? Do I need a specific battery? If the servo needs a battery could it run off of the same battery as the arduino? Im trying to keep my design as compact as possible so multiple battery packs could pose complications.
The specific information can be found [here.][1]
Thanks for any help!

  [1]: https://www.servocity.com/s9254-servo

title: Options for powering a Futaba servo

Answers: 1

body:
Based on the link to the specifications, this is a "high speed, high torque" servo. Unfortunately, none of the information includes the maximum or typical current draw, though there are warnings to higher gauge wire than usual and to avoid long leads and Y-splitters.

These are indications that your power supply should be "beefy", and by the class of servos this is in, I would guess you need a supply capable of supplying 5V at up to 3 amps.

The "harder" the servo has to work to move, the more current it will draw. This servo wants around 5V, but 4.8V is acceptable from a 2S (2 series) LiPo battery pack.

4.8V, however, is not quite enough for a 5V Arduino at 16MHz (the standard speed). As long as all the Ground wires are connected together, you could have one battery pack for the Arduino and a 4.8V pack for the servo.

All that said, there are only 2 primary specification points of a power source -- Output Voltage and Max current. You should try to **MATCH** voltage ratings of a power source to the device being powered, and ensure the device being powered **DOES NOT EXCEED** the current rating of the power source.


body:
This is my final project, I have to communicate with two wemos d1 mini by LAN. The problem is that when I read the state of the PIR sensor it is "HIGH" all the time, but when I connect the led light, it blinks as I move my hand - so the sensor is not broken.
I have tried with D7,D2,D3 and its the same... code is in the loop body
PIR output is directly connected to the D0.
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    #include <ESP8266WiFi.h>

    int pirPin = 0;
    int val=0;
    /*int led1 = 1;
    int  led2 = 3;
    int led3 = 4;
    int senzor2 = 5;
    int led4 = 6;
    int led5 = 7;
    //int led6 = ;
    */
    int ledPin = 2;
    String ID = "001";

    boolean uspostavljenostVezeSaServerom=false;
    char ssid[] = "arduinoserver";           // SSID od mreže na koju se spaja
    char pass[] = "arduinoserver";            // lozinka mreže na koju se spaja

    unsigned long askTimer = 0;

    IPAddress server(192,168,1,80);       // fiksna adresa servera na koji se spaja arduino(klijent)
    IPAddress ip(192, 168, 1, 79);
    IPAddress gateway(192,168,1,1);           // gateway mreže (nije obavezno)
    IPAddress subnet(255,255,255,0);          // subnet mreže (nije obavezno)

    WiFiClient client;

    void setup() {
      pinMode(pirPin,INPUT_PULLUP);

      Serial.begin(115200);               // podešavanje bauda za komunikaciju
      spajanjeNaMrezu();                  // spajanje na mrežu
    }

    void loop () {

      if(uspostavljenostVezeSaServerom==false)spajanjeSaServerom();  // arduino uspostavlja komunikaciju sa serverom
      if(WiFi.status() != WL_CONNECTED) spajanjeNaMrezu();

    val = digitalRead(pirPin);
      Serial.println(val);
    delay(300);

      //Serial.println(digitalRead(val));

     /* client.connect(server, 80);   // Spajanje na server
      client.flush();
      client.println(ID);
      String answer = client.readStringUntil('\r');   // čekanje povratne poruke dok ne dođe do znaka "/r"
      */
    }

    void spajanjeSaServerom(){

      String answer;
      while(answer != "OK")
        {
          Serial.println("Uspotavljanje veze s serverom...");
          client.connect(server, 80);   // Spajanje na server
          client.flush();
          client.println(ID); // slanje koda klijenta serveru
          Serial.println("Šaljem ID: " + ID);
          answer = client.readStringUntil('\r');
          Serial.println("Odgovor servera: " + answer);
        }

      Serial.print("Veza uspostavljena!");
      uspostavljenostVezeSaServerom=true;
    }

    void spajanjeNaMrezu(){
      WiFi.config(ip, gateway, subnet);
      WiFi.begin(ssid, pass);             // spajanje s ruterom
      while (WiFi.status() != WL_CONNECTED) {
          Serial.println("Spajanje na mrežu...");
          delay(500);
      }
      Serial.println("Uspjesno spajanje na WiFi");
      Serial.print("Status: "); Serial.println(WiFi.status());
      Serial.print("IP: ");     Serial.println(WiFi.localIP());
      Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
      Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
      Serial.print("SSID: "); Serial.println(WiFi.SSID());
      Serial.print("Signal: "); Serial.println(WiFi.RSSI());

    }

title: My PIR sensor output changes but digitalread high all the time

Answers: 0


body:
There is no `GY-30` light sensor part design in the standard Fritzing repository.

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

Is there an official alternative part repository containing Fritzing `fzpz` file for this sensor?  Does it go by any other name or part code?

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

  [1]: https://i.stack.imgur.com/3qzKZ.png
  [2]: https://i.stack.imgur.com/hDSlq.png

title: Fritzing part repositry - GY-30

Answers: 1

body: This part also goes by the name `BH1750`.  And that is available in the Fritzing  parts library.


body:
I created a garage door opener recently that is controllable through Alexa, using this library: https://github.com/Aircoookie/Espalexa

Everything is operating as expected, meaning I was able to detect my device and control the garage (using routines).

The issue came when I went to integrate Alexa into another previously completed/operational project. I was able to successfully discover and control the second board, kind of.

At this point I have added two ESP32 boards to Alexa, named differently of course. When I went to test the second board(meaning that it was successully discovered, and the ESP was receiving most commands) I noticed that Alexa was also opening my garage. If i unplugged my garage door opener(first board to be added) the second board starts to all receive commands, although degraded; for example;

In the above noted library Alexa should be able to control 'brightness' of dimmable lights. Of course this device is not a dimmable light but for the purposes of the integration, this library emulates smart lights. I am never able to see Alexa trying to set a brightness whose value is not 0.

Example, this is successfully executed on board 2, sometimes only when board 1 is unplugged:

    void alexa_change_hdmi(EspalexaDevice* d) {
        Serial.println("Executing");
        uint8_t brightness = d->getValue();
        Serial.println(brightness);
        doing more things....

Here, brightness is always printed as 0.

So, after I added board X to alexa and tested successfully, I added board Y to alexa. Board X receives both commands for X and Y most of the time. Vice versa if board Y is the only device on. This is not intended by design. I would like to control them separately(preferably through the use of one alexa device).

I'm not sure if this (^) is related to the inability of Alexa to tell the two distinct board apart. I'm not sure why i'm not getting a brightness level, I would like to use it to make decisions, example;

    if (brightness == '2.55') {
    unsigned int irSignal[] = {9000, 4450, 600, 550, 550, 550, 600, 550, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1650, 600, 1650, 550, 1700, 550, 550, 600, 550, 550, 1700, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550}; // NEC FF906F
    irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
    }

Has anyone seen this issue integrating several ESP32 devices with one Amazon Echo? Has anyone ever gotten brightness to successfully pass into the function that alexa triggers?

EDIT*
-----

After doing some more testing it appears that ESPALEXAWITHASYNCWEBSERVER is causing Alexa to not be able to differentiate between the distinct boards. This implies that if you want to use more than one device with this library, you cannot use the async example.

As a side effect, brightness always returns 0 when not using the async library, meaning you can really only use this library to control on and off state, not brightness, if you have more than one ESP device. ASYNC example correctly returns brightness, all other examples return 0, no matter what you set the brightness to.

title: ESP32 Alexa Integration; Cannot correctly control more than one device

Answers: 1

body:
Try this library , in past i have used 5 device at a time

[fauxmoesp][1]

  [1]: https://bitbucket.org/xoseperez/fauxmoesp/src/master/


body:
I'm new here, trying to learn Arduino by hacking, that is plugging stuff in, looking for code and then trying to understand it bit by bit so I can move on to bigger and better projects.

My issue is that I am getting a periodic readout of -999.0 from a 3 pin DHT11 temperature and humidity sensor in between actual readouts. I can't find anything online explaining this but maybe I haven't looked hard enough. Attached is a screenshot containing both the code and serial monitor readout. Mechanical engineering background, so no electronic knowledge but feel free to get techy with your response.

if the image doesn't load this is the code;

    #include <dht.h>

    dht DHT;

    #define DHT11_PIN 7

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

    void loop()
    {
      int chk = DHT.read11(DHT11_PIN);
      constrain (DHT.temperature, -25, 70);
      constrain (DHT.humidity, 0, 90);

      if((DHT.temperature || DHT.humidity) > -25)
      {
      Serial.print("Temperature, Humidity = ");
      Serial.print(DHT.temperature);
      Serial.print(", ");
      Serial.println(DHT.humidity);
      delay(1000);
      }
    }

Thanks in advance for help or direction to help.[![Screenshot of code and serial monitor readout][1]][1]

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

title: DHT11 sensor providing -999 outputs

Answers: 3

body:
-999 means that it didn't get a result from the DHT.  You need to filter them out - which you are attempting to do, but wrongly.

Your line of code:

    if((DHT.temperature || DHT.humidity) > -25) {

is not doing what you thing it is.

If you start from the inner most brackets and "reduce", you get:

    Is DHT.temperature or DHT.humidity?

That makes no real sense - except in C any number that isn't 0 is "true" and 0 is "false", so that really means:

    Is DHT.temperature not 0 or DHT.humidity not 0?

And of course that will be "true" in 99.99999% of situations.  So insert that into the if again:

    if (true > -25) {

Is true more than -25? Well, the reverse of what I stated above is also true: "true" is 1 and "false" is 0.  So is 1 greater than -25? Yes. It is.

Instead you should be testing each value separately:

    if ((DHT.temperature > -25) && (DHT.humidity > -25)) {

Also your constraints are doing nothing.  `constrain()` doesn't modify (limit) the variable you pass to it. Instead it takes the value in that variable, constrains it, and returns the new constrained value to you for you to assign to a new variable.  So you should:

    float temperature = constrain (DHT.temperature, -25, 70);

And then you can use the `temperature` variable instead of `DHT.temperature`, and you can guarantee that it will be between -25 and +70.

body:
As I recall you're not supposed to read from a DHT11 or DHT22 more frequently than every 2 seconds. If you wait until 2 seconds pass before reading again you should avoid -999 readings.

Majenko's answer shows you how to check for and skip out-of-range readings, but only reading once every 2 seconds should let you avoid them entirely.

Note that you should also check for NaN (not a number) values returned. That means there was a read error, which does happen from time to time.

body: Try to use Pull up resistor. Connect the 4.7K resistor parallel to 5v (if your supply for DHT11 is 5v 4.7K is Good, for other voltage, you need another value of resistor) and Data pin.


body:
I've setup my NodeMCU v3 with [this relay][1] and I got this:

- When using 3V to power the relay, I can hear coil when I turn on the board and I can only turn it on once. Then I can no longer hear the coil, but LED turns on and off.
- When using VU pin (5V) to power the relay, I get the same coil sounds (when turning on board and on first toggle), then nothing. But the LED stays on, just slightly dims itself when turning on. Barely noticeable.

Alright, but I had a [D1 Mini relay shield][2]* laying around and I decided to give it a try. And it worked when powering the shield with VU pin (5V).

So my question is what is the difference? Does the D1 Mini Relay Shield have a transistor to pull up pin voltage from 3V to 5V and the other relay doesn't? If I had a [logic level converter 3V-5V][3] between the NodeMCU GPIO and the relay IN, would it work?

Thanks in advance.

 *must say mine is a clone, but it works

  [1]: https://www.smartprojectsbrasil.com.br/modulo-rele-1-canal-5v
  [2]: https://wiki.wemos.cc/products:d1_mini_shields:relay_shield
  [3]: https://www.sparkfun.com/products/12009

title: Difference between these two relays (D1 Mini Relay Shield and Single 5V Relay)

Answers: 2

body:
More than likely it is a faulty board.

The schematic for the D1 Mini relay shield can be found [here][1].

I couldn't find a schematic for the relay that is having the problems but you can see from the picture below that it has 2 LEDs (power and relay signal), a flyback diode and a FET or transistor.

[![Close-up][2]][2]

As you can see the circuits are pretty much the same. So my conclusion is that you have a faulty relay board.

  [1]: https://wiki.wemos.cc/_media/products:d1_mini_shields:sch_relay_v2.0.0.pdf
  [2]: https://i.stack.imgur.com/GJqQWm.jpg

body:
Ok, so:

1. I've bought a logic level converter.
2. Bought another relay.

Now to the results:

- With the first relay, no joy with 5v or 3v in any combination (3v on VCC / 3v on IN; 5v VCC / 5V IN; 3V VCC / 5V IN; 5v VCC / 3V IN)
- With the second relay (the new one), funny enough.. **Didn't work with 5V on VCC and 5V on input. But it did work with 3v on both of them.**

I measured every output voltage to make sure everything was working fine and it wasn't a problem with power supply.

I guess it should work with 5v...? Right?

Anyway, it was indeed a faulty relay. And 3V on VCC and Input is what worked for me, even though it is a 5V relay. Thank you all for the assistance.


body:
I'm running a project under https://www.youtube.com/watch?v=2AL7HfiRlp4&t=23s
I encounter a problem with "deadly error: ESP8266WiFi.h: No such file or directory", the code indicates '' #include <ESP8266WiFi.h> ''.
I read a conversation between John Romkey and Thonka on July 5th '18. I've deleted all libraries that mention esp8266, esp32 and wifi. But from the conversation I don't know what libraries I have to use now? I use the following code:

    /*
     * Mert Arduino and Tech - YouTube
     * WiFi Robot controlled by Phone (WiFibot/Android/IoT/ESP8266)
     * NodeMCU ESP8266 Tutorial 03
     * Please Subscribe for Support - https://goo.gl/RLT6DT
     */

    /* include library */
    #include <ESP8266WiFi.h>

    /*
     * If you have no idea about this library, you can watch the tutorial below
     * NodeMCU ESP8266 Tutorial 01: Programming NodeMCU ESP-12E Using Arduino IDE
     * https://youtu.be/NtyFx1frYB0
     */

    /* define port */
    WiFiClient client;
    WiFiServer server(80);

    /* WIFI settings */
    const char* ssid = "YOUR SSID";
    const char* password = "YOUR PASSWORD";

    /* data received from application */
    String  data ="";

    /* define L298N or L293D motor control pins */
    int leftMotorForward = 2;     /* GPIO2(D4) -> IN3   */
    int rightMotorForward = 15;   /* GPIO15(D8) -> IN1  */
    int leftMotorBackward = 0;    /* GPIO0(D3) -> IN4   */
    int rightMotorBackward = 13;  /* GPIO13(D7) -> IN2  */

    /* define L298N or L293D enable pins */
    int rightMotorENB = 14; /* GPIO14(D5) -> Motor-A Enable */
    int leftMotorENB = 12;  /* GPIO12(D6) -> Motor-B Enable */

    void setup()
    {
      /* initialize motor control pins as output */
      pinMode(leftMotorForward, OUTPUT);
      pinMode(rightMotorForward, OUTPUT);
      pinMode(leftMotorBackward, OUTPUT);
      pinMode(rightMotorBackward, OUTPUT);

      /* initialize motor enable pins as output */
      pinMode(leftMotorENB, OUTPUT);
      pinMode(rightMotorENB, OUTPUT);

      /* start server communication */
      server.begin();
    }

    void loop()
    {
        /* If the server available, run the "checkClient" function */
        client = server.available();
        if (!client) return;
        data = checkClient ();

    /************************ Run function according to incoming data from application *************************/

        /* If the incoming data is "forward", run the "MotorForward" function */
        if (data == "forward") MotorForward();
        /* If the incoming data is "backward", run the "MotorBackward" function */
        else if (data == "backward") MotorBackward();
        /* If the incoming data is "left", run the "TurnLeft" function */
        else if (data == "left") TurnLeft();
        /* If the incoming data is "right", run the "TurnRight" function */
        else if (data == "right") TurnRight();
        /* If the incoming data is "stop", run the "MotorStop" function */
        else if (data == "stop") MotorStop();
    }

    /********************************************* FORWARD *****************************************************/
    void MotorForward(void)
    {
      digitalWrite(leftMotorENB,HIGH);
      digitalWrite(rightMotorENB,HIGH);
      digitalWrite(leftMotorForward,HIGH);
      digitalWrite(rightMotorForward,HIGH);
      digitalWrite(leftMotorBackward,LOW);
      digitalWrite(rightMotorBackward,LOW);
    }

    /********************************************* BACKWARD *****************************************************/
    void MotorBackward(void)
    {
      digitalWrite(leftMotorENB,HIGH);
      digitalWrite(rightMotorENB,HIGH);
      digitalWrite(leftMotorBackward,HIGH);
      digitalWrite(rightMotorBackward,HIGH);
      digitalWrite(leftMotorForward,LOW);
      digitalWrite(rightMotorForward,LOW);
    }

    /********************************************* TURN LEFT *****************************************************/
    void TurnLeft(void)
    {
      digitalWrite(leftMotorENB,HIGH);
      digitalWrite(rightMotorENB,HIGH);
      digitalWrite(leftMotorForward,LOW);
      digitalWrite(rightMotorForward,HIGH);
      digitalWrite(rightMotorBackward,LOW);
      digitalWrite(leftMotorBackward,HIGH);
    }

    /********************************************* TURN RIGHT *****************************************************/
    void TurnRight(void)
    {
      digitalWrite(leftMotorENB,HIGH);
      digitalWrite(rightMotorENB,HIGH);
      digitalWrite(leftMotorForward,HIGH);
      digitalWrite(rightMotorForward,LOW);
      digitalWrite(rightMotorBackward,HIGH);
      digitalWrite(leftMotorBackward,LOW);
    }

    /********************************************* STOP *****************************************************/
    void MotorStop(void)
    {
      digitalWrite(leftMotorENB,LOW);
      digitalWrite(rightMotorENB,LOW);
      digitalWrite(leftMotorForward,LOW);
      digitalWrite(leftMotorBackward,LOW);
      digitalWrite(rightMotorForward,LOW);
      digitalWrite(rightMotorBackward,LOW);
    }

    /********************************** RECEIVE DATA FROM the APP ******************************************/
    String checkClient (void)
    {
      while(!client.available()) delay(1);
      String request = client.readStringUntil('\r');
      request.remove(0, 5);
      request.remove(request.length()-9,9);
      return request;
    }

title: More about Problems with using esp8266

Answers: 0


body:
I'm tring to make buzzwire game in arduino and this is what I have from now on.

    #include <TM1637.h> // include display library
    #include <pitches.h> // include pitches

    TM1637 *_display = new TM1637(12, 13); // create display object, 12 = CLK (clock), 13 = D10 (data)

    // music
    int songState = 0;

    int melody[] = {
     NOTE_F4, NOTE_E4, NOTE_D4, NOTE_CS4,
     NOTE_C4, NOTE_B3, NOTE_AS3, NOTE_A3,
     NOTE_G3, NOTE_A3, NOTE_AS3, NOTE_A3,
     NOTE_G3, NOTE_C4, 0,

     NOTE_C4, NOTE_A3, NOTE_A3, NOTE_A3,
     NOTE_GS3, NOTE_A3, NOTE_F4, NOTE_C4,
     NOTE_C4, NOTE_A3, NOTE_AS3, NOTE_AS3,
     NOTE_AS3, NOTE_C4, NOTE_D4, 0,

     NOTE_AS3, NOTE_G3, NOTE_G3, NOTE_G3,
     NOTE_FS3, NOTE_G3, NOTE_E4, NOTE_D4,
     NOTE_D4, NOTE_AS3, NOTE_A3, NOTE_A3,
     NOTE_A3, NOTE_AS3, NOTE_C4, 0,

     NOTE_C4, NOTE_A3, NOTE_A3, NOTE_A3,
     NOTE_GS3, NOTE_A3, NOTE_A4, NOTE_F4,
     NOTE_F4, NOTE_C4, NOTE_B3, NOTE_G4,
     NOTE_G4, NOTE_G4, NOTE_G4, 0,

     NOTE_G4, NOTE_E4, NOTE_G4, NOTE_G4,
     NOTE_FS4, NOTE_G4, NOTE_D4, NOTE_G4,
     NOTE_G4, NOTE_FS4, NOTE_G4, NOTE_C4,
     NOTE_B3, NOTE_C4, NOTE_B3, NOTE_C4, 0
    };

    int tempo[] = {
     8, 16, 8, 16,
     8, 16, 8, 16,
     16, 16, 16, 8,
     16, 8, 3,

     12, 16, 16, 16,
     8, 16, 8, 16,
     8, 16, 8, 16,
     8, 16, 4, 12,

     12, 16, 16, 16,
     8, 16, 8, 16,
     8, 16, 8, 16,
     8, 16, 4, 12,

     12, 16, 16, 16,
     8, 16, 8, 16,
     8, 16, 8, 16,
     8, 16, 4, 16,

     12, 17, 17, 17,
     8, 12, 17, 17,
     17, 8, 16, 8,
     16, 8, 16, 8, 1
    };

    // non blocking setup
    // free play
    unsigned long previousMillis1 = 0; // time words last changed
    const long interval1 = 1500; // interval between changing

    // music
    unsigned long previousMillis2 = 0; // time last changed
    const long interval2 = 100; // interval between notes

    int displayStatus = 0; // keep track of what's displayed
    int mode = 0; // keep track of game mode -- change to 0 or 1 for different modes

    bool countdown = false;

    unsigned long previousMillis3 = 0; // time last changed
    const long interval3 = 1000; // interval between countdown
    int count = 20; // challenge mode timer

    void setup() {
     // put your setup code here, to run once:
     pinMode(9, INPUT); // setup circuit
     pinMode(10, OUTPUT); // setup buzzer 1
     pinMode(11, OUTPUT); // setup buzzer 2
     pinMode(2, INPUT); // setup button

     _display->set(5); // set brightness
     _display->point(false); // remove colon
     _display->init(); // start display
    }

    void loop(void) {
     // put your main code here, to run repeatedly:
     int conductVal = analogRead(9);

     Serial.print("Conduction sensor reads");
     Serial.println(conductVal);

     if(conductVal>410){
      //digitalWrite(10,HIGH);
      tone(11,550,400);
      tone(10,0,400);
      delay(5000);
      countdown=false;
     }
     if(mode == 0) {
       // free play
     toggleFreePlay();

     }
     else {
     // challenge mode
     if(digitalRead(2) == HIGH) {
     delay(25);
     if(digitalRead(2) == HIGH) {
     countdown = true; // stop the countdown
     }
     else {
     countdown = false; // stop the countdown
     }
     }
     if(countdown) {
     showCountdown(); // advance countdown
     }
     }
     if(digitalRead(10) == HIGH) {
     delay(25);
     if(digitalRead(10) == HIGH) {
     while(digitalRead(10) == HIGH) {
     buzz(11, NOTE_B0, 1000/24);
     }
     }
     }
     else
     sing();
    }

    void showCountdown() {
     // countdown the time remaining
     unsigned long currentMillis = millis(); // current time
     if (currentMillis - previousMillis3 >= interval3) {
     previousMillis3 = currentMillis;
     --count;
     showNumber(count);
     if(count == 0) {
     // game over
     countdown = false;
     count = 20;
     // reset countdown
     // buzz 3 times
     buzz(11, NOTE_B0, 1000/24);
     delay(100);
     buzz(11, NOTE_B0, 1000/24);
     delay(100);
     buzz(11, NOTE_B0, 1000/24);
     }
     }
    }

    void showNumber(int number) {
     // show numbers (maximum 99) on display
     _display->display(0, 25); // write - to segment 1
     _display->display(3, 25); // write - to segment 4

     // write number to middle of display

      if(number == 10)
      {
         _display->display(1,1);
       _display->display(2,0);
      }
      else if(number > 9)
      {
       _display->display(1,1);
       int newVal = number - 10;
       _display->display(2, newVal);
      }
      else
      {
         _display->display(1,0);
       _display->display(2,number);
      }
    }

    void toggleFreePlay() {
     // scroll between words without blocking
     unsigned long currentMillis = millis(); // current time
     if (currentMillis - previousMillis1 >= interval1) {
     previousMillis1 = currentMillis;
     if(displayStatus == 1)
     showPlay();
     else
     showFree();
     }
    }

    void showPlay() {
     // write "PLAY" to the display
     _display->display(0, 21); // write P to segment 1
     _display->display(1, 18); // write L to segment 2
     _display->display(2, 10); // write A to segment 3
     _display->display(3, 4); // write Y to segment 4
     displayStatus = 2;
    }

    void showFree() {
     // write "Free" to the display
     _display->display(0, 15); // write F to segment 1
     _display->display(1, 23); // write r to segment 2
     _display->display(2, 14); // write E to segment 3
     _display->display(3, 14); // write E to segment 4
     displayStatus = 1;
    }

    void buzz(int targetPin, long frequency, long length) {
     /* Buzzer example function by Rob Faludi
     http://www.faludi.com
     https://gist.github.com/AnthonyDiGirolamo/1405180
     */
     long delayValue = 1000000/frequency/2; // calculate the delay value between transitions
     //// 1 second's worth of microseconds, divided by the frequency, then split in half since
     //// there are two phases to each cycle
     long numCycles = frequency * length/ 1000; // calculate the number of cycles for proper timing
     //// multiply frequency, which is really cycles per second, by the number of seconds to
     //// get the total number of cycles to produce
     for (long i=0; i < numCycles; i++){ // for the calculated length of time...
     digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphragm
     delayMicroseconds(delayValue); // wait for the calculated delay value
     digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphragm
     delayMicroseconds(delayValue); // wait again for the calculated delay value
     }
    }

    void sing() {
     // play the song in a non blocking way
     unsigned long currentMillis = millis();

     if (currentMillis - previousMillis2 >= interval2) {
     previousMillis2 = currentMillis;
     int noteDuration = 1000 / tempo[songState];
     buzz(10, melody[songState], noteDuration);
     int pauseBetweenNotes = noteDuration;
     delay(pauseBetweenNotes);

     // stop the tone playing:
     buzz(10, 0, noteDuration);

     ++songState;
     // start song again if finished
     if(songState > 79) {
     songState = 14; // skip intro
     }
     }
    }

First I want to stop continuous buzzing during the game, and I want to make buzzer react when the handle touches the course. Plus, I also want to know how can I change the mode in arduino( and breadboard).

title: buzzwire game in arduino

Answers: 0


body:
I'm relatively new to Arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

I am using AccelStepper Library

Here is my code:
<!-- language-all: lang-cpp -->

    #include <AccelStepper.h>
    //Define stepper motor connections
    #define dirPin 4
    #define stepPin 14
    //Create stepper object
    AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
    void setup()
    {
      stepper.setMaxSpeed(1200); //maximum steps per second
    }
    void loop()
    {
      stepper.setSpeed(1200); //steps per second
      stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
    }

I have tried to add delay and counterclockwise code but its not working.

    #include <AccelStepper.h>
    //Define stepper motor connections
    #define dirPin 4
    #define stepPin 14
    //Create stepper object
    AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
    void setup()
    {
      stepper.setMaxSpeed(1200); //maximum steps per second
    }
    void loop()
    {
      Serial.println("clockwise");
      stepper.setSpeed(1200); //steps per second
      stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
      delay(1000);
      Serial.println("counterclockwise");
      stepper.setSpeed(-1200); //steps per second
      stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
      delay(1000);
    }

title: [Solved]How to make my stepper motor run clockwise and counterclockwise?

Answers: 2

body:
From the AccelStepper website: [link][1]

> Speeds of more than 1000 steps per second are unreliable

Try to change the speed to lower value, and let us know what is the outcome.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#ae79c49ad69d5ccc9da0ee691fa4ca235

body:
Hi here it the reference to the library functions that are available in [accelstepper library](https://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html).

Go through the link, it will provide you the issues with your code and example for your application like @smajli said **steps more than 1000 is unreliabe**, here you can see `setSpeed(float)` function where setting negative or positive sign selects the direction and value set the speed of rotation.


body:
I am using SIM800L and Arduino Uno.

The programme is working fine when I turn the serial monitor on using Arduino IDE but when I start the Arduino board by using the adapter it is not receiving anything. I have blinked LED on receiving SMS.

    #include <SoftwareSerial.h>

    SoftwareSerial wire(3, 2);
    String  Grsp;

    void setup()
    {
       wire.begin(9600);
       Serial.begin(9600);
       wire.println("AT+CMGF=1");
        wire.println("AT+CNMI=2,2,0,0,0");
      pinMode(8, OUTPUT);
      digitalWrite(8, HIGH);
      delay(1000);
        digitalWrite(8, LOW);

       delay(100);
    }

    void loop()
    {

      if (wire.available()>0)
      {
            Grsp = wire.readString();
         Serial.println(Grsp.length());
         Serial.println(Grsp);

         if(Grsp.length() > 100)
         {
           Serial.println("if crossed");

          digitalWrite(8, HIGH);
           delay(1000);
            digitalWrite(8, LOW);

          }

    }

    }

title: sim800l only receiving SMS after serial monitor is started otherwise not receiving

Answers: 0


body:
I'm currently working with an ESP8266 NodeMCU V3 and an IR transmitter breakout board. The module receives NEC IR commands trough a HTTP request and then sends them trough the IR transmitter. Getting the command from the HTTP request and sending static (pre-programmed) IR NEC commands works perfectly. The problem however is that the NEC IR command I receive trough HTTP is in a `String` variable/data type (after processing). `irsend.sendNEC();` however requires `uint64_t` as the input type, according to the error message I get in the Arduino IDE.

I don't really know my way around C data types to be honest. Searches like "Arduino String to uint64_t" have came up empty or reversed. One [post][1] came close to what I'm trying to accomplish, but `irsend.sendNEC(strtoul(irrequest));` didn't do the trick either.

Arduino code;

 - Check for `// Send IR NEC command` almost at the bottom
 - The second and third `irsend.sendNEC();` are an example and not in the final code
 - HTTP request is formatted like http://192.168.1.xxx/rest/ir/nec/0xFB0042BD

`Sketch.ino`

    // Configuration
    const char* CONFIG_SSID      = "mywifi";
    const char* CONFIG_PSK       = "wifipassword";
    const int   CONFIG_SERIAL    = 115200;
    const int   CONFIG_PORT      = 80;
    const int   CONFIG_TIMEOUT   = 5000;
    const int   CONFIG_IRTPIN    = 2;

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    // Include libraries
    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <IRremoteESP8266.h>
    #include <IRsend.h>
    #include <IRrecv.h>
    #include <IRutils.h>

    // Create webserver object
    WiFiServer server(CONFIG_PORT);

    // Create IR Send object
    IRsend irsend(CONFIG_IRTPIN);

    // Setup instructions
    void setup() {

      // Start serial and LED
      Serial.begin(CONFIG_SERIAL);
      Serial.println();
      Serial.println("Starting setup");
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, 1);

      // Start WiFi connection
      Serial.print("Connecting to: ");
      Serial.println(CONFIG_SSID);
      WiFi.mode(WIFI_STA);
      WiFi.begin(CONFIG_SSID, CONFIG_PSK);

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

      // Print WiFi connection information
      Serial.print("  SSID: ");
      Serial.println(WiFi.SSID());
      Serial.print("  RSSI: ");
      Serial.print(WiFi.RSSI());
      Serial.println(" dBm");
      Serial.print("  Local IP: ");
      Serial.println(WiFi.localIP());

      // Start webserver
      Serial.println("Starting webserver...");
      server.begin();
      delay(1000);
      Serial.println("Webserver started!");

      // Print webserver information
      Serial.print("  Host: ");
      Serial.println(WiFi.localIP());
      Serial.print("  Port: ");
      Serial.println(CONFIG_PORT);

      // Start IR Send
      Serial.println("Starting IR Send...");
      irsend.begin();
      delay(1000);
      Serial.println("IR Send started!");

      // Setup complete
      Serial.println("Setup completed");
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();

    }

    // Loop instructions
    void loop() {

      // Wait for new client
      WiFiClient client = server.available();
      if (client) {

        // New client
        digitalWrite(LED_BUILTIN, 1);
        Serial.println("New client connected");

        // Wait nicely for the client to complete its full request
        unsigned long timeout = millis() + CONFIG_TIMEOUT;
        Serial.println("Waiting for client request to finish...");
        while (!client.available() && millis() < timeout) {
          delay(1);
        }

        // End client connection when timeout is reached to not hold up availability
        if (millis() < timeout) {
          Serial.println("Client request finished!");
        } else {
          Serial.println("Client request timeout!");
          client.flush();
          client.stop();
          digitalWrite(LED_BUILTIN, 0);
          Serial.println();
          return;
        }

        // Catch client request
        String req = client.readStringUntil('\r');
        Serial.print("Request header: ");
        Serial.println(req);
        if (req.indexOf(F("/rest/ir/nec/")) != -1) {

          // Get IR Send NEC request
          String irrequest = req;
          irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
          irrequest.remove((irrequest.indexOf(" ")));
          Serial.print("IR Send NEC code: ");
          Serial.println(irrequest);

          // Send IR NEC command
          Serial.println("Sending IR NEC command");
          irsend.sendNEC(irrequest);    // <<< here lays the problem
          irsend.sendNEC(0xFB0042BD);   // This works
          irsend.sendNEC("0xFB0042BD"); // This doesn't

          // Send HTTP response
          Serial.println("Sending HTTP/1.1 200 OK");
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println("Connection: close");
          client.println();
          client.println("OK");

        } else {

          // Invalid request
          Serial.println("Invalid client request");
          Serial.println("Sending HTTP/1.1 404 response");
          client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nNot found");

        }

        // Flush output buffer
        Serial.println("Flushing output buffer");
        client.flush();
        digitalWrite(LED_BUILTIN, 0);
        Serial.println();
        return;

      }

    }

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

title: Change data-type String

Answers: 1

body:
`irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 10));` did the trick with the help of [Juraj][1]. Much thanks! I only had the set `10` to `16` to get it to work.

Working code:

    // Configuration
    const char* CONFIG_SSID      = "mywifi";
    const char* CONFIG_PSK       = "wifipassword";
    const int   CONFIG_SERIAL    = 115200;
    const int   CONFIG_PORT      = 80;
    const int   CONFIG_TIMEOUT   = 5000;
    const int   CONFIG_IRTPIN    = 2;

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    // Include libraries
    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <IRremoteESP8266.h>
    #include <IRsend.h>
    #include <IRrecv.h>
    #include <IRutils.h>

    // Create webserver object
    WiFiServer server(CONFIG_PORT);

    // Create IR Send object
    IRsend irsend(CONFIG_IRTPIN);

    // Setup instructions
    void setup() {

      // Start serial and LED
      Serial.begin(CONFIG_SERIAL);
      Serial.println();
      Serial.println("Starting setup");
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, 1);

      // Start WiFi connection
      Serial.print("Connecting to: ");
      Serial.println(CONFIG_SSID);
      WiFi.mode(WIFI_STA);
      WiFi.begin(CONFIG_SSID, CONFIG_PSK);

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

      // Print WiFi connection information
      Serial.print("  SSID: ");
      Serial.println(WiFi.SSID());
      Serial.print("  RSSI: ");
      Serial.print(WiFi.RSSI());
      Serial.println(" dBm");
      Serial.print("  Local IP: ");
      Serial.println(WiFi.localIP());

      // Start webserver
      Serial.println("Starting webserver...");
      server.begin();
      delay(1000);
      Serial.println("Webserver started!");

      // Print webserver information
      Serial.print("  Host: ");
      Serial.println(WiFi.localIP());
      Serial.print("  Port: ");
      Serial.println(CONFIG_PORT);

      // Start IR Send
      Serial.println("Starting IR Send...");
      irsend.begin();
      delay(1000);
      Serial.println("IR Send started!");

      // Setup complete
      Serial.println("Setup completed");
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();

    }

    // Loop instructions
    void loop() {

      // Wait for new client
      WiFiClient client = server.available();
      if (client) {

        // New client
        digitalWrite(LED_BUILTIN, 1);
        Serial.println("New client connected");

        // Wait nicely for the client to complete its full request
        unsigned long timeout = millis() + CONFIG_TIMEOUT;
        Serial.println("Waiting for client request to finish...");
        while (!client.available() && millis() < timeout) {
          delay(1);
        }

        // End client connection when timeout is reached to not hold up availability
        if (millis() < timeout) {
          Serial.println("Client request finished!");
        } else {
          Serial.println("Client request timeout!");
          client.flush();
          client.stop();
          digitalWrite(LED_BUILTIN, 0);
          Serial.println();
          return;
        }

        // Catch client request
        String req = client.readStringUntil('\r');
        Serial.print("Request header: ");
        Serial.println(req);
        if (req.indexOf(F("/rest/ir/nec/")) != -1) {

          // Get IR Send NEC request
          String irrequest = req;
          irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
          irrequest.remove((irrequest.indexOf(" ")));
          Serial.print("IR Send NEC code: ");
          Serial.println(irrequest);

          // Send IR NEC command
          Serial.println("Sending IR NEC command");
          irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 16));

          // Send HTTP response
          Serial.println("Sending HTTP/1.1 200 OK");
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println("Connection: close");
          client.println();
          client.println("OK");

        } else {

          // Invalid request
          Serial.println("Invalid client request");
          Serial.println("Sending HTTP/1.1 404 response");
          client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nNot found");

        }

        // Flush output buffer
        Serial.println("Flushing output buffer");
        client.flush();
        digitalWrite(LED_BUILTIN, 0);
        Serial.println();
        return;

      }

    }

  [1]: https://arduino.stackexchange.com/users/37622/juraj


body:
Dear Sir,
               I need to know that should led light named as L, TX, RX should be on when we connect it with laptop?
Because when I connect it with laptop led light turns on for 1 or 2 second then turns off. That's why I am asking you this question.
                 Hoping for a favourable answer.
Your's faithful,
Nir Patel.

title: Should L, TX, RX led light on while connected with laptop

Answers: 1

body:
On Arduino Uno (and most basic Arduinos), the 'L' LED is operated by whatever code is on the Arduino. RX and TX flicker whenever the Arduino is sending data to the PC (TX) or is receiving data from the PC (RX).

If you have never re-programmed your Arduino, it is running whatever code was in it when it was shipped to you. It sounds like your Arduino has a bootloader but no code yet. The bootloader listens for the PC to try upload a new program. While it is listening, it blinks the L LED.

If the PC tries to upload, you will see the RX and TX lights flicker as the two communicate, until the upload is finished. Then whatever program was uploaded will run, and *it* will control the LEDs.

If the PC doesn't try to upload a new program within a few seconds (how long depends on which bootloader version is in the Arduino), the bootloader will start whatever program is already in the Arduino. Again, that program will then control the LEDs.


body:
I'm currently working on a small project with my Arduino Yún.
I want to process the sensor data in python and send them in a message queue. I need to use Python3.

I cannot find a way to get the sensor data in my Python code.
I already tried to start the python process in my sketch and use the `println` method of the process object but this doesn't work.

I also tried to use the `BridgeClient` class from the Arduino Github but it won't work either.

Summarized:
I can't find a way to send my measurements from my Arduino sketch to the my Python3 program on the Linux side of the Arudino Yún.

I don't think this is an extraordinary problem and I don't understand why there aren't any tutorials for this specific use-case.

The section below contains my Arduino sketch, which does the measurements.

    #include <SparkFunHTU21D.h>
    #include <Wire.h>

    HTU21D myHumidity;

    int trigPin = 11;
    int echoPin = 12;

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

      myHumidity.begin();

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

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

      //Perform 5 SoilMoisture-measurements and get mean
      float soil = meanSoilMoisture(A0, 5);
      float humd = myHumidity.readHumidity();
      float temp = myHumidity.readTemperature();

      float distance = getDistance();

      String dataString;
      dataString += String(soil) + ", " + String(humd) + ", " + String(temp) + ", " + String(distance);
      Serial.println(dataString);

      delay(4000);
    }

    long getDistance() {
      digitalWrite(trigPin, LOW);
      delayMicroseconds(5);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      pinMode(echoPin, INPUT);
      long duration = pulseIn(echoPin, HIGH);

      // Convert the time into a distance
      return (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
    }

    float meanSoilMoisture(int analogPin, int nMeasurements) {
      float sum = 0;
      for(int i = 0; i < nMeasurements; i ++) {
        sum = sum + readVH400(analogPin);
        delay(50);
      }

      return sum / nMeasurements;
    }

    //Perform Measurement
    float readVH400(int analogPin) {
      int sensor1DN = analogRead(analogPin);
      float sensorVoltage = sensor1DN*(3.0 / 1023.0);
      float VWC;

      // Calculate VWC
      if(sensorVoltage <= 1.1) {
        VWC = 10*sensorVoltage-1;
      } else if(sensorVoltage > 1.1 && sensorVoltage <= 1.3) {
        VWC = 25*sensorVoltage-17.5;
      } else if(sensorVoltage > 1.3 && sensorVoltage <= 1.82) {
        VWC = 48.08*sensorVoltage-47.5;
      } else if(sensorVoltage > 1.82) {
        VWC = 26.32*sensorVoltage-7.89;
      }
      return(VWC);

    }

I'd like to have a way to send `dataString` to the linux side of the Arduino Yún and process it with Python3.

As explained earlier I've already tried out multiple solutions, e.g. start a new process and use the `println` method of the process.

    {...}
    Process proc;
    void setup() {
        {...}
        proc.begin("python3 /mnt/sda1/test.py");
        p.runAsynchronously();
        {...}
    }
    {...}
        proc.println(dataString);
    {...}

I've tried to read this `dataString` in Python3 in different ways, e.g. I've used the `input` method, because I read in a forum that I can handle such input like a keyboard input.
It didn't work and I didn't get an error, neither in Python nor in my sketch.

I've read different examples using the `Bridge` library. So I set up the sketch:

    {...}
    bridge.put("data", dataString);
    {...}

I'd like to try out the `BridgeClient`on the python side but this library was written in Python2. I don't want to migrate the library to Python3 and I need to use Python3, so I didn't find a way to write Python code here.

I would highly appreciate any help from you.

title: Process Sensor Data from Arduino Yun with Python

Answers: 1

body:
You might want to try the Process method, although, looking at your recent edits to the question, it seems like you already have.

Nevertheless, I was having difficulty getting my head around the problem when I first used my Yún, and I found the information below helped me understand how to get up and running. You do say that you've tried many solutions already, and maybe you've already seen this, but as you don't list which solutions you have already tried (apart from one), I thought it might be worth posting this link as an answer.

From [this post][1] to the thread on the Arduino forums, [Yun Serial connection between Arduino and Linux][2]

> Accepting HTTP connections, as shown in the [Bridge tutorial][3], is
> but one facet of the Bridge library. (And probably the least useful
> and least efficient facet.) It is intended for accepting incoming
> connections from the greater network, not necessarily the local Linux
> processor.
>
> The Bridge library is a collection of different classes that perform a
> variety of operations, all over the serial link between the two
> processors, and all can be used at the same time. The Bridge uses a
> network port paradigm, not HTTP. Using ports gives it a little more
> overhead, but it allows multiple simultaneous "connections" between
> the sketch and Linux sides.
>
> I suggest you take a look at the [Process tutorial][4]. It does what
> you want, and 95% of the time it is the only part of the Bridge
> library that I use. The example defines Process objects that are local
> to a function, which run simple commands that do a little bit
> different f processing, return a result, and then exit.
>
> My projects typically define a global Process object which starts a
> Python script, and keeps the connection open. Once open, the sketch
> can write to the Process object at any time, and the Python script
> reads that data from STDIN. Python can write to STDOUT at any time,
> and the sketch can read it from the Process object. The Process class
> derives from the Stream class, just like Serial, so your sketch can
> use any of the read/write methods you would use for a serial port. On
> the Linux side, you are just reading/writing as you would to the
> console. By default, Pythons runs in a buffered mode: I've found that
> you need to add the -u option to the command line that runs your
> Python script, or add it to the hashbang at the beginning of your
> script.
>
> There are those who disable the Bridge library, and use the serial
> port manually on both sides. This can be done, but I've not had to
> resort to that yet. The Process class does everything that a direct
> serial connection can do, and more: you can have multiple simultaneous
> Process connections going, and you can still use all of the other
> Bridge library features. If you disable the Bridge library, you get
> just the one connection stream. It would be a bit more efficient, but
> unless you are dealing with high amounts of data, I'll bet you don't
> need to do that.
>
> My typical project has the sketch running as a rather dumb I/O
> processor, passing barely digested input data down though one or more
> Process objects to a Python script. The Linux side does all of the
> heavy processing and network communications, and then sends output
> data back up the sketch which outputs it to the pins.

  [1]: https://forum.arduino.cc/index.php?topic=500431.msg3414206#msg3414206
  [2]: https://forum.arduino.cc/index.php?topic=500431.0
  [3]: https://www.arduino.cc/en/Tutorial/Bridge
  [4]: https://www.arduino.cc/en/Tutorial/Process


body:
I'm currently trying to isolate what's the problem with a current sensor build I'm working on right now. I'm using a ACS712 that can handle 30A, I've used the code at

http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-arduino-ac-current-tutorial/

And so far for certain devices like pencil sharpeners, computers, chargers, and other household devices the amperage readout seems is "correct" there's some minor error due to the noise I assume.. There's like .10 amperage difference. But when I plug in a stereo amplifier the error sky rockets to 1 Amp to even 2 Amps and I'm not quite sure what's the problem, I've also tried multiple codes online and all of them reach the same conclusion.

Thanks,

title: ACS712 Module inaccurate reading in some devices

Answers: 0


body:
I am trying to read the data from GY-86 with my arduino UNO.
While reading MPU6050 and MS5611, it works quite well. But somehow I can't read anything from HMC5883L. Here is the code I used:
```
#include <Wire.h>
#include <HMC5883L.h>

HMC5883L compass;

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

  // Initialize HMC5883L
  Serial.println("Initialize HMC5883L");
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }

  // Set measurement range
  // +/- 0.88 Ga: HMC5883L_RANGE_0_88GA
  // +/- 1.30 Ga: HMC5883L_RANGE_1_3GA (default)
  // +/- 1.90 Ga: HMC5883L_RANGE_1_9GA
  // +/- 2.50 Ga: HMC5883L_RANGE_2_5GA
  // +/- 4.00 Ga: HMC5883L_RANGE_4GA
  // +/- 4.70 Ga: HMC5883L_RANGE_4_7GA
  // +/- 5.60 Ga: HMC5883L_RANGE_5_6GA
  // +/- 8.10 Ga: HMC5883L_RANGE_8_1GA
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  // Idle mode:              HMC5883L_IDLE
  // Single-Measurement:     HMC5883L_SINGLE
  // Continuous-Measurement: HMC5883L_CONTINOUS (default)
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  //  0.75Hz: HMC5883L_DATARATE_0_75HZ
  //  1.50Hz: HMC5883L_DATARATE_1_5HZ
  //  3.00Hz: HMC5883L_DATARATE_3HZ
  //  7.50Hz: HMC5883L_DATARATE_7_50HZ
  // 15.00Hz: HMC5883L_DATARATE_15HZ (default)
  // 30.00Hz: HMC5883L_DATARATE_30HZ
  // 75.00Hz: HMC5883L_DATARATE_75HZ
  compass.setDataRate(HMC5883L_DATARATE_15HZ);

  // Set number of samples averaged
  // 1 sample:  HMC5883L_SAMPLES_1 (default)
  // 2 samples: HMC5883L_SAMPLES_2
  // 4 samples: HMC5883L_SAMPLES_4
  // 8 samples: HMC5883L_SAMPLES_8
  compass.setSamples(HMC5883L_SAMPLES_1);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.print("Selected range: ");

  switch (compass.getRange())
  {
    case HMC5883L_RANGE_0_88GA: Serial.println("0.88 Ga"); break;
    case HMC5883L_RANGE_1_3GA:  Serial.println("1.3 Ga"); break;
    case HMC5883L_RANGE_1_9GA:  Serial.println("1.9 Ga"); break;
    case HMC5883L_RANGE_2_5GA:  Serial.println("2.5 Ga"); break;
    case HMC5883L_RANGE_4GA:    Serial.println("4 Ga"); break;
    case HMC5883L_RANGE_4_7GA:  Serial.println("4.7 Ga"); break;
    case HMC5883L_RANGE_5_6GA:  Serial.println("5.6 Ga"); break;
    case HMC5883L_RANGE_8_1GA:  Serial.println("8.1 Ga"); break;
    default: Serial.println("Bad range!");
  }

  Serial.print("Selected Measurement Mode: ");
  switch (compass.getMeasurementMode())
  {
    case HMC5883L_IDLE: Serial.println("Idle mode"); break;
    case HMC5883L_SINGLE:  Serial.println("Single-Measurement"); break;
    case HMC5883L_CONTINOUS:  Serial.println("Continuous-Measurement"); break;
    default: Serial.println("Bad mode!");
  }

  Serial.print("Selected Data Rate: ");
  switch (compass.getDataRate())
  {
    case HMC5883L_DATARATE_0_75_HZ: Serial.println("0.75 Hz"); break;
    case HMC5883L_DATARATE_1_5HZ:  Serial.println("1.5 Hz"); break;
    case HMC5883L_DATARATE_3HZ:  Serial.println("3 Hz"); break;
    case HMC5883L_DATARATE_7_5HZ: Serial.println("7.5 Hz"); break;
    case HMC5883L_DATARATE_15HZ:  Serial.println("15 Hz"); break;
    case HMC5883L_DATARATE_30HZ: Serial.println("30 Hz"); break;
    case HMC5883L_DATARATE_75HZ:  Serial.println("75 Hz"); break;
    default: Serial.println("Bad data rate!");
  }

  Serial.print("Selected number of samples: ");
  switch (compass.getSamples())
  {
    case HMC5883L_SAMPLES_1: Serial.println("1"); break;
    case HMC5883L_SAMPLES_2: Serial.println("2"); break;
    case HMC5883L_SAMPLES_4: Serial.println("4"); break;
    case HMC5883L_SAMPLES_8: Serial.println("8"); break;
    default: Serial.println("Bad number of samples!");
  }

}

void loop()
{
  Vector raw = compass.readRaw();
  Vector norm = compass.readNormalize();

  Serial.print(" Xraw = ");
  Serial.print(raw.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(raw.YAxis);
  Serial.print(" Zraw = ");
  Serial.print(raw.ZAxis);
  Serial.print(" Xnorm = ");
  Serial.print(norm.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(norm.YAxis);
  Serial.print(" ZNorm = ");
  Serial.print(norm.ZAxis);
  Serial.println();

  delay(100);
}
```
I download it from https://github.com/jarzebski/Arduino-HMC5883L.

The program always stuck at
```
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }
```
Here is the begin function in HMC5883L.cpp
```
bool HMC5883L::begin()
{
    Wire.begin();

    if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
    || (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
    || (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
    {
 return false;
    }

    setRange(HMC5883L_RANGE_1_3GA);
    setMeasurementMode(HMC5883L_CONTINOUS);
    setDataRate(HMC5883L_DATARATE_15HZ);
    setSamples(HMC5883L_SAMPLES_1);

    mgPerDigit = 0.92f;

    return true;
}
```
So, it seems that the begin function always returns False. What should i do to solve this problem?

This is how I connect GY-86 to UNO:

VCC-IN  -> 5V

GND     -> GND

SDA     -> 4A

SLC     -> 5A

title: Problem with reading data from HMC5883L in GY-86

Answers: 2

body:
Did you run a i2c scanner? Is it found with i2c address 0x1E?

Looking at the schematic, the magnetometer HMC5883L is connected to XDA and XCL. That is not the normal I2C bus, but a second I2C bus from the MPU-6050.

The reason for that is that the 'dmp' firmware in the MPU-6050 can read the magnetometer and do calculations with it, in the MPU-6050.

If you want to communicate with the magnetormeter via the normal I2C bus, then you have to turn on the bypass-mode.

The libraries from Jeff Rowberg and Jarzębski are large. I suggest to enable the bypass-mode and run a i2c scanner.

Do you have a logic analyzer?
Perhaps you can use a simple multimeter. Keep the SDA low (shortcut it to GND) and try to measure if XDA is low as well in the bypass mode.

There is a chance that something is broken.

body:
Thank to Jot, your answer actually helps me.
Now I am using this code and it is working very well.

```
#include <Wire.h>
#include <HMC5883L.h>
#include <MPU6050.h>

HMC5883L compass;
MPU6050 mpu;

int previousDegree;

void setup()
{
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif
  Serial.begin(38400);

  // Initialize MPU6050
  mpu.initialize();

  // Enable bypass mode
  mpu.setI2CMasterModeEnabled(false);
  mpu.setI2CBypassEnabled(true);
  mpu.setSleepEnabled(false);

  // Initialize HMC5883L
  while (!compass.begin())
  {
    delay(500);
  }

  // Set measurement range
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  compass.setDataRate(HMC5883L_DATARATE_30HZ);

  // Set number of samples averaged
  compass.setSamples(HMC5883L_SAMPLES_8);

  // Set calibration offset. See HMC5883L_calibration.ino
  compass.setOffset(0, 0);
}

void loop()
{
  long x = micros();
  Vector norm = compass.readNormalize();

  // Calculate heading
  float heading = atan2(norm.YAxis, norm.XAxis);

  // Set declination angle on your location and fix heading
  // You can find your declination on: http://magnetic-declination.com/
  // (+) Positive or (-) for negative
  // For Bytom / Poland declination angle is 4'26E (positive)
  // Formula: (deg + (min / 60.0)) / (180 / M_PI);
  float declinationAngle = (4.0 + (26.0 / 60.0)) / (180 / M_PI);
  heading += declinationAngle;

  // Correct for heading < 0deg and heading > 360deg
  if (heading < 0)
  {
    heading += 2 * PI;
  }

  if (heading > 2 * PI)
  {
    heading -= 2 * PI;
  }

  // Convert to degrees
  float headingDegrees = heading * 180/M_PI;

  // Fix HMC5883L issue with angles
  float fixedHeadingDegrees;

  if (headingDegrees >= 1 && headingDegrees < 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 0, 239, 0, 179);
  } else
  if (headingDegrees >= 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 240, 360, 180, 360);
  }

  // Smooth angles rotation for +/- 3deg
  int smoothHeadingDegrees = round(fixedHeadingDegrees);

  if (smoothHeadingDegrees < (previousDegree + 3) && smoothHeadingDegrees > (previousDegree - 3))
  {
    smoothHeadingDegrees = previousDegree;
  }

  previousDegree = smoothHeadingDegrees;

  // Output
  Serial.print(norm.XAxis);
  Serial.print(":");
  Serial.print(norm.YAxis);
  Serial.print(":");
  Serial.print(norm.ZAxis);
  Serial.print(":");
  Serial.print(headingDegrees);
  Serial.print(":");
  Serial.print(fixedHeadingDegrees);
  Serial.print(":");
  Serial.print(smoothHeadingDegrees);
  Serial.println();

  // One loop: ~5ms @ 115200 serial.
  // We need delay ~28ms for allow data rate 30Hz (~33ms)
  delay(30);
}
```

By the way, the code on https://github.com/jarzebski/Arduino-HMC5883L should add
```
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif
```
in the begin of setup.


body:
hey guys so i get this error when plugging in my arduino and not sure why:

> Blockquote
>
> Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"
>
> Sketch uses 930 bytes (2%) of program storage space. Maximum is 32256
> bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving
> 2039 bytes for local variables. Maximum is 2048 bytes.
> **avrdude: ser_open(): can't open device "\\.\COM5": The system cannot find the file specified.**
>
>
> Problem uploading to board.  See
> http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
>
> This report would have more information with "Show verbose output
> during compilation" option enabled in File -> Preferences.

How can i solve it? It used to work and not sure what's happened... also does anyone know if the Braccio robotic arm can be connected to arduino via just the arduino/usb cable alone? Because when i connect the braccio shield v4 to both th arduino(and to laptop) and to the wall, it actually causes my laptop to switch off ??

title: Arduino Uno COM issue + Braccio qu

Answers: 0


body:
I just made a very basic circuit with a LED and a resistor. I also wrote a program that's supposed to take an input for how long to keep the LED on for. It works fine for shorter times like 10 seconds but as soon as I try to input a time like 120 seconds the LED never turns off.
My code's below. What could be wrong?

    int light=9;

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

    void loop() {
      Serial.println("How long do you want the light on for (in seconds)?");
      while(Serial.available()==0){}
      int on_time = (Serial.parseInt() * 1000);
      digitalWrite(light, HIGH);
      delay(on_time);
      digitalWrite(light, LOW);
      Serial.print("The light was just on for ");
      Serial.print(on_time/1000);
      Serial.print(" seconds. ");
    }

title: Serial input values only working for very short seconds

Answers: 1

body:
If you add `Serial.println(on_time);` right after `int on_time = (Serial.parseInt() * 1000);` you will see the problem. Once you enter the number 33 for example, the `integer` value printed is **-32536**. The Allowed data type for `delay()` is `unsigned long`, so the negative number is causing a problem.

Using `Serial.println()` judiciously can be very helpful when you are trying to debug a sketch.


body:
The Arduino NTP implementation is rather naive in some respects. It basically just grabs the time in seconds from the raw packet, and then converts it to Unix time via subtraction. How would it be possible to create an implementation that is safe from at least this next NTP rollover (due in 2036)? I'd rather not design something that might suddenly fail in strange ways in a decade or two when I have forgotten why it might do so (but it's not horribly important if it's not easily fixed).

If it can make it to 2100, I'd have larger problems (the RTC would crap itself), so just this rollover is fine.

The existing implementation (https://github.com/arduino-libraries/NTPClient/blob/master/NTPClient.cpp):
<!-- language-all: lang-cpp -->

    unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
    unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;

    this->_currentEpoc = secsSince1900 - SEVENZYYEARS;

title: NTP rollover-safe design with ESP8266 (Curiosity)

Answers: 1

body:
This implementation is perfectly fine. The calculations are done with
unsigned numbers, so they are naturally rollover safe. The day NTP time
rolls over, `secsSince1900` will become a very small number, and
subtracting `SEVENZYYEARS` from it will cause an extra roll over. Owing
to the rules of modular arithmetics, these two rollovers compensate and
you are guaranteed to get the correct result modulo
232 s.

In the end, you get a Unix time as an unsigned 32-bit integer. Unix time
is traditionally signed, which makes the 32-bit representation roll over
in January 2038. The authors of this library have instead chosen to
represent it as an _unsigned_ number, which means it will roll over in
February 2106.


body:
I have hard time to understand what this doc tells me: https://www.microchip.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_use_bv.html

I has a macro called `_BV` that

>  convert a bit number (usually within a byte register) into a byte value

And the example tells this

>_BV(3) => 1 << 3 => 0x08

I am kinda used to bits and bytes etc. But I don't understand what the **3** in this example is? It says it converts a bit number but **3** is not binary it is an integer. And the macro resolves it to **0x08** which is the value of 8 in decimal.

I am very confused. I hope someone can explain to me what is happening here!

title: Bit Number to Byte Value conversion (AVR Docs)

Answers: 1

body:
The bits within a byte are numbered 0 through 7 from right to left. The
rightmost (least significant) is bit 0, next is bit 1... and the
leftmost (most significant) is bit 7.

The expression `_BV(3)` builds a byte where bit 3 is set (is 1) and all
other bits are clear (are 0). In binary it looks like this:

    position:   7  6  5  4  3  2  1  0
    bit value:  0  0  0  0  1  0  0  0

The macro expands to `1<<3`, which takes the integer 1 (0b00000001 in
binary) and shifts all its bits by three positions to the left. The
result can be written 0b00001000 in binary, 0x08 in hexadecimal, and 8
in decimal.


body:
Running Arduine IDE `SD DataLogger Example`, my data gets appended to a txt file.

    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
    }

Is there an explicit option to open the file in overwrite / append modes?

title: Arduino SD Card open file modes append / overwrite

Answers: 3

body:
If you look in [this library][1], you see:

    File SDClass::open(const char *filepath, uint8_t mode) {

        ...

        if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) {

So you can use all these mode combinations (e.g. O_CREATE, O_APPEND, O_WRITE).

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

body:
The Arduino SD library is an Arduino wrapper of old version of SdFat library (put into utility subfolder of the SD library). This SdFat library [has constants][1] like O_READ, O_WRITE, O_APPEND.

Arduino wrapper has constants

    #define FILE_READ O_READ
    #define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

You can use the SdFa library constants in the wrapper calls.

    File dataFile = SD.open("datalog.txt", O_READ | O_WRITE | O_CREAT);

**Warning**: not all versions of SD library bundled in different board packages have O_APPEND in `#define FILE_WRITE`. Even in the Arduino SD library the O_APPEND was removed some time ago and then the change was reverted, because all dataloger examples used FILE_WRITE.

  [1]: https://github.com/arduino-libraries/SD/blob/b8a78d4b3bf970c776522b79f95c7cc4691ced3c/src/utility/SdFat.h#L52

body:
You only need to open the file with `FILE_WRITE` and use `file.seek(EOF)` to go to de end of the file. After that you can write whatever you want that will be appended to the end of the file.

```
File outputFile = SD.open(LOG_FILE, FILE_WRITE);
outputFile.seek(EOF);
outputFile.println("Appended to the EOF");
```


body:
I'm trying to make an LED go from no brightness to max and back down on a loop and I've encountered a problem I can't seem to crack. The LED will go to maximum brightness steadily as it should but then it will drop to zero brightness and start again... Why?

    int blue_led=10;

    void setup() {
      pinMode(blue_led,OUTPUT);
    }

    void loop() {

      int voltage=0;

      for(int i=0;i<=255;i+1){

        analogWrite(blue_led,voltage);
        voltage=voltage+1;
        delay(8);
      }
       int volts=255;

       for(int i=0;i<=255;i+1){

        analogWrite(blue_led,volts);
        volts=volts-1;
        delay(8);
       }

    }

title: LED dimmer not fading out

Answers: 1

body: your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)


body:
I've recently been trying to make program using IRremote(library) in my Arduino IDE(v1.8.9), but whenever I hit the upload button this error message is returned

> Sketch uses 7514 bytes (23%) of program storage space. Maximum is
> 32256 bytes. Global variables use 415 bytes (20%) of dynamic memory,
> leaving 1633 bytes for local variables. Maximum is 2048 bytes.
>
> avrdude: verification error, first mismatch at byte 0x0002
>
>    0x5d != 0x62 avrdude: verification error; content mismatch
>
> avrdude: verification error; content mismatch

I'm using **Arduino UNO R3**

This is the code I'm trying to run

        #include <IRremote.h>
    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop()
    {
      if (irrecv.decode(&results))
        {
         Serial.println(results.value, HEX);
         irrecv.resume(); // Receive the next value
        }
    }

Also, every other code(not using the IRremote library) uploads just fine without any errors.

title: Arduino IDE upload error

Answers: 1

body:
There can be power/connection problem or somehow the bootloader has been damaged.
So

 - Check power
 - Check Connection
<br>

If there no problem found, then by using usbasp, avrisp, usbtinyisp, etc reflash the bootloader. I hope your problem will be solved.


body:
I connected my gps module (NEO-6M) with esp32doit-devkit-v1 board. The module provided data but many data are missing.

### My pin configuration:
GPS ------- ESP32

VCC ------- 3v3

GND ------- GND

TX -------- RX2 (pin 16)

RX -------- TX2 (pin 17)

### Baud Rate: 9600

My code:
```c++
#include <Arduino.h>
#include <TinyGPS++.h>

#define TXD2 17
#define RXD2 16

TinyGPSPlus gps;

void setup()
{
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.println("Started......");
}

void loop()
{
  while (Serial2.available())
  {
    Serial.write(Serial2.read());
    // gps.encode(Serial2.read());
    // if (gps.location.isValid())
    // {
    //   Serial.print("Latitude= ");
    //   Serial.print(gps.location.lat(), 6);
    //   Serial.print(" Longitude= ");
    //   Serial.println(gps.location.lng(), 6);
    // }
  }
}
```
### OUTPUT
[![my output][1]][1]

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

title: GPS Module don't provide full data

Answers: 1

body:
GPS seems to be working and informing you that you have no signal.  Usually happens inside buildings, when far from a window or when antenna isnt properly connected.

Testing out of doors is many times not possible, so try placing your antenna next to a window with a partial view of the sky.  Wait for a couple of minutes until you get a fix on 4 or 5 satellites.


body:
I'm using Arduino Uno controller

How it is possible to know if controller connected to PC via USB, to detect if wire is plugged and get condition for variable in sketch.

I've tried `Serial.available()`, but I'm not sure, if I can do it this way:

    if (Serial.available())
    {
       val = true;
    }
    else
    {
       val = false;
    }

I want use this condition to avoid `setup()` commands by some unexpected reason in case if controller powered only with adapter

title: Check if Arduino Uno connected with PC

Answers: 1

body:
You can't determine if there is a valid USB source on the UNO without modifications, because the Atmega328P just receives serial data when the host sends some data. Some approaches that you can keep in mind.

 1. If you want to determine whether you are connected through the USB or barrel connector, you can connect an analog pin to the Vin pin through a voltage divider (you should calculate the values so that you do not exceed 5V on the analog pin). This way if you detect a voltage greater than 6.6V you will know that you are being powered from the barrel jack.

 2. If you want to detect a particular PC, you can write a SW in the PC which scans for new ports, then opens them and sends a particular string. If you receive that within X seconds, you know that you are connected to the PC

 3. If you want to determine if you are connected to any valid PC, then I think you will need to modify the program in the Atmega16u2 which is used as a serial bridge between the two. I'm not sure whether it is possible or not, but I think that the Atmega16u2 knows when a valid USB session is started, and so can tell the Atmega328 this information (through the serial interface)


body:
I've been using **Python** for quite long, and I was wondering if it can be used as a programming language for **Arduino**, rather than **C/C++**.

When I'm using the Arduino IDE, the sketch is compiled into a **hex** file that contains the program **binary**.

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

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

Knowing that micro controllers execute only binary, I would like to know if there is a tool to **convert** Python code into binary, so that I can **upload** it directly to Arduino using AVR or other programmers.

  [1]: https://i.stack.imgur.com/8RDCw.png
  [2]: https://i.stack.imgur.com/C5QiE.png

I read about **Micro Python**, a lightweight adaptation of Python that can fit in boards, but can only work with **PyBoard**, which I have never used yet.

I believe that Arduino manufacturers should start developing boards that can run Python, because it's very simple to use, unlike C/C++. It also has a lot of builtin modules that can make development very easy, which will achieve a remarkable progress in **IOT**.

title: Running Python on Arduino

Answers: 1

body:
To my knowledge, there is not a "python to ATMega architecture" compiler out there.

However, it's not true that MicroPython only runs on PyBoard. There are versions for installation also on the ESP8266 and ESP32 chips, and so the popular NodeMCU and Wemos D1 development boards, or any of the other similar products with those processors, can easily run Python code. Many of these are available at a very low cost from the usual retailers/sources.

Be aware that MicroPython is somewhat limited compared to the full version due to the limited RAM available on these boards.


body:
What is the minimum `debug level` (`TOOLS` tab) which will display the stack trace on crash?

I would like to reduce information clutter in the serial monitor.

I understand that `debug port` must point to my serial monitor.

In case it makes a difference, it is a NodeMCU, running C++, in Arduino IDE on a Ubuntu 16.04 machine.

title: ARDUINO IDE debug level for stack trace only (nodeMCU 1.0)

Answers: 1

body:
The crash report is printed to 'standard output' by `__wrap_system_restart_local` in `core_esp8266_postmortem.c` in esp8266 Arduino core.

The standard output is considered as debug output in esp8266 Arduino core. Debug output to hardware Serial can be enabled in runtime by `Serial.setDebugOutput(true);`.

At compile time the initial debug output is controled by `-DDEBUG_ESP_PORT=`, for example `-DDEBUG_ESP_PORT=Serial1`. The Tools menu "Debug port" sets the `DEBUG_ESP_PORT` define. The crash report is not controlled by "Debug level" setting.


body:
I'm trying to programme a servo motor to reach certain positions. I have a 360 degrees servo motor, so I can not use the Servo library and I can only control the speed. Therefore I want to regulate the time for the pulse. The setup is simple, 5 V, GND and pin 9 from the Arduino to the motor.

    int servo1 = 9;

    void setup{
        Serial.begin(9600);
        pinMode(servo1, OUTPUT);
    }
    void loop{
        digitalWrite(servo1, HIGH);
        delay(5000);
        Serial.println(digitalRead(servo1));
        digitalWrite(servo1, LOW);
        delay(5000);
        Serial.println(digitalRead(servo1));
    }
Expected:
I expect the code to run the servo motor at full speed for 5 seconds.

Actual:
The motor runs at the first impulse and pauses for 10 seconds.

How can I improve the code to do what I expect?

title: Servo motor (HSR-1425R) not running continuously

Answers: 2

body:
Look at how servo motors are typically controlled. As far as I know there are no servos that can just be "enabled to rotate" like you seem to expect.
Usually a servo's position is set by applying a pulse of a specific length. This means you can apply a PWM signal with proper frequency. Then the duty cycle should be proportional to the servos position. From my experience timing is quite critical when controlling a servo, so going the way you do (timing a gpio's output state with `delay()`s) will not work well. You have to use the atmega's hardware modules (which already is the case when using the arduinos digital write) to achieve adequate timing.

body: Apply some impulse which you need your servo to work on


body:
I have a char array of length 10.  It gets filled with an unpredictable number of chars, usually up to 6.

    char charDummy[10] = "";

When i concatenate the char array with another, I get spaces, which are unwanted in later parsing.

    char postStr[300] = "";
    strcat(postStr, "&field1=");
    strcat(postStr,dtostrf(rain05m,6,2,charDummy));

How do I trim a char array directly?

Workaround: loop thru the array and copy valid characters to a new char array with perfect number of rows.  Due to memory constraints, I need to be parcimonious with the amount of variables created.

title: C++ trim char array

Answers: 1

body:
Your problem is that `dtostrf()` right-aligns the value in the space allotted to it.  The simple answer is to tell it to left-align instead:

> Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the possible '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. **width is signed value, negative for left adjustment.**
>
> [AVR LIBC Manual](https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html)

So, just make your width negative and it will left align.


body:
I am an arduino beginner and I am trying to make a speed camera alert system, it would start beeping if I am above the speed limit and getting close to the speed camera. There is this website where I can get all the data I need, coordinates, direction and speed limit of every 36000 speed cams in my country.

I would need some extra memory space to be able to store all this data, would an eeprom chip do the job? and would it be able to keep up with a for loop going through all those 36000 speed cam locations to check if i am close to it and above the speed limit?

Edit: since going through all those locations on a loop would be a lot for the processor to handle, someone recommended the creation of a temp file that would narrow that list down by direction, and when that direction changed it would recalculate that temp file. This is what I came up with:

```c++
void setup() {
  int tempDirection = gpsDirection;
  writeTempFile();
}

void loop() {
  //this will recalculate the temp file when the gpsDirection changes
  if(gpsDirection > tempDirection +5 || gpsDirection < tempDirection -5){
    tempDirection = gpsDirection;
    writeTempFile();
  }

  for(temp file){
    if(distance <= 100 && speed > speedlimit){
      //start beeping
    }
  }
}

void writeTempFile(){
  //this will write a temp file with every cam with a direction that's similar the gps direction
  for(each line of the file){
    if(gpsDirection + 10 > camDirection || gpsDirection - 10 < camDirection ){
      add cam to temp file;
    }
  }
}

```

title: Best way of storing extra data for Arduino project

Answers: 1

body:
EEPROM writes are limited to about 100k cycles.  They are for permanent or semi-permanent data (like your absolute speed threshhold - 120kmh, for example).

You should not store your speed camera base here.

Get a MicroSD adapter and save your data there.  Looping thru 36000 speed trap locations is going to put a toll on your processor and memory.  I recommend that you determine a binding box (+/- 2 degrees, for example) and save a temp file with only those traps inside the box.  recheck every time your position changes a full degree (N/S or E/W).

Notice: in some countries, Brazil for example, distributing information regarding speed trap locations is illegal (obstruction of justice).


body:
I wanted to get some help about my ATMega328P on my breadboard. I programmed a simple clock like this -

    #include <LiquidCrystal.h>
    #include <dht.h>
    #include <DS3231.h>

    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    dht DHT;
    DS3231  rtc(SDA, SCL);

    void setup() {
      rtc.begin();
      lcd.begin(16,2);

    }

    void loop() {

      int chk = DHT.read11(9);
      delay(1000);
      lcd.print("Temp: ");
      lcd.print(DHT.temperature);
      lcd.print(" ");
      lcd.print((char)223);
      lcd.print("C");
      lcd.setCursor(0,1);
      lcd.print("Humi: ");
      lcd.print(DHT.humidity);
      lcd.print(" %");
      lcd.setCursor(0,0);

      delay(5000);

      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Time:  ");
      lcd.print(rtc.getTimeStr());
      lcd.setCursor(0,1);
      lcd.print("Date: ");
      lcd.print(rtc.getDateStr());
      delay(5000);

      lcd.clear();
     }
The code works when ATMega328P is connected on the Arduino Board itself, everything is showing correctly. But when I remove the chip (when it's already programmed) and place it on the breadboard, do all the necessary wirings, it only outputs me the words Humi and Temp without even showing the proper values (-999.0 degrees it shows me). I triple-checked my connections and found nothing. And after those 5 seconds of waiting, I finally got Time, and nothing is there, only the text, not even those weird numbers. And it doesn't even reload back to Temp and Humi, it just stays on Time word forever.

I have feeling that loop doesn't work properly somehow.

EDIT: I found out what was the problem about reseting, BUT STILL the proper values doesn't show up

Can you help me out, please?

title: ATMega328P chip on breadboard does not work properly

Answers: 0


body:
I am using `Accelstepper` library to control a unipolar stepper motor. In my project, I would like to run the stepper in full-step mode when I need speed and in half-step mode when I need precision. As you know, the full-step/half-step selection is done in the very beginning of the sketch...

I found a workaround by creating two instances of `Accelstepper` for the same stepper. That is:

    Accelstepper fast(FULL4WIRE, 2,3,4,5);

    Accelstepper slow(HALF4WIRE, 2,3,4,5);

With this, when I call (skipping other details of the code) `fast.run()` the motor moves fast (full-step) and when I call `slow.run()` it moves slowly as it is in half step mode.

But;

When it comes to determine to current motor position, this workaround fails, since there are two different values returned by the two functions: `fast.currentPosition()` and `slow.currentPosition()`. So this workaroud becomes useless.

My first question is: is there a way in `Accelstepper` to switch from full-step to half-step and vice versa in the execution(let say in the loop)? If so, the second question can be skipped.

The second: `XX.currentPosition()` function returns the value of a variable, namely "_currentPos" which is calculated in `Accelstepper.cpp` file. As I understand, there become, as many `_currentPos` values as `Accelstepper` instances. In my case, one for fast and another for slow, and somehow they are kept and calculated individually without any confusion. Is there a way to access (extern?) and set this variable from the sketch, by referencing the specific `Accelstepper` instence? Briefly, is there a way to copy one motor position to another?

Many thanks.

title: Accelstepper - how to switch from fullstep to halfstep in loop?

Answers: 1

body:
[The documentation][1] notes a `setCurrentPosition()` function.

>     void AccelStepper::setCurrentPosition ( long position )
> Resets the current position of the motor, so that wherever the motor happens
> to be right now is considered to be the new 0 position. Useful for
> setting a zero position on a stepper after an initial hardware
> positioning move. Has the side effect of setting the current motor
> speed to 0.
>
> Parameters
>
> **position** The position in steps of wherever the motor happens to be right now.

----------

Use the `currentPosition()` function to get the current position from either mode. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#a9d917f014317fb9d3b5dc14e66f6c689


body:
I have written my own 'assert' since I want to use it for both Windows and Arduino. The class is called from many files (about 10).

AssertUtils.h:

    #pragma once

    #define assert(expr) AssertUtils::Assert2((expr), (__func__), (__FILE__), (__LINE__));

    class AssertUtils
    {
    public:
     static void Assert2(bool expression, const char* funcName, const char* fileName, int line);
    };

AssertUtils.cpp:

    #include "AssertUtils.h"
    #include "Arduino.h"

    /* static */ void AssertUtils::Assert2(bool expression, const char* funcName, const char* fileName, int line)
    {
     if (!expression)
     {
      Serial.println(funcName);
      Serial.println(fileName);
      Serial.println(line, DEC);
      Serial.flush();

      // Abort program execution.
      abort();
     }
    }

When I compile this, the SRAM usage is 1469 bytes (together with the rest of my sketch and classes).

When I comment the line below, I get a segmentation fault in a random assert call (when I comment out that call, I get it in the next, etc.).

  //Serial.println(funcName);

When I also comment out the second print statement, the compiler reports only 1137 bytes SRAM usage (which I expect since this was about equal until before I added the Assert class).

  //Serial.println(funcName);
     //Serial.println(fileName);

Questions:

1. How can I get rid of the segmentation fault?
2. How can it be that about 332 bytes are used for one two additional print statements? (maybe related to the const char* buffering (?)

title: Segmentation fault and huge SRAM need for Serial.println

Answers: 1

body:
Note, this answer is not MY answer, but approximately the combination of the first 5 comments from my original question.

What I did was:

- (Juraj) Changed the compiler version to 6.21
- (juraj) Added an F in `F(__FILE__)`
- (KIIV) Removed __func__; this did not work with the `F` flash helper, but I can find back the code anyway unambiguously because of the file name + line number.
- (Majenko) I removed the class and use a macro. This costs some more Flash memory (depending on the number of asserts I use, but I'm still around 40% (was 35%).

The SRAM usage is now 1125 bytes, even less than where I'm started with.

The resulting code is below:

    #define assert(expression) \
      if (!(expression)) \
      { \
        Serial.println(F(__FILE__)); \
        Serial.println(__LINE__, DEC); \
        Serial.flush(); \
       abort(); \
      }


body:
I am new to arduino and i am making a smart energy meter for my home. I want to run the arduino months so, how to power arduino with a adapter, I have a 12V 1.2A adapter is it ok to power arduino with it or not?.
Thanks in advance.
As i said i want to run it long time.

title: Can I power Arduino with 12V 1.2A adapter

Answers: 2

body:
If it is an Arduino Uno Rev3 SMD, the [documentation](https://store.arduino.cc/arduino-uno-smd-rev3) (see Juraj's comment) is of relevance here, click the tab "Tech Specs" to find:

> Operating Voltage     5V
>
> Input Voltage (recommended)   7-12V
>
> Input Voltage (limit)     6-20V

While the microcontroller's (ATmega328P) operating voltage is 5 V there is an on-board voltage regulator to make the board work within the input voltage range of 6 to 20 V (max limits) or the recommended range of 7 to 12 V.

Operating this Arduino with a 12 V power adapter is within spec and therefore safe to do. The current rating of the adapter of 1.2 A is also more than sufficient to run the Arduino.

body:
Yes, you can power an Arduino with 12V into the barrel connector. It will then use it's internal voltage regulator to drop that to the 5V it needs internally. However, that is on the high side of it's recommended range, and will make the Arduino's voltage regulator run hot. A 7.5V supply would be better, and you could probably get more total current out of the 5V regulator without overheating if you fed it 6V or 7.5V instead of 12V. (6V is the lower limit. >= 7V is better.)

(A linear voltage regulator like the one in most Arduino boards essentially uses a transistor as a variable resistor to lower the voltage from the input voltage to 5V, which converts the excess voltage to heat. The higher the input voltage, and the more current you draw from the regulator, the more heat it generates.)