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

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

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);


sender: user

sender: assistant

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


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

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

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`.


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

[![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

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.


message:
'myservo' does not name a type

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);
      }
    }

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.


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

[![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

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.


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

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

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.


message:
Webpage values wont update

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

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!


message:
Nodemcu does not connect to phone wifi

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()
    {

    }

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.


message:
Esp and blynk app

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);
  }
}

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


message:
OLED DISPLAY USING SPI

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(){

        }

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.


message:
Xbee S2C is resetting Arduino Uno

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...

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


message:
All floats feedback a rounded down integer

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!

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.


message:
Multiple dht11 on an wemos d1 r1

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

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.


message:
New to arduino, help wiring relay

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.

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.


message:
Change css form color from esp32 if statement

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?

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>");


message:
Windows 10 does not recognize Arduino Leonardo

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.

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.


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

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?!

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.


message:
PUT request: PHP code to Arduino HTTPClient

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

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


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

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

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


message:
Arduino UNO and TB67H303HG Ic driver: Wiring question

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

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

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


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

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

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)).


message:
Compiled sketch vs text file size

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
    }

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.


message:
Remembering a colour

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.

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.


message:
How does use an arduino like a A/D converter for convert 3 analogue signal from 3 poteciometer to a raspberry?

I am developing a control system in my raspberry, but i have the problem that it doesn't have any analogue port, so if i use an arduino to convert de signal from analogue to digital and after send this signal into a I/o digital port from anduino to raspberry, thas is posible?

my plan was receive the analog signal in arduino and transforms here in a digital signal and after send it by Digital port to rasberry

body:
It is not clear what you mean by “digital port”. The simplest mean to
communicate from the Arduino to the Raspberry is to use the Arduino's
serial port, which gets into the Raspberry Pi through USB. Just like you
would do if you had a PC instead of the Raspberry:

```c++
/*
 * Continuously report the analog readings on pins A0 through A2.
 */

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

void loop() {
    Serial.print("0 "); Serial.println(analogRead(A0));
    Serial.print("1 "); Serial.println(analogRead(A1));
    Serial.print("2 "); Serial.println(analogRead(A2));
}
```

This program will continuously output a text stream like this:

    0 145
    1 220
    2 865
    0 142
    1 223
    ...

where the first column is the analog channel number and the second
column is the ADC value. How you handle this stream on the Raspberry
side is up to you.


message:
Measure position of gear with arduino

So, my plan is to be able to turn a motor, with a gear on the end, for a certain amount of gear teeth then stop it. I can’t find a data sheet for the motor but it is very fast, brushed and DC. I was thinking putting something like [this][1] below the gear so when a tooth goes past, it turns on and off. Like I said before the motor is very fast (faster then being able to see the teeth as it spins)  and I don’t think the arduino will be able to read that kind of speed with digital read, I may be wrong. Any suggestions would be appreciated. Thanks.

EDIT:
The motor runs off 2 cell or three cell lipo which is 7.4-11.1v, it’s maximum current is 20 amps.

Edit: For anyone wondering how to use the sensor, the datasheet is [here][2] and it shows the positions of the collector, emitter, anode and cathode.

  [1]: https://uk.rs-online.com/mobile/p/products/1612156/?grossPrice=Y&cm_mmc=UK-PPC-DS3A-_-google-_-3_UK_EN_Reflective Optical Sensors_Vishay_Exact-_-Vishay - Reflective Optical Sensors - 1612156-_-vishay vcnt2020&matchtype=e&kwd-383452625495&s_kwcid=AL!7457!3!237533593421!e!!g!!vishay vcnt2020&gclsrc=aw.ds&&gclid=Cj0KCQjw6IfoBRCiARIsAF6q06seXlEYZ00YPNVyDWBQ2_7uM_WEoWEcBqtlp74rwz92QOQBfZsglC8aAkTpEALw_wcB
  [2]: http://www.vishay.com/docs/84285/vcnt2020.pdf

body:
If memory serves, the clock speed of an arduino Uno is 16Mhz. Some are faster, some much faster and a few are slower.

Most assembler instructions take around 1-3 clock cycles. A few take more. Assuming an average of 3 ticks per instruction, that translates to executing over 5 million instructions per second.

So, unless your motor is approaching supersonic speeds, the arduino should be able to "keep up" with polling your motor's sensor in your `loop()` function.

If you are doing a few other things in your loop, you might consider using an interrupt to trigger some code when the motor "activates" the sensor. In this case you will unlikely need to worry about the speed of the CPU at all. When using an interrupt, you do not need to worry about polling the state of your sensor inside the `loop()` function.

Always remember to keep the code in your interrupt service routine as short and fast as possible. In this case, probably you would just turn off the motor and return when the interrupt is triggered.

Having said all of that, you will still need to do some work to get the most appropriate implementation as only you know what other things you need to take into account at this time.

One other thing to note is that a single high level instruction will normally equate to more than one assembler instruction. Even a simple statement like `int x = 1000;` will be more than one assembler instruction and thus take more than 1 clock tick. However, if memory serves, the individual instructions generate to execute `x = 1000` will all take just one clock tick.

Others will vary the amount of instructions that are generated to execute them. For example
`
float x = 1.0;
x = x + 2.0;
`

will likely take more instructions to execute than it's integer counterpart:
`
int x = 1;
x = x + 2
`

I hope this helps and enables you to try controlling your motor via Arduino. If not, you can always ask a more specific question later.


message:
Change From One State Machine To Another

I have a project where I need to state from leds turning on and off to another one that will have all the leds turned on and send data and I was wondering how should I do that, this the code I have:

    #include <CapacitiveSensor.h>

    CapacitiveSensor cs_11_10 = CapacitiveSensor(11,10);

    int state_s1 = 0;
    int state_s2 = 0;
    int state_s3 = 0;
    int state_s4 = 0;
    int state_prev_s1 =0;
    int pin_s1 = 12;
    int val_s1 = 0;

    const unsigned int ledPins[]={2,3,4,5,6,7,8,9};
    const unsigned int lenledPins=9;

    unsigned long t_s1 = 0;
    unsigned long t_0_s1 = 0;
    unsigned long t_s3 = 0;
    unsigned long t_0_s3 = 0;
    unsigned long t_0_s4 = 0;
    unsigned long t_s4 = 0;
    unsigned long t_s2_4 = 0;
    unsigned long tiempo = 250;

    unsigned long bounce_delay_s1 = 5;

    long total = 0;

    void setup()
    {
      pinMode(pin_s1, INPUT_PULLUP);
      Serial.begin(9600);

      for(int i=0; i<(9); i++)
      {
        pinMode(ledPins[i], OUTPUT);
      }

      cs_11_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
      Serial.begin(9600);

    }

    void loop()
    {

      MBoton();          //MAQUINA DE ESTADO

     MaquinaGeneral();

      if(state_s2 == 1)
      {
        led();
      }

      if(state_s1 != state_prev_s1)
      {
        Serial.print("state =");
        Serial.println(state_s3);
      }

      if(state_s4 == 6)
      {
        for(int i=0; i<lenledPins; i++)
        {
          digitalWrite(ledPins[i],HIGH);
        }
      }

      Serial.print("");

    }

    void MaquinaGeneral()
    {
      switch(state_s2)
      {
        case 0:
        if(state_s1 == 4)
        {
          state_s2 = 1;
        }
        break;

        case 1:

        break;
      }
    }

    void MBoton()
    {
      state_prev_s1 = state_s1;
      switch(state_s1)
      {
        case 0:         //RESET
        state_s1 = 1;
        break;

        case 1:        //START
        val_s1 = digitalRead(pin_s1);
        if(val_s1 == LOW)
         {
          state_s1 = 2;
         }
        break;

        case 2:         // GO!
        t_0_s1 = millis();
        state_s1 = 3;
        break;

        case 3:         //WAIT
        t_s1 = millis();
        if(t_s1 - t_0_s1 >= bounce_delay_s1)
        {
          state_s1 = 5;
        }
        break;

        case 5:         //ARMED
        val_s1 = digitalRead(pin_s1);
        if(val_s1 == HIGH)
         {
          state_s1 = 4;
         }
        break;

        case 4:       //TRIGGERED
        state_s1 = 0;
        break;

      }
    }

    void led()
    {

      switch(state_s3)
      {
        case 0:         //OFF
        for(int i=0; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],LOW);
        }
        for(int i=1; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],HIGH);
        }

        t_0_s3 = millis();
        state_s3 = 1;
        break;

        case 1:         //WAIT
        t_s3 = millis();
        if(t_s3 - t_0_s3 >= tiempo)
        {
          state_s3 = 2;
        }
        break;

        case 2:         // ON
         for(int i=0; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],HIGH);
        }

         for(int i=1; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],LOW);
        }

        t_0_s3 = millis();
        state_s3 = 3;
        break;

        case 3:         //WAIT
        t_s3 = millis();
        if(t_s3 - t_0_s3 >= tiempo)
        {
         state_s3 = 0;
        }
        break;

      }

      }

    void Capacitor()
     {

      switch(state_s4)
      {

        case 0:         //RESET
        state_s4 = 1;
        break;

        case 1:        //START
        total = cs_11_10.capacitiveSensor(10);
        if(total >= 1000)
         {
          state_s4 = 2;
         }
        break;

        case 2:         // GO!
        t_0_s4 = millis();
        state_s4 = 3;
        break;

        case 3:         //WAIT
        total = cs_11_10.capacitiveSensor(10);
        if(total < 1000)
         {
          state_s4 = 0;
         }

        t_s4 = millis();

        if(t_s4 - t_0_s4 >= 2000)
        {
          state_s4 = 5;
        }

        break;

        case 5:         //ARMED & WAIT
        t_s2_4 = millis();
        total = cs_11_10.capacitiveSensor(10);
        if(total < 1000)
         {
          state_s4 = 4;
         }

         if(t_s2_4-t_s4 >= 1000)
         {
          state_s4= 6;
         }
        break;

        case 4:       //TRIGGERED
        state_s4 = 0;
        break;

        case 6:     // ARMED 2
        Serial.println("Entro al estado 6");
        total = cs_11_10.capacitiveSensor(10);
        break;

    }
    }

body:
If you think you need two finite state machines, where only one of them
is running at any given time, then it is trivial to combine them
together: draw them side by side, and add the required transitions
between them. The set of states of the combined FSM will be the union of
the states of the initial FSMs. For example, if you have:

* FSM 1 states: `STATE_A`, `STATE_B`, `STATE_C`
* FSM 2 stages: `STATE_D`, `STATE_E`
* global states: `FSM_1_RUNNING`, `FSM_2_RUNNING`

Then the combined FSM will have the states `STATE_A`, `STATE_B`,
`STATE_C`, `STATE_D` and `STATE_E`, and all the transitions of both
initial FSMs.


body:
Similar to what others have commented, this is not the best implementation of a Finite State Machine (FSM). You should establish clear states and define what happens during all transitions of your system.

Follow Edgar's advice on using enumerators for your states.

Nick Gammon's guide will surely be of great help: https://www.gammon.com.au/statemachine


message:
Sending sine wave from MATLAB and reading on Arduino Uno

I am working on timing issues associated with sampling data at high rates and storing it on an SD card (ADC delays, clock drifts and file I/O time). For this experiment, I thought of sending a sinusoidal wave to an analog pin on the Arduino Uno, and have the board read the samples. Can I eliminate the need for a function generator and instead use the Matlab Support Package for Arduino to send the sinusoid to the Arduino? (I guess this would mean two programs simultaneously, a Matlab program for generation of a sinusoid and an Arduino sketch for reading and writing.)
I'm new to Matlab, so any help would be greatly appreciated.

body:
No, you can't. The Arduino Uno has no analog outputs to start with and,
as you guessed, it cannot run two programs at the same time.

Maybe you should search for a solution of the _initial_ problem instead.
You should be aware that you cannot get consistent timings with
`analogRead()`. You will have to read the datasheet of the ATmega328p,
especially the section dedicated to the ADC. Then you will configure the
ADC yourself, at the register level. It has a feature called
“auto-trigger” which is intended to provide perfectly consistent
timings. This is what you are looking for.


message:
Arduino simple resistors in series

Silly question but how would a circuit be set up with Arduino where two different resistors are in series but one has an unknown value (i.e. is just a piece of metal for example) and so how would we be able to find the current through each, collage through each and thus find the value of the resistance of the unknown wire.

body:
Just a math exercise really.

Say you had a 5V source, two Resistors R1 and R2, and an Arduino.
5V - R1 - R2 - Gnd, with R1/R2 junction feeding the Arduino.
R1 is unknown.

Vout is what the Arduino sees. Vout = 5VxR2/(R1+R2)
Vout (R1+R2) = 5VxR2
R1+R2 = 5VxR2/Vout
R1 = 5VxR2/Vout - R2

Vout = ~ 0.00488mV x Analog In reading. (5V/1024)
If you select R2 of say 5K ohm, and you determine Vout to be 3V (analogRead returns 615), then you can calculate R1:
(5V x 5000)/3V- 5000 = 3333 ohm.

Checking with Vout = 5VxR2/(R1+R2), 5V x 5000/(3333 + 5000) = 3.000V


body:
While [CrossRoads' answer](https://arduino.stackexchange.com/a/66288/17196) got the math sorted out that is likely not the kind of measurement you are aiming for if the unknown resistor has a rather low resistance (*i.e. is just a piece of metal*). Assume the same circuit: 5V - R1 - R2 - GND.

Consider R1 to be a strand of copper wire of ribbon cable, AWG 26, i.e. with a diameter of 0.4 mm (0.016 inch) and a cross section of 0.13 mm², and a length of 3 inches (7.62 mm), being that "piece of metal". Its resistance will be 0.001 Ohms. To have any meaningful readings you'd want to have the other resistor (R2) in the same range otherwise the output voltage of the voltage divider will just be close to VCC (or GND if R1 and R2 are reversed). So assuming R2 to be 0.001 Ohms too, the total resistance of both resistors in series is therefore 0.002 Ohms. Connecting these to a 5V power supply (i.e. a voltage source) we find using Ohm's Law a current of 2500 A - which of course an ordinary Arduino wall plug will not provide. The power supply will either limit the current or its output voltage will be reduced or both - either way not a desirable situation in a measurement setup. Another approach of direct measurement is to apply a known current to the unknown resistor and measure the voltage across it. For any reasonable current that voltage will be rather small (i.e. 1 mV at 1 A) and would need to be amplified before being measured with an Arduino's ADC.

In short, measuring low resistances is difficult and might require a dedicated setup such as a [Wheatstone bridge](https://en.wikipedia.org/wiki/Wheatstone_bridge). Best answers are likely to be found at [Electrical Engineering](https://electronics.stackexchange.com) but need additional input on measurement range and required accuracy.


message:
How is better to store html / java script / in code or in flash on esp32

I have an esp32 which is running a web page together with a java script and using socket I update some values on the web page. I am doing this very fast (like each 50ms). Now I am serving all the html/java script code stored in a string variable but I am wondering which is the best? To store this html in spiff or in code ? and why?
Thank you very much

body:
It depends on your definition of "better".

Directly inlined in your code will probably be faster - it will be subject to the caching mechanisms of the execution pipeline, whereas SPIFFS will have to make specific SPI calls to read the data from the flash chip at the time it's required.  However SPIFFS will be easier to maintain since you are just working with files.

I would probably choose SPIFFS for larger files like graphics or big chunks of Javascript. Things that the client can download once and then cache (as long as your web server supports that kind of functionality - not sure what facilities the default ESP32 web server code has). The rest, the more dynamic things that change often, have as inline string literals.


body:
Best is to store static files in SPIFFS and serve them with Expires header set, to let the browser cache the html, css, js files and pictures files.

How to build the Expires header:

    unsigned long expires = now() + SECS_PER_YEAR;
    bp.printf(F("Expires: %s, "), dayShortStr(weekday(expires))); // two printfs because ShortStr functions share the buffer
    bp.printf(F("%d %s %d 00:00:00 GMT"), day(expires), monthShortStr(month(expires)), year(expires));

And use AJAX method to show data on the page. Make the request with `XMLHttpRequest` object:

    function getData(cmd) {
      var xhr = new XMLHttpRequest();
      xhr.onerror = function(e) {
        alert(xhr.status + " " + xhr.statusText);
      }
      xhr.onload = function(e) {
        showValues(xhr.responseText);
      };
      xhr.open("GET", "http://" + host + ":" + restPort + "/" + cmd, true);
      xhr.send();
    }

`showValues` would be your function to fill the data into page

In ESP32 build the response as JSON for simple handling of the data in JavaScript.

Here is [the WebServer in my project][1]. It uses the basic Arduino Server class, not the esp WebServer. It has `#ifdefs` for SD or SPIFFS. The static files of my project including the js file are [here][2].

  [1]: https://github.com/jandrassy/Regulator/blob/b6ef120c6f8963979268d8d17b56e5632336f317/Regulator/WebServer.ino#L22
  [2]: https://github.com/jandrassy/Regulator/tree/master/Regulator/data