body:
I've built this simple Arduino controlled led-array. The Arduino sets a 5v pin on a relay to connect the high current power supply to a led array.
However, just before the led array is being fully turned on I'm getting this fast flash of the led array. I really would like to have the led working in an "on/off" manner.

[![Scheme][1]][1]

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

I remember that working with some motors one have to use capcitator in parallel because of resistence drop. Is it also the case with led array? And if it is why so, and why a capcitator would help?

Thank you very much.

title: LED array flashes once before being lit

Answers: 1

body:
As Wendall says in his comment, you probably have an issue with the power-on state of your logic pins before the Arduino finishes booting up.

In addition to that, you should **not** drive a relay directly from an Arduino logic pin, for a couple of reasons:

 1. It can't provide enough current to drive a relay coil.
 2. The relay emits a strong surge of reverse current when you switch it off. This will likely destroy the logic pin you are using to drive the relay, or it might even destroy the whole Arduino board.

For these reasons you should drive the relay using a transistor, and you should put a properly sized diode wired across the relay coil backwards from the flow of current when the relay is energized. The diode bleeds off the reverse current from the relay coil.


body:
I'm having problems creating a 32-bit integer from a 4-byte array. In the following complete, minimal, and verifiable example, converting a byte array containing `0x00, 0x04, 0x04F, 0x45` results in `4F45` (expected result would be `44F45`). I must be overlooking something fundamental here.... can anyone see where I went wrong?

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

    void loop()
    {
        uint8_t bytes[4] = {0x00, 0x04, 0x4F, 0x45}; //00044F45
        int32_t theInt = byteArrayToInt32(bytes);
        Serial.println(theInt, HEX); //Print 4F45
        delay(250);
    }

    uint32_t byteArrayToInt32(uint8_t* bytes)
    {
        uint32_t i = 0;
        i |= bytes[0] << 24;
        i |= bytes[1] << 16;
        i |= bytes[2] << 8;
        i |= bytes[3];
        return i;
    }

title: Unexpected results when creating 32-bit int from byte array

Answers: 1

body:
The problem is that you are trying to shift `uint8_t` more than 8 bits and then `OR` it with `int32_t`.

You have to `cast` the `uint8_t` to `int32_t` before doing the shift.

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

    void loop()
    {
        uint8_t bytes[4] = { 0x00, 0x04, 0x4F, 0x45}; //00044F45
        int32_t theInt = byteArrayToInt32(bytes);
        Serial.println(theInt, HEX); //Print 4F45
        delay(1000);
    }

    int32_t byteArrayToInt32(uint8_t* bytes)
    {
        int32_t i = 0;
        i |= (int32_t) bytes[0] << 24;
        i |= (int32_t) bytes[1] << 16;
        i |= (int32_t) bytes[2] <<  8;
        i |= (int32_t) bytes[3];
        return i;
    }


body:
[![enter image description here][1]][1]let me describe my schema, i got one arduino and one esp32 connected over i2c using 30m cat 5e ftp cable, I'm using 12v to power up both devices, each of them have dc-dc converter that convert to 5V, there is two P82B715P extenders, controllers i2c bus is wired with 10K pullups to P82B715P , i2c bus between P82B715P is wired with 1K pullups on master device side. On 30M cable it works only if I transmit SDA, SCL in twister pair with ground, no power voltage (+12V) is on the cable. When I place +12V on the cable, I2C bus stop working, tried to decrease pullups to 0.4K no effect, since I do not understand can only make try/fail tests. Question is do I need to adjust pullups beween P82B715P only,  or I need to change pullups between P82B715P and esp/arduino? Perhaps for calculation of pullups I must mention that i2c bus work on 10KHz

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

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

title: Calculate pullup resistor, cat5e ftp

Answers: 0


body:
I want to start a relay, have it run for 3 seconds, stop for 10 seconds, repeat.

I can't use delay, because I have a motor driver starting / stopping every 100 milis.

So I put together this code, but it does not work. Any help appreciated.

There's a 500ms delay to stop too much debugging info.

Also for some reason, tenSecondsBool switches to true as soon as you run the code.

    unsigned long threeSeconds=3000; // the time we need to wait
    unsigned long threeSecondsMillis=0; // millis() returns an unsigned long.
    unsigned long fourSeconds=7000; // the time we need to wait
    unsigned long fourSecondsMillis=0; // millis() returns an unsigned long.

    unsigned long previousMillis=0; // millis() returns an unsigned long.
    bool ledState = false; // state variable for the LED
    bool led2State = false; // state variable for the LED
    unsigned long tenSecondMilis=0; // millis() returns an unsigned long.
    unsigned long tenSeconds=10000; // the time we need to wait

    unsigned long paliGasiMilis=0; // millis() returns an unsigned long.
    unsigned long paliGasi=1000; // the time we need to wait

    unsigned long ventMilis=0; // millis() returns an unsigned long.
    unsigned long ventInt=100; // the time we need to wait

    bool threeSecondBool = false;
    bool tenSecondBool = false;

    int Fin1 = D7;

    #define enA D1
    #define in1 D2
    #define in2 D3
    #define button 4

    int rotDirection = 0;
    int pressed = false;

    void setup() {
      Serial.begin(9600); // send and receive at 9600 baud
      pinMode(enA, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(button, INPUT);
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      pinMode(Fin1, OUTPUT);
      digitalWrite(Fin1, HIGH);
      threeSecondBool = false;
      tenSecondBool = false;
    }

    void loop() {

     unsigned long currentMillis = millis(); // grab current time

     if ((unsigned long)(currentMillis - tenSecondMilis) >= tenSeconds) {
        Serial.print("---------------\n");
        Serial.print("10 second end\n");
        Serial.print("---------------\n");
        tenSecondBool = true;
        tenSecondMilis = millis();
    }

    Serial.print("10 second bool = ");
    Serial.print(tenSecondBool);
    Serial.print("\n");
    Serial.print("3 second bool = ");
    Serial.print(threeSecondBool);
    Serial.print("\n");

     if (tenSecondBool) {
      if ((unsigned long)(currentMillis - threeSecondsMillis) >= threeSeconds) {
       Serial.print("---------------\n");
       Serial.print("3 second end\n");
       Serial.print("---------------\n");
       threeSecondBool = true;
       threeSecondsMillis = millis();
      }
     }

    if (!tenSecondBool && threeSecondBool){
      Serial.print("Both triggered!\n");
      digitalWrite(Fin1, HIGH);
    }

    if (!tenSecondBool && !threeSecondBool){
      Serial.print("Both triggered!\n");
      digitalWrite(Fin1, HIGH);
    }

    if (tenSecondBool && threeSecondBool){
      threeSecondBool = false;
      tenSecondBool = false;
      digitalWrite(Fin1, LOW);
    }

    delay(500);

      if ((unsigned long)(currentMillis - ventMilis) >= ventInt) {
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
        ventMilis = millis();
      } else {
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
      }

    }

title: Start / end events using milis

Answers: 2

body:
Your code is somewhat confusing, probably because it has too many
variables. For doing what you describe, the program only needs to
remember two things:

 * is the relay in the ON state or in the OFF state?
 * when was the last time the relay changed state?

These can be represented as follows:

<!-- language-all: lang-c++ -->

    bool relay_is_on = false;
    unsigned long last_relay_change = 0;

Then, I recommend you use descriptive names for your variables and
constants. Calling a constant `threeSeconds` is not useful. It has no
added value over just typing `3000`. Having the constant named
`RELAY_ON_TIME` makes it a lot clearer what it is intended for. It is a
common convention to name the constants with all caps to make them stand
out relative to variables:

    const uint8_t RELAY_PIN = ...;
    const unsigned long RELAY_ON_TIME  =  3000;  //  3 s ON
    const unsigned long RELAY_OFF_TIME = 10000;  // 10 s OFF

With this in place, periodically switching the relay on and off can be
achieved as follows:

    void loop()
    {
        unsigned long now = millis();
        if (relay_is_on && now - last_relay_change >= RELAY_ON_TIME) {
            // Turn off.
            digitalWrite(RELAY_PIN, LOW);
            relay_is_on = false;
            last_relay_change = now;
        }
        if (!relay_is_on && now - last_relay_change >= RELAY_OFF_TIME) {
            // Turn on.
            digitalWrite(RELAY_PIN, HIGH);
            relay_is_on = true;
            last_relay_change = now;
        }
    }

body:
If you want a timer with millis with different intervals, then you can change the interval.

I use the [Blink Without Delay][1] to start with, and I borrow the 'relay_is_on' from the answer by Edgar Bonet.

    unsigned long previousMillis;
    unsigned long interval;
    bool relay_is_on;

    void loop() {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        if (relay_is_on) {
          // Relay was on, now turn it off.
          interval = 10000;
          digitalWrite (relayPin, LOW);
          relay_is_on = false;
        } else {
          // Relay was off, now turn it on.
          interval = 3000;
          digitalWrite (relayPin, HIGH);
          relay_is_on = true;
        }
      }
    }

The global variables can be set to a value to start with (for example 3000 for the interval) or they can be set in the setup() function. You have to choose what you want to start with. For example one second or one minute delay before it starts is also possible.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
I'm constructing a circuit that needs both voltage supplies (for 3.3V RFID and 5V relay, GPS and screen) but the Uno is physically too big so I need to use a nano or mini pro, both of which I can only get in 5V. I understand how to use a regulator to drop 5V to 3.3V for the RFID-IC power but I keep seeing instructions to use a level shifter between the IC outputs and arduino input pins. I was just wondering if the Uno has a built-in level shifter for all pins or some other method as the I/O pins do not have specified voltages or uses.

Thanks for your time.

title: How does the dual 5V and 3.3V output on the Uno R3 work exactly?

Answers: 3

body:
You can get pro-mini in 3.3V, but this has little to do with your problem.

The nano runs on 5V, but has an on-board regulator which supplies 3.3V power, although the logic I/O is 5V.

Level shifters can be used to perform logic level translation, but are not always needed.

The output of a 3.3V logic circuit will drive the INPUT of a 5V logic circuit (technically this is marginal, but works in practice).

5V logic outputs can be connected to 3.3V inputs with a simple voltage divider (you can use level shifter or other methods). Without some means of limiting voltage there is a risk of damaging the 3.3V logic.

Without more detail of exactly what you are planning it is not possible to be more precise.

body:
Pins of the UNO/Nano/Mini/Mega board are connected to GPIO pins of the MCU without any additional circuit. The ATmega MCU running at 5 V will sense 3.3 V as HIGH because of the threshold level to convert voltage to logic state.

ATmega will read the pin HIGH from 0.6 * Vcc, so at 5 V Vcc the threshold is 3 V.

Sources:

 - [Schematics of Arduino Uno][1]
 - [Datasheet of ATmega328p][2] (28.2 DC Characteristics)

  [1]: https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

body:
There are no built-in level shifters on the Uno; it doesn't need them. Uno's 3.3v pin is merely a convenience for supplying a low-current 3.3v device but there is no provision made for level shifting if/when that is necessary.

Genuine Uno's can deliver a *max* of 150mA to the 3.3v pin, so plan your current-budget conservatively. In my dual-voltage designs (2 voltage rails on a board with 3.3v & 5v parts), I reduce the "raw" 5v with a 3.3v regulator (typically an LM1117-3.3 part) rather than drawing it off of the regulated 5v power. (I put "raw" in quotes because I usually supply the board with a pre-regulated 5 volts (USB or wall-wart).

For I/O levels, a 3.3v part's HIGH level is within the range of what Uno will read as HIGH. In the other direction, Uno's HIGH level is too high for a 3.3v part and needs to be shifted down to 3.3v. If there are only one or two such signals (Uno -> 3.3v device), a voltage divider circuit would be less expensive and use less board space than a level-shifter. The level-shifter board would be an extra purchase but it is a quick and dirty solution if you have the space for it.


body:
I'm stuck and don't know how to get over it.
The problem: i want to use a push button for a menu with 2 screens(frames)
Frame1: if i push the button i want to turn on the light from the room1
        if i press it again i want to turn the light off in the room1

Frame 2: using the same button: i want to turn on the light in the room2
         pressing it again i want to turn the light off in the room2

Now.. the problem i encounter...
if i'm in frame 1 and press the button then the light from room1 will turn on but also the light from the room2 will turn on. and i don't want that.
All i want is to tell somehow to uC that in the frame1 it should turn on only the light from the room1
Please, someone smarter than me ..give me an ideea how can i do that.
i cannot post the code because there are over 3000lines and would be time consuming for you to read it all.

for the buttons i use a counter to see if the state has changed and if so then increment and do what it has to do.
Also i think that the problem is here because i use the same counter in both functions.

---

    int btn1 = 46,starebtn1, stareVechebtn1 = 0, btn2 = 50, starebtn2, stareVechebtn2 = 0;
    int btn3 = 42, starebtn3, stareVechebtn3 = 0,btn4 = 40, starebtn4, stareVechebtn4 = 0,btn5 = 44, starebtn5, stareVechebtn5 = 0;
    int cntbtn1 = 0, cntbtn2 = 0,cntbtn2_1 = 0, cntbtn3 = 0, cntbtn4 = 0, cntbtn5 = 0;
    int soilMoisture = A0;
    int buzzer = 3;
    boolean frame1 = false, frame2 = false;
    int procentajUmiditate(){
      int mSensorValue = analogRead(soilMoisture);
      mSensorValue = map(mSensorValue,0,1023,180,0);
      return mSensorValue;
    }
    void setup()
    {
      Serial.begin(9600);
      dht.begin();
      rtc.begin();
      pinMode(ledVerde,OUTPUT);
      pinMode(buzzer,OUTPUT);
      pinMode(soilMoisture,INPUT_PULLUP);
      pinMode(btn1,INPUT);
      pinMode(btn2,INPUT);
      pinMode(btn3,INPUT);
      pinMode(btn4,INPUT);
      pinMode(btn5,INPUT);
      imagineSistemDomotic();
      delay(3000);
      imagineCasaWifi();
      delay(4000);
      tone(buzzer,1000);
      delay(500);
      noTone(buzzer);
      delay(500);
      digitalWrite(ledVerde,HIGH);
    }

    void loop()
    {

      starebtn1 = digitalRead(btn1);
      starebtn2 = digitalRead(btn2);
      starebtn3 = digitalRead(btn3);
      starebtn4 = digitalRead(btn4);
      starebtn5 = digitalRead(btn5);
      int h = dht.readHumidity();
      int t = dht.readTemperature()-2;
      int f = dht.readTemperature(true);
      temp = t;
      hum = h;
      houR = rtc.getTimeStr();
      dateR = rtc.getDateStr();

    //conditii procentaj umiditate si pornire automata irigare
    if(procentajUmiditate()<20)
    {
      //relayOn
    }
    else
    {
      //relayOff
    }

    //btn1
     if(starebtn1 != stareVechebtn1)
      {
        if(starebtn1 == HIGH)
        {
          Serial.println(cntbtn1);
          cntbtn1++;
        }
      stareVechebtn1 = starebtn1;
      }//end btn1

    //btn2
     if(starebtn2 != stareVechebtn2)
      {
        if(starebtn2 == HIGH)
        {

          cntbtn2 = cntbtn2+1;

        }
        stareVechebtn2 = starebtn2;
      }//endbtn2

    //btn3
     if(starebtn3 != stareVechebtn3)
      {
        if(starebtn3 == HIGH)
        {
          cntbtn3 = cntbtn3+1;
        }
        stareVechebtn3 = starebtn3;
      }//endbtn3

    //btn4
     if(starebtn4 != stareVechebtn4)
      {
        if(starebtn4 == HIGH)
        {
          cntbtn4 = cntbtn4+1;
        }
        stareVechebtn4 = starebtn4;
      }//endbtn4

    //btn5
     if(starebtn5 != stareVechebtn5)
      {
        if(starebtn5 == HIGH)
        {
          cntbtn5 = cntbtn5+1;
        }
        stareVechebtn5 = starebtn5;
      }//endbtn5

    //ecran1
         if(cntbtn1 == 1)
        {
         displayInteriorTempHum();
         //u8g.drawStr(23,58,temp.c_str());
        // u8g.drawStr(99,58,hum.c_str());
        }
    //ecran2
         if(cntbtn1 == 2)
        {
         displayInteriorLights();
        }

    //ecran3
          if(cntbtn1 == 3)
        {
         displayExteriorValues();
        }

         if(cntbtn1 == 4) cntbtn1 = 0;
         if(cntbtn2 == 3) cntbtn2 = 1;
         if(cntbtn2_1 == 3) cntbtn2_1 = 1;
         if(cntbtn3 == 3) cntbtn3 = 1;
    } //end loop

    void imagineSistemDomotic()
    {
      u8g.firstPage();
      do{
        u8g.drawFrame(0,0,128,64);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(0,30,"Sistem Domotic");
        }while(u8g.nextPage());
    }

    void imagineCasaWifi()
    {
       u8g.firstPage();
       do{
        u8g.drawFrame(0,0,128,64);
        u8g.drawBitmapP( 0, 1, 16, 64, CasaDomoticaImage2);
         }while(u8g.nextPage());
    }

    void tempInterior()
    {
       u8g.firstPage();
       do{
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,15,128,49);
        u8g.setFont(u8g_font_5x7);
        u8g.drawStr(2,24,dateR.c_str());
        u8g.drawStr(101,24,houR.c_str());
        u8g.setFont(u8g_font_courB10);
        u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
        u8g.drawCircle(40,46,1);
        u8g.drawStr(23,58,"26");
        u8g.setFont(u8g_font_10x20);
        u8g.drawStr(43,58,"C");
        u8g.setFont(u8g_font_courB10);
        u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
        u8g.drawStr(99,58,"57");
        u8g.drawStr(117,58,"%");
         }while(u8g.nextPage());
    }

    void displayExteriorValues()
    {
           frame1 = false;
           frame2 = true;
      u8g.firstPage();
          do{
            u8g.setFont(u8g_font_courB10);
            u8g.drawStr(32,10,"Exterior");
            u8g.drawFrame(0,12,128,51);
            u8g.drawLine(64,12,64,62);

           if(cntbtn2 == 1)
           {
            //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
            u8g.setFont(u8g_font_5x8);
            u8g.drawStr(78,23,"Irigare");
            u8g.drawStr(78,30,"pornita");
            u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
            u8g.setPrintPos(15,40);
            u8g.setFont(u8g_font_courB10);
            u8g.print(procentajUmiditate());
            if(procentajUmiditate()<100)
            {
              u8g.setPrintPos(34,40);
              u8g.print("%");
            }
            else
            {
              u8g.setPrintPos(44,40);
              u8g.print("%");
            }

           }

      else{

          //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(78,23,"Irigare");
          u8g.drawStr(78,30,"pornita");
          u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
         // u8g.drawBitmapP( 20, -20, 16, 64, LightOff);
        // valoare buna FanOffLOGO   u8g.drawStr(10,23,"Ventilatie");
       // valoare buna FanOffLOGO    u8g.drawStr(20,30,"oprita");
        //  u8g.drawBitmapP( -15, 24, 16, 64, fanOffLogo);
           u8g.drawStr(10,23,"Umid. Sol");
           u8g.drawBitmapP( 12, -1, 16, 64, UmiditateSol);
           }
           }while(u8g.nextPage());
        cntbtn2 = 0;
    }

    void displayInteriorLights()
    {

       u8g.firstPage();
          do{
          u8g.setFont(u8g_font_courB10);
          u8g.drawStr(32,10,"Interior");
          u8g.drawFrame(0,12,128,51);
          u8g.drawLine(64,12,64,62);
          u8g.setFont(u8g_font_5x8);

          if(cntbtn2 == 1)
          {
          u8g.drawStr(73,23,"Dormitor");
          u8g.drawStr(75,60,"L.aprinsa");
          u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
          }
          else if(cntbtn2 == 2)
          {
          u8g.drawStr(73,23,"Dormitor");
          u8g.drawStr(75,60,"L.stinsa");
          u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
          }
          else{
          u8g.drawStr(73,23,"Dormitor");
          u8g.drawStr(75,60,"L.stinsa");
          u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
          }

          if(cntbtn3 == 1)
          {
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.aprinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
          }
          else if(cntbtn3 == 2)
          {
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.stinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
          }
        //else if(digitalRead(relay)

        else{
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.stinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        }
          }while(u8g.nextPage());

    }

    void displayInteriorTempHum()
    {
          u8g.firstPage();
          do{
          u8g.setFont(u8g_font_courB10);
          u8g.drawStr(32,10,"Interior");
          u8g.drawFrame(0,15,128,49);
          u8g.setFont(u8g_font_5x7);
          u8g.drawStr(2,24,dateR.c_str());
          u8g.drawStr(101,24,houR.c_str());
          u8g.setFont(u8g_font_courB10);
          u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
          u8g.drawCircle(40,46,1);
          u8g.drawStr(23,58,temp.c_str());
          u8g.setFont(u8g_font_10x20);
          u8g.drawStr(43,58,"C");
          u8g.setFont(u8g_font_courB10);
          u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
          u8g.drawStr(99,58,hum.c_str());
          u8g.drawStr(117,58,"%");
          digitalWrite(ledVerde,LOW);
            }while(u8g.nextPage());
    }

title: How to independently control two lights with a single button and a menu system?

Answers: 3

body:
Difficult to advise without more clear information but here's a couple of ideas to play around with (currently typing on my phone, will edit later).

If using a physical menu and buttons then you need some way to track location. You could try adding proximity sensors to check physical location/proximity to the light source and let that be the deciding variable for which bulb gets activated. You could use a "universal remote" approach, using separate arduinos (per light) with IR receivers.

If using an app menu, like on a phone, try declaring a variable "room" and have the button pass the frame name or ID number based on the frame ("bedroom" or "kitchen", "1" or "2" etc) as that variable via your communication line to the arduino. On the arduino side, declare the same variable and process the received data from the app i.e. String room = your-room-ID. Ensure you have separate pinout declarations for each bulb you want to control i.e. #define kitchen 14 # define livingroom 15... setPin(output, kitchen), setPin(output, livingroom) then modify your bulb activation line to be pinout(room, HIGH);

body:
The code you show is indeed too long. However, a cursory look seems to
indicate that you are not using any debouncing library. This is then the
first thing you should do. There are probably many options. I will
suggest [Bounce2][] which, in addition to debouncing, handles the edge
detection. Then you have the `fell()` method that tells you whether the
input signal just fell since the last time it was tested, which is a way
to detect the button press.

Then, within `loop()`, you would add something like this:

<!-- language:lang-c++ -->

    if (mainButton.update() && mainButton.fell()) {

        // Find the pin that controls the appropriate light.
        uint8_t lightPin;
        if (currentFrame == FRAME1) {
            lightPin = PIN_LIGHT_ROOM_1;
        } else {  // FRAME2
            lightPin = PIN_LIGHT_ROOM_2;
        }

        // Toggle the light.
        if (digitalRead(lightPin) == HIGH) {
            digitalWrite(lightPin, LOW);
        } else {
            digitalWrite(lightPin, HIGH);
        }
    }

The assumptions I am making should be pretty obvious:

* `currentFrame` is a variable updated by your menu system. Its value
  can only be one of the constants `FRAME_1` or `FRAME_2`
* `PIN_LIGHT_ROOM_1` and `PIN_LIGHT_ROOM_2` are constants holding the
  pin numbers which control the corresponding lights.

[Bounce2]: https://github.com/thomasfredericks/Bounce2

body:
It's really very simple, I think...  If I understood properly...

    global frame, lightRoom1, lightRoom2

    function changeFrame ( ) {

    // if frame == 1, change it to 2

        if ( frame == 1 ) {
            <commands to refresh display>;
            frame = 2;
        } else {
            <commands to refresh display>
            frame = 1;
        }

    }

    function switchLight ( ) {

    // roomno = frameno.
    // if light on, switch off; if off, switch on.

        if ( frame == 1 ) {

            if ( lightRoom1 == false ) {
                <code to switch light on >;
                lightRoom1 == true;
            } else {
                <code to switch light off >;
                lightRoom1 == false;
            }

        }

        if ( frame == 2 ) {

            // same as above but for room 2.

        }

    }

    if ( digitalRead ( framePin ) == LOW ) {
        changeFrame ( );
    }

    if ( digitalRead ( lightPin ) == LOW ) {
        switchLight ( );
    }


body:
I have an ESP32 project which I'd like to be able to update OTA. The trouble is that it is in deep sleep for approximately 15 minutes before waking up, connecting to WiFi sending an MQTT packet then going back to sleep.

I would like to be able to have a webpage hosted on a Raspberry Pi with a repository of datestamped .bin files that the ESP32 can connect to, check it's current version against the available options, if there is an applicable update, go through the standard OTA update protocol, or if there is no new available version, don't check again for 24 hrs.

How do I go about this?

title: OTA updating the ESP32 from a separate server

Answers: 0


body:
I'm developing an interactive LED table for an university assignment that is being controlled by an Arduino Mega2560 which gets the information about which LEDs should be lit in which colour from a Java application that runs on a Raspi 3b+. So far everything is almost finished and the program is running quite smoothly.

The whole time I've been developing the Java application on a PC and it worked just perfect. Now I wanted to move the application to the Pi to have a runnable demo for a meeting with my advisor. Therefore I wanted to check on which USB port the Arduino connects to the Pi so I can setup the corresponding part of the Java code correctly. As I also wanted to set a specific descriptive port name on which the Arduino is always accessible for the Java application I followed [this][1] tutorial.

In a previous attempt where I still used 2 Arduino Duemilanove that step worked however when I now try to find the Arduino Mega with `dmesg | grep ttyUSB` I get no results and `ls -l /dev/ttyUSB*` only tells me that there is no such path or directory. I also retried that with one of the Arduino Duemilanove in case the USB cable was defective but in that case it returned a valid result.

As the code that I need to run on the Arduino is too extensive for using 2 Arduino Duemilanove (due to the array size to represent the table) I definitely need to run this on the Mega. After many attempts to find a solution I didn't find anything that helps me in my situation as every thread on a similar topic was about a board that wasn't recognized on any machine (whereas my Mega gets recognized on my normal Windows PC). As the Duemilanoves get recognized seamlessly I conduct that it's probably not a problem caused by the Pi (or at least not only the Pi).

I read that using a powered USB hub could be a possible solution. However, as the Arduino itself is powered by a power supply  I suppose that using a powered USB hub would not help much in this case? However I'd be happy if someone proved me wrong in this case and solving the issue was as easy as that.

  [1]: https://www.domoticz.com/wiki/Assign_fixed_device_name_to_USB_port

title: Arduino Mega not recognized on Raspberry Pi 3b+

Answers: 1

body: The newer Arduinos, like the Uno or Mega 2560, have a different way of managing the Serial ↔ USB translation, compared with the older Duemilianove. From the Linux side, you shouldn't see much difference, except that the device is now `/dev/ttyACM0` instead of `/dev/ttyUSB0`.


body:
[![Micro-SD breakout][1]][1]]
[![Connection to MEGA][2]I am having quite a bit of trouble trying to get my Arduino MEGA 2560 to read my micro-SD card. My wiring is as follows:

    Breakout    Arduino
    5v            5v
    Gnd           Gnd
    CLK           52
    DO            50
    DI            51
    CS            53
    CD            Was not connected and then connected to 47 (neither worked)

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

    #include <Wire.h> //library necessary to use I2C communications bus
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME680.h>
    #include <SD.h>
    #include <SPI.h>

    const uint8_t chipSelect = 53; //chipSelect pin for the SD card Reader
    const uint8_t cardDetect = 47;

    File CO2Data; //Data object you will write your sensor data to

    void setup() {
    Serial.begin(115200);//"begins" the serial monitor so you can print stuff out when connected to the computer (set baud rate to 115200)
    Wire.begin ();//begins the I2C communications bus so it can talk to the K33

    Serial.print("Initializing SD car...");
    pinMode(53, OUTPUT);

    if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1) ;
    }
    Serial.println("card initialized.");
    File CO2data = SD.open("datalog.txt", FILE_WRITE);
    if (! CO2data) {
    Serial.println("error opening datalog.txt");
    // Wait forever since we cant write data
     while (1) ;
    }}

The SD card is formatted to FAT32.

Thank you for any help!

  [1]: https://i.stack.imgur.com/qW66k.jpg
  [2]: https://i.stack.imgur.com/93ZFM.jpg

title: Adafruit Micro-SD breakout not initializing on MEGA 2560

Answers: 1

body:
The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved! (Check your voltages).

From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.


body:
I keep getting *'myservo' does not name a type* as an error message, I have already looked other solved questions like this one but I can´t find the mistake. I would be very glad for your help.

    /*********************************************************
     * Bot control
     * By soleil_zero
     * Based on code by
     * MSc. Fausto M. Lagos S.
     * @piratax007
     * V2.0.0 - 2019
     * GNU GPLV3+
     *
     * Hardware:
     * Arduino Mega2560
     * Adafruit Motor Shield V1.2
     * Bluetooth module H6
     * 1 Servo
     * 2 DC Motor
     *********************************************************/

    // Librería para Adafruit Motor Shield V1.2 y Servo
    #include "AFMotor.h"
    #include "Servo.h"

    // Motores conectados en los puertos 1 y 2
    AF_DCMotor leftMotor(1, MOTOR12_64KHZ);
    AF_DCMotor rightMotor(2, MOTOR12_64KHZ);

    Servo myservo;
    myservo.attach(9);

    // Variable para el paso de mensajes vía Bluetooth
    char message;
    //ángulo de rotación del servo
    int angle = 0;

    void setup() {
      // Velocidades en los motores
      leftMotor.setSpeed(150);
      rightMotor.setSpeed(150);

      /* Debido a que el Adafruit Motor Shield V1.2 ocupa los pines digitales 0 y 1 para la conexión del módulo HC05
         bluetooth deben utilizarse cualquiera de los otros disponibles: 14 (TX3) y 15 (RX3) o 16 (TX2) y 17 (RX2) o
         18 (TX1) Y 19 (RX1). De acuerdo a cuál de los cuatro pines se utilicen deben modificarse las líneas
         relacionadas a la comunicación Serial e.g si se utilizan los pines 18 y 19 la instrucción será Serial1 */
      Serial3.begin(9600);
      myservo.write(angle);
    }

    void loop() {
      // Verificación de mensaje en el puerto Serial
      if (Serial3.available() > 0) {
        message = Serial3.read();
      }

     if (message == 'F') {//Forward
        leftMotor.run(FORWARD);
        rightMotor.run(FORWARD);
      } else if (message == 'B') {//Backwards
        leftMotor.run(BACKWARD);
        rightMotor.run(BACKWARD);
      } else if (message == 'L') {//Left
        leftMotor.run(FORWARD);
        rightMotor.run(BACKWARD);
      } else if (message == 'R') {//right
        leftMotor.run(BACKWARD);
        rightMotor.run(FORWARD);
      } else if (message == 'S') {//stop
        leftMotor.run(RELEASE);
        rightMotor.run(RELEASE);
        Serial3.print("stop");
      }
      } else if (message == 'U') {//down
        angle = 0;
        servo1.write(angle);
      }else if (message == 'D') {//up
        angle = 90;
        servo1.write(angle);
      }
    }

title: 'myservo' does not name a type

Answers: 1

body:
In C and C++ languages we write statements *inside functions*. That `myservo.attach(9);` is a *statement*. You can't just write it in the middle of the file. It has to reside inside a function.

In your code `myservo.attach(9);` just sits in the middle of nowhere. You had enough sense to put `leftMotor.setSpeed(150);` inside `setup()`. Why did you suddenly decide to place `myservo.attach(9);` outside of any functions?

Function `setup()` would be an appropriate place for this statement.


body:
[![Arduino Pro Mini wiring][1]][1][![Arduino Uno wiring][2]][2]

I have a project where I am getting sensor data and sending it over to an ESP8266-01 to send to ThingSpeak. After some work I got it to work. So like a real smart person I decided to replace the Arduino UNO I was using (that worked) with an Arduino Pro Mini. Using the same code and connections the String isn't sent to the ESP and then not to ThingSpeak.

Here is a reduced version of the sending code that I used on the UNO and the Pro.

    #include <FS.h>
    #include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
    #include <EEPROM.h>
    //needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
    #include <ArduinoJson.h>
    //#include <SoftwareSerial.h>

    //SoftwareSerial espSerial(A0, D1); // RX | TX
    //stuff to bring in string
    const byte numChars = 32;
    char receivedChars[numChars];
    char tempChars[numChars]; // temporary array for use when parsing
    // variables to hold the parsed data
    char messageFromPC[numChars] = {0};
    float floatFromPC = 0;
    float floatFromPC2 = 0;
    boolean newData = false;
    //end stuff ti bring in string
    String f;
    String start = "start";
    //NEW STUFF START
    char Password[36] = "";
    char apiKey[16] = "";
    WiFiClient client;
    //eeprom new end
    char defaultHost[100] = "";
    //Thing Speak IP address (sometime the web address causes issues with ESP :/
    long itt = 500;
    long itt2 = 500;
    const byte wifiResetPin = 13;
    int interruptPinDebounce = 0;
    long debouncing_time = 1000;
    volatile unsigned long wifiResetLastMillis = 0;
    bool shouldSaveConfig = false;

    void saveConfigCallback () {
      Serial.println("Should save config");
      shouldSaveConfig = true;
    }

    void handleWifiReset() {
      if (millis() < wifiResetLastMillis) {
        wifiResetLastMillis = millis();
      }
      if ((millis() - wifiResetLastMillis) >= debouncing_time) {
        Serial.println("Clearing WiFi data resetting");
        WiFiManager wifiManager;
        wifiManager.resetSettings();
        SPIFFS.format();
        ESP.reset();
        delay(1000);
      }
      wifiResetLastMillis = millis();
    }
    int addr = 0;
    void setup() {
      //EEPROM.begin(512); //Initialize EEPROM
      WiFiManager wifiManager;
      Serial.begin(9600);
      //espSerial.begin(115200);
      pinMode(wifiResetPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset, FALLING);
      WiFiManagerParameter customAPIKey("apiKey", "ThingSpeakWriteAPI", apiKey, 16);
      //END NEW STUFF
      //WiFiManager
      //Local initialization. Once its business is done, there is no need to keep it around
      //WiFiManager wifiManager;
      //NEW STUFF START
      //wifiManager.setSaveConfigCallback(saveConfigCallback);
      wifiManager.addParameter(&customAPIKey);
      //END NEW STUFF
      //reset saved settings
      //wifiManager.resetSettings();
      //set custom ip for portal
      //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
      //fetches ssid and pass from eeprom and tries to connect
      //if it does not connect it starts an access point with the specified name
      //here  "AutoConnectAP"
      //and goes into a blocking loop awaiting configuration
      wifiManager.autoConnect("AutoConnectAP");
      Serial.println("Connected");
      //NEW STUFF START
      strcpy(apiKey, customAPIKey.getValue());
      if (shouldSaveConfig) {
        Serial.println("saving config");
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.createObject();
        json["defaultHost"] = defaultHost;
        json["apiKey"] = apiKey;
        Serial.println("API");
        Serial.print(apiKey);
        String apiKey2 = String(apiKey);
        File configFile = SPIFFS.open("/config.json", "w");
        if (!configFile) {
          Serial.println("failed to open config file for writing");
        }
        json.printTo(configFile);
        json.printTo(Serial);
        delay(1000);
        configFile.close();
        //end save
      }
      Serial.println("local ip");
      Serial.println(WiFi.localIP());
      //END NEW STUFF
      //or use this for auto generated name ESP + ChipID
      //wifiManager.autoConnect();
      //Serial.println("WriteApi");
      //Serial.println(apiKey);
      //if you get here you have connected to the WiFi
      //Serial.println("K)");
      //save the custom parameters to FS
      strcpy(apiKey, customAPIKey.getValue());
      EEPROM.begin(512); //Initialize EEPROM
      // write appropriate byte of the EEPROM.
      // these values will remain there when the board is
      // turned off.
      EEPROM.write(addr, 'A'); //Write character A
      addr++; //Increment address
      EEPROM.write(addr, 'B'); //Write character A
      addr++; //Increment address
      EEPROM.write(addr, 'C'); //Write character A
      //Write string to eeprom
      String www = apiKey;
      for (int i = 0; i < www.length(); i++) {
        //loop upto string lenght www.length() returns length of string
        EEPROM.write(0x0F + i, www[i]); //Write one by one with starting address of 0x0F
      }
      EEPROM.commit(); //Store data to EEPROM
      //Read string from eeprom
    }

    //callback notifying us of the need to save config
    void loop() {
      //new stuff string
      recvWithStartEndMarkers();
      if (newData == true) {
        strcpy(tempChars, receivedChars);
        // this temporary copy is necessary to protect the original data
        //   because strtok() used in parseData() replaces the commas with \0
        parseData();
        showParsedData();
        newData = false;
      }
      //new stuff string end
      WiFiManager wifiManager;
      if (WiFi.status() == WL_DISCONNECTED) {
        wifiManager.autoConnect("AutoConnectAP");
      }
      delay(1000);
      if (WiFi.status() == WL_CONNECTED) {
        Serial.println("Connected");
        delay(1000);
        WiFiClient client;
        long itt = 50;
        long itt2 = 200;
        char defaultHost[100] = "api.thingspeak.com";
        EEPROM.begin(512);
        Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
        Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
        addr++; //Increment address
        Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
        addr++; //Increment address
        Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
        //Read string from eeprom
        String www;
        //Here we dont know how many bytes to read it is better practice to use some terminating character
        //Lets do it manually www.circuits4you.com  total length is 20 characters
        for (int i = 0; i < 16; i++) {
          www = www + char(EEPROM.read(0x0F + i)); //Read one by one with starting address of 0x0F
        }
        Serial.print(www); //Print the text on serial monitor
        if (client.connect(defaultHost, 80)) { // "184.106.153.149" or api.thingspeak.com
          itt++; //Replace with a sensor reading or something useful
          String postStr = www;
          postStr += "&field1=";
          postStr += String(floatFromPC);
          postStr += "&field2=";
          postStr += String(floatFromPC2);
          postStr += "\r\n\r\n\r\n";
          client.print("POST /update HTTP/1.1\n");
          client.print("Host: api.thingspeak.com\n");
          client.print("Connection: close\n");
          client.print("X-THINGSPEAKAPIKEY: " + String (www) + "\n");
          client.print("Content-Type: application/x-www-form-urlencoded\n");
          client.print("Content-Length: ");
          client.print(postStr.length());
          client.print("\n\n\n");
          client.print(postStr);
          Serial.println("% send to Thingspeak");
        }
        client.stop();
        Serial.println("Waiting…");
      }
      delay(5000);
    }

    //more new stuff for string
    void recvWithStartEndMarkers() {
      static boolean recvInProgress = false;
      static byte ndx = 0;
      char startMarker = '<';
      char endMarker = '>';
      char rc;
      while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();
        if (recvInProgress == true) {
          if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
              ndx = numChars - 1;
            }
          } else {
            receivedChars[ndx] = '\0'; // terminate the string
            recvInProgress = false;
            ndx = 0;
            newData = true;
          }
        } else if (rc == startMarker) {
          recvInProgress = true;
        }
      }
    }

    void parseData() { // split the data into its parts
      char * strtokIndx; // this is used by strtok() as an index
      strtokIndx = strtok(tempChars, ","); // get the first part - the string
      strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC
      strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
      floatFromPC = atoi(strtokIndx); // convert this part to an integer
      strtokIndx = strtok(NULL, ",");
      floatFromPC2 = atoi(strtokIndx); // convert this part to a float
    }

    void showParsedData() {
      Serial.print("Message ");
      Serial.println(messageFromPC);
      Serial.print("Float ");
      Serial.println(floatFromPC);
      Serial.print("Float ");
      Serial.println(floatFromPC2);
    }
    //end new stuff string

Sorry for the length but... I don't know if I need to modify how I send the string or I have to turn on the TX and RX pins in the Pro Mini. I have tried connecting the RX Arduino to TX ESP and TX Arduino to RX ESP and RX to RX and TX to TX with no results. I know the pins work because I have programmed the ESP and the PRO numerous times with the TX and RX pins.

Can anyone help me with this? It is driving me crazy.

  [1]: https://i.stack.imgur.com/99qK9.png
  [2]: https://i.stack.imgur.com/v5zsm.png

title: Sending a string from Arduino to ESP8266 works on UNO but not on Pro Mini

Answers: 1

body:
I finally got this to work by repeating the Serial.print (f); and then delay(1000); multiple times.  I changed my original post to reflect this.  Somehow this gets the string over to the ESP so it can parse it and upload it.  Now all I want to do is add a temperature sensor and maybe add an IFTTT to the whole thing so if the low end gets too low or the high end too high (of the water level I can get a notification to check out the whole system.
Thanks JRobert for the help I got the power I needed to the board.


body:
I am building a mini-cnc laser engraver as shown in this [intructable][1] and this [youtube video][2].

I have built the circuit (minus the jst connector and two male pins at the top left of the board) and have attached a stepper motor from a dvd drive. It worked like a charm, but made a loud ringing noise (like tinnitus.) I proceeded to test it with laser GRBL, and it moved great, but gradually started missing steps, at first only in one direction and eventually in both. After a couple hours of being connected, it wouldn't budge at all. I switched the motor for another motor, and tested it again. This time the motor was much shorter-lived. It made 5 steps perfectly and then just shut off. You could hear the motor try to turn, but it was like it didn't have any torque at all. What could be the issue? (I also tried it on the other axis with the other motor driver, no change.)

It's also worth noting that at one point both the positive and negative (ground) cables from my power supply made contact with metal at once, throwing a spark. However, the steps were already beginning to be lost **before** that happened.

As per your request, I have attached the circuit layout I am attempting (it's identical to the one in the tutorial) as well as a [picture][3] of my physical circuit board. (sorry, a link was my only option as the pics were to big for upload) I know the soldering is pretty bad- I have a giant soldering iron. I don't see any shorts though.

[![Intended Layout][4]][4]

  [1]: https://www.instructables.com/id/DIY-Arduino-Mini-Laser-Engraver/
  [2]: https://www.youtube.com/watch?v=QZgZL9u1BBw
  [3]: https://drive.google.com/drive/folders/199vTjMnB_HO5Il4q4YlpWqPEFlPRZVVC?usp=sharing
  [4]: https://i.stack.imgur.com/owkHr.png

title: Are my stepper motors being burnt out? What is the issue here?

Answers: 1

body: So the problem was that somehow the potentiometer had reset its own vref output. I couldn't adjust it after it did this. I replaced both drivers and it works like a charm now.


body:
I've been trying to run the following esp32 LED PWM code to change the LED's brightness, and show the current PWM duty on the webpage, but the PWM values on the webpage won't change until I hit the submit button twice.

    #include <Arduino.h>
    #include <WiFi.h>
    #include <WebServer.h>
    WebServer ser(80);
    int s=0;
    String k;

    String iso()
    {
      k="
LED PWM<FORM action=\"/\" method=\"post\"><input type=\"text\" name=\"duty\">
 <input type=\"submit\" value=\"Submit\">Cureent Duty=";
      k=k+s;
      k=k+"
";

      return k;
    }

    void root()
    {
      iso();
      ser.send(200, "text/html", iso());

      if (ser.hasArg("duty"))
      {
          iso();
          s=ser.arg("duty").toInt();
          ledcWrite(4, s);
          iso();
          ser.send(200, "text/html", iso());
      }
    }

    void setup() {
      Serial.begin(9600);
      ledcAttachPin(33, 4);
      ledcSetup(4, 5000, 8);
      WiFi.begin("ssid", "pass");
      Serial.print("\nConnecting To WiFi");
      while (WiFi.status()!=WL_CONNECTED)
      {

        Serial.printf("\n.");
      }
      Serial.print("\nConnected");

      ser.on("/", root);
      ser.begin(80);
    }

    void loop() {
      ser.handleClient();
    }
Here's a GIF addressing the issue

[![Issue][1]][1]

  [1]: https://i.stack.imgur.com/Zk9vY.gif

title: Webpage values wont update

Answers: 1

body:
When the client sends you a request, you should answer _only once_. Your
`root()` function attempts to answer twice whenever the request contains
the argument “duty”. The client will not handle a duplicate response to
a single request.

Here is your `root()` function:

<!-- language-all: lang-c++ -->

    void root()
    {
      iso();
      ser.send(200, "text/html", iso());  // ← first response

      if (ser.hasArg("duty"))
      {
          iso();
          s=ser.arg("duty").toInt();
          ledcWrite(4, s);
          iso();
          ser.send(200, "text/html", iso());  // ← second response
      }
    }

You may notice that the first response was sent _before_ updating the
duty cycle.

The proper way to handle the request is to first handle the request
parameters, if any, _then_ send the response:

    void root()
    {
      if (ser.hasArg("duty")) {
        s = ser.arg("duty").toInt();
        ledcWrite(4, s);
      }
      ser.send(200, "text/html", iso());  // ← only sent once
    }

As a side note, there is absolutely no need to build the response five
times (you have five calls to `iso()` within `root()`) when you only
need it once!


body:
All welcome.

I'm trying to connect nodemcu to the phone's wifi.

And nodemcu can't do it. But sometimes after several reboots she does it. Also if i use my old phone - nodemcu connects perfectly! Why?

My "new" phone: Fly FS504 Cirrus 2

My old phone: Fly IQ4504 Quad.

My code:

    #include <ESP8266WiFi.h>

    const char *ssid =  "Just my SSID";

    const char *pass =  "Some password";

    WiFiClient client;

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

           Serial.println("Connecting to ");
           Serial.println(ssid);

           WiFi.begin(ssid, pass);
           while (WiFi.status() != WL_CONNECTED)
              {
                // stack here (only with new phone)
                delay(500);
                Serial.print(".");
              }
          Serial.println("");
          Serial.println("WiFi connected");
    }

    void loop()
    {

    }

title: Nodemcu does not connect to phone wifi

Answers: 1

body:
From my experience the esp8266's wifi is a little bit buggy sometimes. I'm not sure if it has something to do with the esp auto-connecting to known networks, but I managed to work-around this issue by explicitly `WiFi.disconnect()`ing from any potential network right before calling `WiFi.begin()`.

Another thing that I noticed several times is that the esp can be easily disturbed when connected to a breadboard, in special when wifi is in use (in this case the esp might even crash). There must be some bad interferences, I guess.


body: I am working with Arduino. I'm using 2 Arduino boards along with 2 ESP8266 modules to transfer data from one Arduino to another Arduino. I want to transfer GPS values from system 1 to system 2 using Wi-Fi module ESP8266 along with Arduino UNO. I've written the main codes for server and client end. I'm not able to print anything on LCD if I'm using ESP8266 and selected 'generic ESP8266' boards.

title: Showing GPS Values on I2C LCD using Arduino and ESP8266

Answers: 0


body:
It is possible to control one relay using Blynk app and also using an atmega? To a better understanding think at a relay that will turn on a fan when you use the blynk app. but when you don;t have the phone around you, using a pushbutton, you can turn it on from there(the button will be connected to atmega)

---

```#define EspReadPin 6

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

  pinMode(relCh2,OUTPUT);

  pinMode(relCh3,OUTPUT);

  pinMode(relCh4,OUTPUT);
  digitalWrite(relCh1,HIGH);
  pinMode(EspReadPin, INPUT);
  digitalWrite(relCh3,HIGH);
}
void loop()
{
Serial.println(digitalRead(6));
delay(400);
  if(digitalRead(EspReadPin == 1))
  {
    digitalWrite(relCh3,LOW);
  }
  else if(digitalRead(EspReadPin == 0))
  {
    digitalWrite(relCh3,HIGH);
  }
}

title: Esp and blynk app

Answers: 1

body:
Yes it is possible.

Use [the Blynk example sketch][1] to activate the pin of the esp8266. Read the pin of the esp8266 with the ATMega. Handle in ATmega sketch the esp8266 pin as a second button.

  [1]: https://examples.blynk.cc/?board=ESP8266&shield=ESP8266 WiFi&example=GettingStarted/VirtualPinWrite


body:
I need send http request to my own server from arduino uno.

First of all I connected the board through web client configurator.

I tried different codes, the last one is:
    /*
    File: RestClient.ino
    This example makes an HTTP request after 10 seconds and shows the result both in
    serial monitor and in the wifi console of the Arduino Uno WiFi.

    Note: works only with Arduino Uno WiFi Developer Edition.

    http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient
    */

    #include <Wire.h>
    #include <UnoWiFiDevEd.h>

    void setup() {

      const char* connector = "rest";
      const char* server = "<MY IP>";
      const char* method = "GET";
      const char* resource = "/";

      Serial.begin(9600);
      Serial.println("prima");
      Ciao.begin();
      Serial.println("dopo");

      pinMode(2, INPUT);

      //delay(1000);
      doRequest(connector, server, resource, method);
    }

    void loop() {

    }

    void doRequest(const char* conn, const char* server, const char* command, const char* method){
      Serial.println("Im doing the request");
      CiaoData data = Ciao.write(conn, server, command, method);
      if (!data.isEmpty()){
        Ciao.println( "State: " + String (data.get(1)) );
        Ciao.println( "Response: " + String (data.get(2)) );
        Serial.println( "State: " + String (data.get(1)) );
        Serial.println( "Response: " + String (data.get(2)) );
      }
      else{
        Ciao.println ("Write Error");
        Serial.println ("Write Error");
      }
    }

But I get "Write Error" and the server does not recive any request

title: ARDUINO UNO WIFI R3 (Dev Edition) Send simple http get request

Answers: 0


body:
I am new I took a code of keypad in arduino. Arduino code is not working in setup area but if I place the same code in loop are it works why? Kindly guide me.
Here is the code.

    #include <Keypad.h>

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    //define the cymbols on the buttons of the keypads
    char hexaKeys[ROWS][COLS] = {
      {'0','1','2','3'},
      {'4','5','6','7'},
      {'8','9','A','B'},
      {'C','D','E','F'}
    };
    byte rowPins[ROWS] = {2, 3, 4,5}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad

    //initialize an instance of class NewKeypad
    Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    void setup(){
      Serial.begin(9600);
      char customKey = customKeypad.getKey();

      if (customKey){
        Serial.println(customKey);
      }
    }

    void loop(){

    }

title: Keypad code not working

Answers: 0


body:
My display is not responding to this code. Help please

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

    #define OLED_MOSI 10
    #define OLED_CLK 9
    #define OLED_DC 12
    #define OLED_CS 13
    #define OLED_RESET 11
    Adafruit_SSD1306 display(OLED_MOSI,OLED_CLK,OLED_DC,OLED_CS,OLED_RESET);

    void setup(){
      Serial.begin(9600);
      display.begin(SSD1306_SWITCHCAPVCC);
      display.clearDisplay();

      display.setTextSize(1);
      display.setCursor(30,30);
      display.print("Hello WOrld");
      display.display();
      }

      void loop(){

        }

title: OLED DISPLAY USING SPI

Answers: 1

body:
Pin definitions in your code seem to be mixed up. If Adafruit example works fine with your setup, you should keep the pin definitions Adarfruit uses:

    #define OLED_MOSI   9
    #define OLED_CLK   10
    #define OLED_DC    11
    #define OLED_CS    12
    #define OLED_RESET 13

Also, you are using a deprecated constructor. It is recommended to use a constructor which explicitly specifies display size.


body:
I have a coordinator radio hooked up to a sparkfun xbee shield, hooked up to an Uno. This is then hooked up to my computer. This coordinator talks with a number of xbee routers/end devices and sends them 6 commands to change the digital pins high or low on the corresponding xbees. The commands are always frame ID = 0, then the last (6th) command I send a 0x2 to save all the digital pins high or low at once.

The issue is that occasionally when the xbee receives all of the commands and saves them, the Uno will reset itself. (I can tell by the blinking LED on 13).

I have looked into it, and the best suggestion so far is to disable D7 on the receiving Xbee via XCTU. This unfortunately has not helped. Is there another reason that the arduino is resetting every couple of times I change the pins on the xbee? It doesn't happen every time, just once out of every 3-5 times...

title: Xbee S2C is resetting Arduino Uno

Answers: 1

body:
Bleh, I figured it out. Not only do I have to turn D7 off, I also have to hook a jumper between 5V and RST as shown here.
https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/all


body:
So I am very confused at the results I am getting.
It seems that floats aren't working properly, and I don't understand why.

I was trying to read a temp sensor and convert the reading to celsius. However, when I tried to divide the value (an int between 145-165) by 1024, and multiply by 5 I would get back a float value of 0.00
Here's the code I was using

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

    }

    void loop() {
      int sensorVal = analogRead(A0);
        Serial.print("Sensor Value: ");
        Serial.println(sensorVal);

      float voltage = ((sensorVal/1024) * 5);
        Serial.print("Voltage Value: ");
        Serial.println(voltage);

    }

This would only return values of 0.00 for voltage, even though the sensor itself is working fine, returning varying values between 146 and 165 based on how much heat I apply.
This didn't make any sense, so I tried it with some other values, eg.

    Serial.print(float (10 / 6));
and

    Serial.print(float (5 / 2));

which should have returned 1.67 and 2.50 respectively, but instead returned 1.00 and 2.00

I think it might be a settings thing, where all floats round down to an int, but that seems really weird.

Any help would be great!

title: All floats feedback a rounded down integer

Answers: 3

body:
You are doing integer arithmetic. Try adding .0 to the end of your values where you need the floating point results.

For example...

```C

  float voltage = ((sensorVal/1024.0) * 5.0);
```

Remember the results of analog read is an integer. So the conversion to a float in you original code only happens when the "=" is being "executed". Another possibility is to cast it to a float straight away.

```C

  float voltage = ((((float)sensorVal)/1024.0) * 5.0);
```

Or more simply
```C

  float voltage = ((float)sensorVal)/1024.0 * 5.0;
```

body:
GMc explained what to do, but didn't explain in detail why your code fails to give floating point results.

Most languages evaluate expressions using order of operations. C and C++ are no exception to this.

In C/C++, while the expression is being evaluated, the compiler also decides what data types to use for each part. integer-integer expressions are evaluated using integer math. If either of the parts of an expression is a larger/floating point type, both values are "promoted" to the larger/more complex type before evaluating the expression.

in your code

    float voltage = ((sensorVal/1024) * 5);

The `sensorVal/1024` bit is evaluate first. Since both `sensorVal` and `1024` are integers, the compiler uses integer math. That yields an int result, and so any fractional part is truncated and lost.

It then evaluates `result*5` (where `result` is the result of the first part, `sensorVal/1024`, which is an integer.) Both of those parts are integers, so the result of that expression is an int.

Finally, you ask the compiler to store the result into a float, `voltage`. The compiler then promotes the integer result of the whole expression to a float, but you've lost any floating point part of your calculations.

By rewriting your line as

    float voltage = ((sensorVal/1024.0) * 5.0);

The compiler does what you want. The `sensorVal/1024.0` bit is now integer-float math, so the compiler "promotes" `sensorVal` to a float and then does float-float math. The second part is now float-float, so the result is also floating point.

    float voltage = ((sensorVal/1024.0) * 5);

Would also work in this case (where `5` is an integer constant.) That works because `float_result*5` is float-integer math, and the compiler will promote `5` to a floating point value and do float-float math. to get the final result. However, it's safer to use all floating point constants so you don't accidentally do part of your calculations using integer math and truncate that part before converting to floating point.

As you say, making `sensorVal` a float also would be a good idea. (Again, to avoid accidentally doing integer math on part of your expression and getting wrong results in the process. In this case making `sensorVal` a float isn't needed, but with a different expression you might wind up with integer math for part of the calculation.)

body:
You already got a couple of perfectly good answer. I will nevertheless
suggest a slightly different idiom:

    float voltage = sensorVal * (5.0 / 1024);

or, maybe better:

    const float V_REF = 5.0;  // at the top of the sketch

    float voltage = sensorVal * (V_REF / 1024);

The reason this is slightly better than the other options is because
division – even integer division – is a very expensive
operation on the smaller Arduinos. By writing the conversion as in the
lines above, the ratio `V_REF / 1024` becomes a compile-time constant,
which is evaluated by the compiler at build time. Then, only the much
cheaper multiplication needs to be done by the Arduino itself, at run
time. Not a big deal if you are not time constrained, but it's a
low-hanging fruit in terms of optimization.

You may write `1024.0` instead of `1024` if it feels safer. I tend to
keep the `.0` for the voltage only, because 1024 is an integer, whereas
the “5” in “5 volts” is conceptually a real number (it's an
_analog_ voltage, and not even exactly 5 V if you bother to measure
it). But this is just a personal preference at the end.


body:
I am trying to connect three separate DHT11 to my Wemos d1 r1.
I have each sensor hooked to a power pin which turns on and off, the sensor pin and a common ground.
Here is my code:
<!-- language-all: lang-cpp -->

    #include <DHTesp.h>
    #include <ESP8266WiFi.h>

    String apiKey = "xxxxxxxxxxxxxx";
    const char* ssid = "xxxxxxxxxxx";
    const char* password = "xxxxxxxxxxxx";
    const char* server = "api.thingspeak.com";

    DHTesp dht;
    DHTesp dht2;
    DHTesp dht3;
    WiFiClient client;

    void setup() {

      pinMode(D6,OUTPUT);
      pinMode(D8,OUTPUT);
      pinMode(D1,OUTPUT);

        Serial.begin(115200);
        dht.setup(D5, DHTesp::DHT11);
        dht2.setup(D7, DHTesp::DHT11);
        dht3.setup(D2, DHTesp::DHT11);
        WiFi.begin(ssid, password);

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
    digitalWrite(D6,HIGH);

    }

    void loop() {
     digitalWrite(D6,HIGH);
      delay(8000);

        float t = dht.getTemperature();
        float f = (t*1.8) + 32;

        if (isnan(t))
      {
        Serial.println("Failed to read from DHT2 sensor!");
        return;
      }
        Serial.print(", \"maintemp\": ");
        Serial.print(f);
        Serial.print("}\n");

    digitalWrite(D6,LOW);
    digitalWrite(D8,HIGH);
    delay(8000);

        float t2 = dht2.getTemperature();
        float f2 = (t2*1.8) + 32;

        if (isnan(t2))
      {
        Serial.println("Failed to read from DHT3 sensor!");
        return;
      }
        Serial.print(", \"lowtemp\": ");
        Serial.print(f2);
        Serial.print("}\n");

    digitalWrite(D6,LOW);
    digitalWrite(D1,HIGH);
    delay(8000);

        float t3 = dht3.getTemperature();
        float f3 = (t3*1.8) + 32;

        if (isnan(t3))
      {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }
        Serial.print(", \"uptemp\": ");
        Serial.print(f3);
        Serial.print("}\n");

        digitalWrite(D1,LOW);

        delay(2000);

        if (client.connect(server, 80)) {
        String postStr = apiKey;
        postStr += "&field3=";
        postStr += String(f);
        postStr += "&field4=";
        postStr += String(f2);
        postStr += "&field5=";
        postStr += String(f3);
        postStr += "\r\n\r\n\r\n\r\n";

        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(postStr.length());
        client.print("\n\n\n\n");
        client.print(postStr);

        Serial.print("Temperature: ");
        Serial.print(f);

        Serial.println("Sending data to Thingspeak");
      }
      client.stop();

      Serial.println("Waiting 20 secs");
      // thingspeak needs at least a 15 sec delay between updates
      // 20 seconds to be safe

      delay(53700);
    }

As you can see I assign a separate DHT to each sensor pin and turn on and off the power pins to each sensor.  They all have a common ground.

When I run the code the first sensor reads the temperature but the second one says "Failed to read from DHT3 sensor!".

It is not the sensor because if I swap the first and second sensor the first one always read and the second fails.  If I eliminate the second sensor the third one fails.  I have tried to power all of the sensor pins in SetUP but still the first one is the only one to work.  Is there some kind of trick I have to use here.
I am using DHTESP.h since the regular DHT.h didn't work with the Wemos Pro Mini.

Has anyone had any experience with this to give me some guidance.

Thanks

title: Multiple dht11 on an wemos d1 r1

Answers: 1

body: You probably have to create an set up a new DHT object each time you turn the power on. My guess is that the sensor needs to be initialized by the Arduino before it is ready to take readings, and when you turn the power off and back on it loses its configuration.


body: I am new to arduino and need some help. I just baught light bars for my jeep and wiring harnesses with them, the harnesses come with buttons and I wanted to replace the button and have them controlled on my phone. The harnesses come with a relay and a fuse and a button all 12v, How would i go about using my raspberry pi or udoo x86(which has built in adruino) to basically replace the rocker switch so i can then turn things on and off without needing to have actual switches.

title: New to arduino, help wiring relay

Answers: 1

body:
To drive a relay you'll need a transistor (a MOSFET is a good choice) and you'll need a diode across the relay coils to protect the transistor from the reverse current pulse when you remove power from the relay coils.

As Majenko says, if you Google "Arduino relay" you'll find lots of articles covering the topic. (And if you use a digital output line from your PI the exact same circuit will work.)

This MOSFET is a good option for switching high current loads with a 5V logic signal:

https://www.adafruit.com/product/355

The diode will need to be a power diode that can handle your voltage/current needs. You'll need to figure out how much current your light bar uses, and then I'd suggest a diode that can handle twice that much current (at 12V) for a margin of safety.


body:
I am fairly new to arduino and ESP though am very familiar with css and javascript.

I have an esp webserver that includes a button

    client.print("<button style='background-color: #F30C0C; color:#000;'></button>");

but need it to change the css backbround-color when pin is reading HIGH

     if (c == '\n') {
              currentLineIsBlank = true;
              buffer = "";
            }
            else if (c == '\r') {
              if (buffer.indexOf("GET /?relay1") >= 0)
                relayPIN1read = digitalRead(relayPIN1);

              if (relayPIN1read == HIGH) {
                digitalWrite(relayPIN1, LOW);
              }
              if (relayPIN1read == LOW) {
                digitalWrite(relayPIN1, HIGH);
              }
            }
          }

Does any one know of any way to do this?

title: Change css form color from esp32 if statement

Answers: 1

body:
First print everything up to the colour. Then print the colour, which you change depending on the state of the pin. Then print the rest.

    client.print("<button style='background-color: ");

    if (digitalRead(PIN) == HIGH) {
        client.print("#0CF30C");
    } else {
        client.print("#F30C0C");
    }

    client.print("; color:#000;'></button>");


body:
Using Arduino Leonardo, IDE 1.8.9, Windows 10.

For a short time, when I first got the Leonardo, Windows 10 would recognize the board; I could see it in devices, Windows 10 would make a sound when plugged in, it would show listed in the ports of the IDE, and I could upload my code to the board (confirmed with blinking light sketch). ***It no longer does.***

The error I get in the IDE `avrdude: butterfly_recv(): programmer is not responding`.

I believe the main issues stems from I had selected Arduino UNO (I have a couple of those as well) in the IDE and Uploaded my sketch.

Ever since I did this, Windows 10 no longer recognizes the board when plugged in. It doesn't even show in "other devices" under device manager.

I have tried the following:

 - The on-board reset trick that seems to be most of what other users experience and solves their issue. All variations. Holding the reset button, uploading, releasing, etc.
 - Swapping cables. Confirmed with another device it was a data cable and working.
 - Uninstalling and reinstalling the IDE
 - Restarting numerous times
 - Burning boot loader - since Windows 10 won't recognize the device, this fails immediately can't even communicate to the board.

I have seen similar questions about this, but none of them seem to specifically cover what I am encountering.

title: Windows 10 does not recognize Arduino Leonardo

Answers: 1

body:
Sounds like you've bricked it.  Your broken sketch (wrong MCU selected) means that it's not presenting a CDC/ACM port.

Your best bet is to use a hardware programmer (eg USBASP or another Arduino) to erase the chip and reload the bootloader.


body:
I am working on a program where I am controlling an MP3 player by using UART between my MEGA2560 and the MP3 player. The MEGA2560 sends serial commands to the MP3 player when external interrupts are generated on INT4 and INT5 and it all seems to work fine.

When I want to test my program I press the RESET button on the Arduino in order to start the program. However, sometimes the program only starts after pressing the RESET button multiple times. This happens often but not all the time, which is weird.

What do you think could be the reason for this?

title: MEGA2560 only starts program after pressing RESET button multiple times

Answers: 0


body:
I have a project I am working on, based on an ESP32 from NodeMCU. I have a bunch of sensors connected to said ESP32 - they all work and the code itself "works" with a minor quirk.

The issue in question starts with a DHT11 sensor. I started from the basic "hello world" DHT11 code (you can find it easily with a DHT11 search in google). That sensor works in my code that you can see below - I copied and pasted the sample code, and except for changing variables, did not alter the sample code really at all.

The issue I have is that while the sample code will read accurately on every loop, in my code, it reads from the sensor exactly once the first time the loop runs, and then never again.

I believe I have isolated the issue to this bit of code and the corresponding function it calls (it didn't used to be a function - that was a troubleshooting step):

```c++
  if (!client.connected()) {
    reconnectMQ();
  } etc...
```

By moving this statement and grouping the MQTT messaging to the end, the system runs a full loop with correct readings, exactly once, but after that function is called the DHT11 begins failing to read.

Things I have tried:
<ul>
    <li> different variable names for temp and humidity (in case "t" and "h" are in use in the MQ library)
    <li> order of operations (made the loop work once)
    <li> changing the reconnectMQ() to a full function and not just a loop in the main loop
    <li> changing the logic of the DHT11 sensor to at least not hang forever trying to read - this meant it got through this part, but with 0 values
    <li> "turning off" MQ - this means that everything works, but obviously is a bit like cutting off your arm for a sprained wrist.
    <li> ENDLESS Google and Stack searches before resorting to this post.
</ul>

I hate to do this as my project is 200 lines long, but I suspect the full code is needed to see what's possibly happening.

```c++
#include <time.h>
#include <DHT.h>
#include <WiFi.h>
#include <PubSubClient.h>

//use pin 23 to read temp and humidity
//our sensor is DHT11 type
//creates an instance of DHT sensor
#define DHTPIN 23
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

//Define the analog pins inbound for the Soil Moisture sensors
const int sm1Pin = 33;
const int sm2Pin = 34;
const int sm3Pin = 35;
const int sm4Pin = 32;

const int power = 22;
const int exec = 21;
const int net = 19;

//define the pin for the light level reading
const int light = 36;

//Init MQTT payload arrays
char data0[50];
char data1[50];
char data2[50];

// declare our Wifi and MQTT connections and other constant settings for the network
const char* ssid     = "*******";            // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = "*******";                          // The password of the Wi-Fi network
const char* mqtt_server = "192.168.1.195";                             // The target mqtt server
const char* input_string = "{\"Reporting\":\"GardenUnit1\", ";       // The name of this garden monitor unit
String clientId = "GP1";
int lcount = 0;

// declare our Wifi and MQTT connections
WiFiClient espClient;
PubSubClient client(espClient);

//
// Reconnects to the MQTT message-bus if the connection died, or we're
// not otherwise connected.
//
void reconnectMQ() {

  digitalWrite(net, LOW);  // turn the Blue NET LED Off

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Wifi not connected - configuring");
    setup_wifi();
  } else {
    Serial.println("Wifi Connected - connecting MQTT");
  }

  // Attempt to connect
  Serial.println("Attempting to connect to MQTT Server...");
  while (!client.connected()) {
    if (client.connect(clientId.c_str())) {
      Serial.println("connected to MQTT server");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }

  // Once connected, publish an announcement...
  String payload = String(input_string) + "\"MQTT\":\"Reconnected\"}";
  payload.toCharArray(data1, (payload.length() + 1));
  client.publish("control", data1); //the "control" topic is just for notifications - change to fit your needs

  digitalWrite(net, HIGH);  // turn the Blue NET LED on
  delay(5000);
}

void setup_wifi() {
  delay(10);
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  WiFi.begin(ssid, password);             // Connect to the wifi network

  while (WiFi.status() != WL_CONNECTED) // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print('.');

  Serial.println('\n');
  Serial.println("Connected!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());         // Send the IP address of the ESP32 to the serial port

}

void setup() {
  Serial.begin(9600); // open serial port, set the baud rate as 9600 bps
  // These Options control the precision of the reading, and the voltage reduction capability of the ESP32
  // Attenuation number 3 is 11DB
  analogSetWidth(10);
  analogSetAttenuation((adc_attenuation_t)3);

  // Define the MQTT Server connection settings and then launch the MQTT Connection
  client.setServer(mqtt_server, 1883);

  // Set output and input pins to correct modes
  pinMode (power, OUTPUT);
  pinMode (exec, OUTPUT);
  pinMode (net, OUTPUT);

  //Turn on Green Power light
  digitalWrite (power, HIGH);

  //Connect to the wireless network
  setup_wifi();

  //This call starts the dht11 sensor instance
  dht.begin();
}

void loop() {
  //Turn on RED EXEC light - this means a sample is being taken
  digitalWrite (exec, HIGH);

  //Read DHT11 Temp and Humidity - Humidity is a % and temp is in Celcius
  float hum = dht.readHumidity();
  float temp = dht.readTemperature();
  // Check if any reads failed but insert bogus data so system continues
    if (isnan(hum) || isnan(temp)) {
        Serial.println("Failed to read from DHT sensor!");
        client.publish("garden1", "{\"Error\":\"Humidty/Temp Sensor Offline!\"}");
        hum = 0;
        temp = 0;
    } else {
        // print the result to Terminal
        Serial.print("Humidity: ");
        Serial.print(hum);
        Serial.print(" %\t");
        Serial.print("Temperature: ");
        Serial.print(temp);
        Serial.println(" *C ");
    }

  //Read value and print to serial for S1
  float s1 = analogRead(sm1Pin);
  Serial.print("Sensor 1: ");
  Serial.print(s1);
  Serial.println();
  //Read value and print to serial for S2
  float s2 = analogRead(sm2Pin);
  Serial.print("Sensor 2: ");
  Serial.print(s2);
  Serial.println();
  //Read value and print to serial for S3
  float s3 = analogRead(sm3Pin);
  Serial.print("Sensor 3: ");
  Serial.print(s3);
  Serial.println();
  //Read value and print to serial for S4
  float s4 = analogRead(sm4Pin);
  Serial.print("Sensor 4: ");
  Serial.print(s4);
  Serial.println();

  float L1 = analogRead(light);
  Serial.print("Light level: ");
  Serial.print(L1);
  Serial.println();

  if (!client.connected()) {
    reconnectMQ();
  }

  String payload = String(input_string) + "\"S1\":\"" + s1 + "\", \"S2\":\"" + s2 + "\", \"S3\":\"" + s3 + "\", \"S4\":\"" + s4 + "\"}";
  payload.toCharArray(data0, (payload.length() + 1));
  Serial.println("Publishing message 1:");
  while (!client.publish("garden1", data0)) {
    Serial.print(".");
  }
  String payload2 = String(input_string) + "\"Humidity\":\"" + hum + "\", \"Temperature\":\"" + temp + "\", \"Light\":\"" + L1 + "\"}";
  payload2.toCharArray(data2, (payload2.length() + 1));
  Serial.println("Publishing message 2:");
  while (!client.publish("garden1", data2)){
    Serial.print(".");
  }

  //Turn off RED EXEC light - this means a sample is done
  digitalWrite (exec, LOW);
  lcount = lcount + 1;
  delay(10000);
}
```

What happens when the code I have here runs is that I see all the messages at the Mosquito server and in serial monitor, and the loop runs as expected. Due to the logic I had to put in to keep the program running, after the first reading from the DHT11, temp and hum come back as 0 forever. This is obviously not what I want.

What is obvious:
Something happens between the first reading of the DHT11 and the next that makes it unhappy.

What is not:
What that something is. That something occurs in the MQTT connection, but for the life of me I cannot figure out what it is or isolate it.

So now I leave it to the community. What the heck is happening here?!

title: Connecting to MQTT causes DHT11 Sensor to stop working?

Answers: 2

body: I've used the DHT11 library, not the DHT library in my sketches. The Example sketch should make it clear what minimal changes you'll need to make to your code.  It always worked well for me.

body:
Leaving this here in case anyone else has a similar issue as an "answer" to my own question:

Simply put - DHT11 library as used, and MQTT library as used conflict. That's it, that's the answer.

There are two options for correcting this depending on your needs:

- don't use or deeply examine and rebuild one of the libraries - frankly this was a negative ROI for me and not worth it

- Add an  ESP.restart();  at the end of the main program loop and AFTER the sleep timer - this reboots the ESP and allows the DHT11 to read BEFORE the MQTT connection happens and the solution works.

This, in my mind is not "a fix" it is a workaround, but it does address the primary issue.


body:
I'm uploading a file to Azure blob storage using REST API request. The file uploaded successfully using PHP curl request. But when I transfer the code into ESP32 HTTP client I'm getting an Authentication error. I also verify the HMAC key generated by the ESP32 Arduino code in PHP code.
I'm thinking that I'm missing something in adding header.
Here is my PHP code :
```
       $header = array (
        "x-ms-blob-type: BlockBlob",
        "x-ms-date: " . $date,
        "x-ms-version: " . $version,
        "Authorization: SharedKey account_name:" . $signature_str,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Length: " . strlen($fdata),
        );

    $url =  "https://acount_name.blob.core.windows.net/container/test.txt";
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata);
    curl_setopt ( $ch, CURLOPT_HEADER, True );
    echo($ch);
    curl_exec ( $ch );
```
and here is the corresponding Arduino IDE code:
```
    String sig = get_hmac();
      Serial.println(sig);

      if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        HTTPClient http;
        http.begin("https://account_name.blob.core.windows.net/container/test.txt");  //Specify destination for HTTP request

        http.addHeader("x-ms-blob-type", "BlockBlob");
        http.addHeader("x-ms-date", Date);
        http.addHeader("x-ms-version", "2018-03-28");
        http.addHeader("Authorization", "SharedKey account_name:"+sig);
        http.addHeader("Content-Type", "text/plain; charset=UTF-8");
        http.addHeader("Content-Length",  "20");

        int httpResponseCode = http.PUT(d);
        if (httpResponseCode > 0) {
          String response = http.getString();
          Serial.println(httpResponseCode);
          Serial.println(response);
        } else {
          Serial.print("Error on sending POST: ");
          Serial.println(httpResponseCode);
        }
        http.end();  //Free resources
      } else {
        Serial.println("Error in WiFi connection");
      }
```
The error I'm getting is :

> <AuthenticationErrorDetail>The MAC signature found in the HTTP request
> 'sVrSFpplX+Gkcb4R/iSDf6eqUP4srkZuVD68/pAeYwE=' is not the same as any
> computed   signature.....

Although the HMAC signature created from same String works in PHP
here is the reference page of the API:
https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob
Thanks

title: PUT request: PHP code to Arduino HTTPClient

Answers: 1

body:
I got clue from @esoterik answer and manage to send request successfully.
The problem were in adding header parameter:

     http.addHeader("Content-Length",  "20");

This duplicate the header( 2nd one added in PUT method). I just comment it and the code works.
Thanks for every one response


body:
i am working on a project for my school tech class. Our goal is to make a vehicle that will travel along a cable and drop an egg to a target while going down the cable. i am using an arduino to to open a trap door with a servo after a certain amount of time that is set by two push buttons, and a third push button will control when the timer starts.
Here is my circuit
[![enter image description here][1]][1]

Here is the code:

    #include <Servo.h>
    #include <LiquidCrystal.h>

    int b = 0;
    int up = 0;
    int down = 0;
    int val = 100;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    Servo myservo;

    int pos = 0;

    void setup()
    {
      pinMode(b, INPUT);
      pinMode(up, INPUT);
      pinMode(down, INPUT);
      lcd.begin(16, 2);
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop()
    {
      digitalRead(down);
      digitalRead(up);
      digitalRead(b);
      lcd.setCursor(0, 0);
      lcd.print("milli seconds:");

      while (b == HIGH)
      {
       digitalRead(down);
        digitalRead(up);
        digitalRead(b);
       lcd.setCursor(0, 1);
        lcd.print(val);
        myservo.write(0);
        if (up == HIGH, down == LOW)
        {
          val + 1;
        }
        if (down == HIGH, up == LOW )
        {
          val - 1;
        }

        delay(val);
        myservo.write(100);
        delay(1000);
      }
    }

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

title: Arduino timer to turn a serve at a certain time

Answers: 1

body:
in setup you are calling

    pinMode(b, INPUT);
    pinMode(up, INPUT);
    pinMode(down, INPUT);

but b, up and down all equal 0 so this is what you are doing is :

    pinMode(0, INPUT)
    pinMode(0, INPUT)
    pinMode(0, INPUT)

This doesn't do what you want at all, these need to be assigned to pins. All you are doing is repeatedly setting arduino digital pin 0 to INPUT 3 times.

secondly

    while(b == HIGH)

will never fire since b is 0 and is never set to anything else. so it will never == HIGH

Finally,

    digitalRead(down);

doesn't do anything useful; what it does is read from pin down which is set to 0, and then drops the return value on the floor

also, this,

    if (up == HIGH, down == LOW)

is just very wrong, sholud be

    if (up == HIGH && down == LOW)

anyway based on you scematic, fixing this code:

    #include <Servo.h>
    #include <LiquidCrystal.h>

    const int B = 7;
    const int UP = 8;
    const int DOWN = 9;
    int val = 100;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    Servo myservo;

    int pos = 0;

    void setup()
    {
      pinMode(B, INPUT);
      pinMode(UP, INPUT);
      pinMode(DOWN, INPUT);
      lcd.begin(16, 2);
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
      lcd.setCursor(0, 0);
      lcd.print("milli seconds:");
    }

    void loop()
    {
      // todo: debounce the switches
      int up = digitalRead(UP);
      int down = digitalRead(DOWN);
      int b = digitalRead(B);

      if (up == HIGH && down == LOW)
      {
         val += 1  // todo: handle overflow
      }

      if (down == HIGH && up == LOW )
      {
         val -= 1
      }

      lcd.setCursor(0, 1);
      lcd.print(val);

      if(b == HIGH)
      {
        myservo.write(0);
        delay(val);
        myservo.write(100);
        delay(val);
      }

    }

this will do what the origonal code was trying to do, more or less, but the
proper way to do this would be (in psuedo-code):

    // Setup pins etc.
    // Setup(): pinMode(...) ... etc.
    // Loop():
    //   debounce buttons
    //   handle up/down
    //   record milliseconds when button is pressed
    //   see how much time has passed
    //   trigger servo when timer has passed


body:
I would like to control the [TB67H303HG][1] (a full bridge driver IC for DC motor
adopting MOS in output transistor) with my Arduino UNO.
This is its [datasheet][1].

I was thinking to connect:

 - **PIN 3 INPUT** to Arduino Digital Output 13 and set it to LOW to use the direct PWM mode
 - **PIN 5 Vref** to 24VDC
 - **PIN 6 Vcc** to 24VDC
 - **PIN 7 STBY** to Arduino pin 8
 - **PIN 8 IN1** to Arduino Pin 12
 - **PIN 9 IN2** to Arduino Pin 11
 - **PIN 16 OUT1A** and **12 OUT1B** in parallel to the Motor
 - **PIN 14 OUT2A** and **10 OUT2B** in parallel to the Motor
 - **PIN 13** and **17** to GND
 - **PIN 20 Vcc** to 24VDC
 - **PIN 22 PWM** to Arduino PWM 10

I do not know if I'm wrong, but I think I should use IN1 and IN2 to select the motor spin rotation and the Pin 12 PWM to change the velocity by setting the Arduino pin 10 with the PWM output from 0 to 255. Is it correct?

Can you tell me if the wiring is correct?
Thank you a lot!

  [1]: https://toshiba.semicon-storage.com/info/docget.jsp?did=15071&prodName=TB67H303HG

title: Arduino UNO and TB67H303HG Ic driver: Wiring question

Answers: 1

body:
The Vref potential should not be 24V. As mentionned in the datasheet:

Vref = 0.3V to 1.95V depending on what you want.


body:
I have located the 5V voltage regulator chip on my Arduino board which I am hoping to use to power an attached device (which draws up to 500 mA at 5V).  The chip is next to the plug for the external voltage supply.  It says: `ON RUX 117-5`.  It looks like it's in a SOT−223 package (body about 6.1 by 3.4mm).

I used this page to shows 3 different possible voltage regulators from ON Semiconductors: https://www.mouser.co.uk/ON-Semiconductor/Semiconductors/Power-Management-ICs/Voltage-Regulators-Voltage-Controllers/LDO-Voltage-Regulators/_/N-5cgac?P=1z0wa29Z1z0xwtvZ1z0zlrjZ1ywvc7yZ1yxz1yoZ1ywvc5z

This gives two unique data sheets for [NCP1117LP][1] and [NCP1117, NCV1117][2].  But this is where I'm stuck.  They look pretty similar but not exactly the same data sheets.  Also I don't know what RUX stands for, perhaps this is important in figuring out what power rating the Arduino 5V line has.
Additionally the mouser.co.uk site says they're in SOT-223-3 packages but then gives dimensions which a) aren't the dimensions of the chip I have and b) are the dimensions of the SOT-223-4 package (6.3mm wide instead of the ~6.1 mm I have).

I don't care about the dimensions but I would like to correctly identify the chip on the Arduino board to be able to know what power I can draw from it before it shuts itself down.

  [1]: https://www.mouser.co.uk/datasheet/2/308/NCP1117LP-D-82673.pdf
  [2]: https://www.mouser.co.uk/datasheet/2/308/NCP1117-D-1595886.pdf

title: Maximum power rating for Arduino UNO revision 2 (SMD)

Answers: 1

body:
The [Arduno UNO SMD R2 uses an MCP33269 not an LM1117](https://www.arduino.cc/en/uploads/Main/arduino-uno-smd-schematic.pdf).  What you have is probably some cheap Chinese clone of the Arduino, and in that case the regulator will be the cheapest Chinese copy of the LM1117 available.  It's impossible to tell what the specs of that specific chip are.  Suffice it to say, though, that the specs of the chip are pretty much irrelevant since they rely on good heatsinking, which you most certainly don't have on a little Arduino board.

500mA, though, is a lot to push through a linear regulator like that, and when running from batteries the excess power loss imposed by the regulator will be a major factor in longevity.

You are better off investing in a proper switching regulator (such as a UBEC from a model aircraft supplier like [Hobbyking](https://hobbyking.com/en_us/kingkong-5v-3a-ubec.html)).


body:
OK,so this is my first program written via the Tinkercad utility. I have saved the program as a text file, and it equates to about 22K.

My simple question is, when uploaded / compiled to the actual board, is the size increased or decreased? I plan to use the Nano (32K) If it shrinks or stays roughly the same, I should be OK. However,if it 'bloats' due to extra C code ...

** As someone used to working with sub routines, arrays and variables, found it a bit of a hassle that everything has to be in one loop, only conditional statement breaking the flow - leastin TinkerCAD. And when you want to control 8 LED outputs, having to switch each one on and off via a digital write line. For example, the four output lines below:

    11001100
    01100110
    00110011
    10011001

... needs 32 digital write commands !! (And whilst the above is 4 lines, there are nearer 150 similar lines in final code, hence it's size)

The way I wrote it using ths above utility was something like:

    for(counter=0; counter<4; counter){
    if (counter==0){
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        digitalWrite(4, LOW);
        digitalWrite(5, LOW);
        digitalWrite(6, HIGH);
        digitalWrite(7, HIGH);
        digitalWrite(8, LOW);
        digitalWrite(9, LOW);
      }
    if (counter==1){
        digitalWrite(2, LOW);
        digitalWrite(3, HIGH);
        digitalWrite(4, HIGH);
        digitalWrite(5, LOW);
        digitalWrite(6, LOW);
        digitalWrite(7, HIGH);
        digitalWrite(8, HIGH);
        digitalWrite(9, LOW);
      }
    //etc
    }

title: Compiled sketch vs text file size

Answers: 2

body:
The size of the text file and the size of your compiled code are impossible to relate. The compiled size purely depends on *what* your code consists of, not the size.

To find out how much room your code will take on the chip you need to compile it. The IDE will then tell you how much flash and RAM it takes.

For example:

    Sketch uses 3730 bytes (13%) of program storage space. Maximum is 28672 bytes.
    Global variables use 157 bytes (6%) of dynamic memory, leaving 2403 bytes for local variables. Maximum is 2560 bytes.

body:
Does counter increase somewhere?  As written, it would always be 0, yes?

I would use

    for(counter=0; counter<4; counter = counter +1){ // or counter++

You could store your 8 bits in an array

    byte ledArray[] = {
    0b11001100, // or hex format, 0xCC
    0b01100110, // 0x66
    0b00110011, // 0x33
    0b10011001, // 0x99
    };

Then use a function call (subroutine by another name) to manipulate the outputs.


body:
Hey guys I have a led grid. it's 8 sides that are addressable with the bytes `'1'` through `'8'`. (a Kinect is sending these bytes through processing)  I have also creates three buttons in processing that change the colour of the leds. (`'R'`,`'G'`,`'B'`).

I'm stuck in the code, my code now when receiving the bytes: `'R'`, `'G'` or `'B'` changes all leds to that colour. instead of remembering the colour and only lighting up the sides determined by the `'1'`, `'2'`, `'3'`, `'4'`, `'5'`, `'6'`, `'7'`, `'8'` values.

I need it to remember the chosen R,G,B colour until another colour is chosen and only  use the bytes `'1'`, `'2'`, `'3'`, `'4'`, `'5'`, `'6'`, `'7'`, `'8'` to select what side of the grid to light up.

Here is my code so far:
<!-- language-all: lang-cpp -->
```
#include <FastLED.h>

#define LED_PIN     6
#define NUM_LEDS    360

CRGB leds[NUM_LEDS];
CRGB saved_color;

void setup()
{
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);

  Serial.begin(9600);

  FastLED.clear();
  FastLED.show();

}

void loop()
{

  if (Serial.available() > 1)
  {
    int incomingByte = Serial.read();

    if (incomingByte > '0' && incomingByte < '9')
    {
      FastLED.clear();
    }

    if (incomingByte == 'R') {
      saved_color = CRGB(255, 0, 0);
    }
    else if (incomingByte == 'G') {
      saved_color = CRGB(0, 255, 0);
    }
    else if (incomingByte == 'B') {
      saved_color = CRGB(0, 0, 255);

    }

    if (incomingByte == '1')
      for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '2')
      for (int i = 44; i <= 89; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '3')
      for (int i = 90; i <= 134; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '4')
      for (int i = 135; i <= 179; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '5')
      for (int i = 180; i <= 224; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '6')
      for (int i = 225; i <= 269; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '7')
      for (int i = 270; i <= 314; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '8')
      for (int i = 315; i <= 359; i++) {
        leds[i] = saved_color;

      }

    FastLED.show();
  }
}

```

I'll describe the project a bit more to elaborate. It's a lamp (octagon shape) with 45 leds on the 8 sides. each side is triggered by movement and  sends a byte (`'1'`, `'2'`, `'3'`, `'4'`, `'5'`, `'6'`, `'7'`, `'8'`) to turn on one side of the lamp.

I want to be able to select the colour before sending the bytes. so I need arduino to remember the `'R'`, `'G'`, `'B'` bytes and only change when I send the other byte.

title: Remembering a colour

Answers: 1

body:
The array `CRGB leds[NUM_LEDS]` only holds the current state of the LEDs. It is used to push the data out to the LEDs. If you want the code to save one color to use later, you need an extra variable, that can hold the color.

Add a variable at global scope:

    CRGB saved_color;

In the `if` statements for R, G and B you can set this variable to the corresponding value, for example:

    if(incomingByte == 'R'){
        saved_color = CRGB(255,0,0);
    }

And in the `if` statements of 1 to 8 you can use this value, for example:

    if (incomingByte == '1'){
        for (int i = 0; i <= 44; i++) {
            leds[i] = saved_color;
        }
    }

Note: The above code does not change any LEDs on R, G or B. They just set the color for future operation 1 to 8.