message:
conflict with different i2c devices

I am trying to communicate with two i2c components using an arduino nano - some [ADS1115s][1] and some [i2c flow sensors][3] each connected to a different [i2c multiplexer][2], but they seem to be conflicting.

Some of the ADS1115s are 0x49 addresses, the same as all the flow sensors. The full code works, including constructing and initialising the ads1115s, but if I then try to read from them also, I don't get almost any data from the flow sensors (they just read 0 or close to when they should be reading around 8192 for zero flowrate). Any help or suggestions much appreciated!

I've put the full code at the bottom as its quite long and I keep changing it anyway but the important parts are here:

ADS1115:

    Adafruit_ADS1115();  //Construct an instance of an ADS1115 with the default address (0x48)
    ads1115.begin();  // Initialize ads1115
    int16_t readADC_Differential_0_1(void);  //Perform a differential analog to digital conversion on the voltage between channels 0 and 1.

tca9548a multiplexer:

    #define TCAADDR 0x70

    void tcaselect(uint8_t i) {
      if (i > 7) return;

      Wire.beginTransmission(TCAADDR);
      Wire.write(1 << i);
      Wire.endTransmission();
    }

    tcaselect(i);

Zephyr flow sensors:

    void getflows (int sensor, float range, float flowreading) {
    Wire.requestFrom(0x49, 2);
    while (Wire.available())   // slave may send less than requested
      {
        int flowdata = Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowdata = flowdata << 8;
        flowdata |= Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowreading = range * ((flowdata / 16384.0) - 0.5) / 0.4;
        //Serial.print("sensor 3 flow = "); Serial.println(flow3);
        //Serial.println();         // print the character
        //Serial.println();
      }
      delay(20);
}

The full code:

    #include <ModbusRtu.h>
    #include <Wire.h>
    #include <Adafruit_ADS1015.h>
    #include <SPI.h>
    #include <PID_v1.h>
    #include <math.h>

    //modbus
    #define ID          1
    #define TXEN        2

    //valve TTL and DAC CS pins - nos correspond to valve driver numberings in rig box
    //Current connections - O2high = 1 = A, CO2 = 2 = B, O2low = 3 = C
    #define ATTL       5
    #define CTTL       4
    #define BTTL       3

    #define BCS         7
    #define CCS         8
    #define ACS         9

    #define tempfreq    5
    #define tempnum     3
    ///////////////////////////////////////////
    //Sensor ranges - USER DEFINED
    float DACrange = 3500.0; //ml/min

    int POutrange = 2000; //mbar abs
    int PInrange = 2000; //mbar abs
    ///////////////////////////////////////////

    //ADC multiplexer
    #define TCAADDR      0x70
    #define TCA2ADDR      0x77

    //Input resistor values
    float         T1R2  =  2320.0;
    float         FPR1  =  3090.0;
    float         FPR2  =  12010.0;

    //max variation from setpoint before PID cycle
    int maxdif    =  5;
    //max variation from setpoint at end of PID cycle
    int PIDdif    =  1;

    ///////////////////////////////////////////
    //MATHS
    //scale factor
    long FPscale = 10000000;
    long flowscale = 10000000;
    //vrefs - with scale factors applied
    float vref   = 2.5; //tscaled
    float Tref   = 1.0; //tscaled
    long FPref  = 20000000; //FPscaled
    //divisions - integrated to sensor range in long format for calculations
    float FPdiv = (FPR1 + FPR2) / FPR2;
    int Vmax = 5;

    int Poutfac = (int)((POutrange / Vmax) * FPdiv);
    int Pinfac = (int)((PInrange / Vmax) * FPdiv);

    //ADC mv/bit
    float Tbit = 0.00003125;
    long FPbit = 625; //- with scale factor of 10,000,000

    //temp sensor steinhart constants
    double sA = 0.001462146;
    double sB = 0.0002393355;
    double sC = 0.0000000963049;

    //declare holding constants
    int16_t hT1 = 0;
    int16_t hT2 = 0;
    int16_t hT3 = 0;
    int16_t hT4 = 0;
    int16_t hT5 = 0;
    int16_t hT6 = 0;
    int16_t hT7 = 0;
    int16_t hT8 = 0;

    int16_t hFP1 = 0;
    int16_t hFP2 = 0;
    int16_t hFP3 = 0;
    int16_t hFP4 = 0;
    int16_t hFP5 = 0;
    int16_t hFP6 = 0;
    int16_t hFP7 = 0;
    int16_t hFP8 = 0;

    //intermediates
    int i = 0;
    int j = 0;
    int b[3];
    int loopnum = tempfreq;
    float tres = 0.0;
    double treslog = 0.0;
    long lconv = 0;
    int16_t O2dif = 0;
    int16_t CO2dif = 0;
    int16_t N2dif = 0;
    int16_t gasdif = 0;
    int gasreading = 0;
    int hFP = 0;
    uint16_t val = 0;
    bool truePID;
    bool trueAPID = false;
    bool trueBPID = false;
    bool trueCPID = false;
    int (*gasreadfunc)();

    int flowdata = 0;
    float flow3 = 0.0;
    float flow2 = 0.0;
    float flow4 = 0.0;
    float flow5 = 0.0;
    long reading = 0;

    uint16_t Setpt;
    int CS;
    int TTL;

    //initialise nested functions
    //void eachPID(int16_t (*)(), int16_t, int, bool);

    enum
    {
      Error1,    //CHANNEL 0  //0
      Error2,    //CHANNEL 1
      FP2a,      //CHANNEL 2  //1
      FP2b,      //CHANNEL 3
      T1a,       //CHANNEL 4  //2
      T1b,       //CHANNEL 5
      T2a,       //CHANNEL 6  //3
      T2b,       //CHANNEL 7
      T3a,       //CHANNEL 8  //4
      T3b,       //CHANNEL 9
      T4a,       //CHANNEL 10 //5
      T4b,       //CHANNEL 11
      Flow2a,    //CHANNEL 12 //6
      Flow2b,    //CHANNEL 13
      Flow3a,    //CHANNEL 14 //7
      Flow3b,    //CHANNEL 15
      Flow4a,    //CHANNEL 16 //8
      Flow4b,    //CHANNEL 17
      Flow5a,    //CHANNEL 18 //9
      Flow5b,    //CHANNEL 19
      A_set,     //CHANNEL 20
      B_set,     //CHANNEL 21
      C_set,     //CHANNEL 22
      HOLDING_REGS_SIZE
    };

    unsigned int holdingRegs[HOLDING_REGS_SIZE];

    /**
        Modbus object declaration
        u8id : node id = 0 for master, = 1..247 for slave
        u8serno : serial port (use 0 for Serial)
        u8txenpin : 0 for RS-232 and USB-FTDI
                     or any pin number > 1 for RS-485
    */
    Modbus slave(1, 0, TXEN); // this is slave @1 and RS-485

    //Construct ADCs at addresses
    Adafruit_ADS1115 adcOne(0x48);
    Adafruit_ADS1115 adcTwo(0x49);
    Adafruit_ADS1115 adcThree(0x4B);
    Adafruit_ADS1115 adcFour(0x4A);

    // SPI - set up the speed, data order and data mode
    SPISettings settings(4000000, MSBFIRST, SPI_MODE0);

    //PID
    //Define Variables we'll be connecting to
    double Output, Setpoint, Input;

    //Define the aggressive and conservative Tuning Parameters
    double aggKp = 4, aggKi = 0.2, aggKd = 1;
    double consKp = 1, consKi = 0.05, consKd = 0.25;

    //Specify the links and initial tuning parameters
    PID myPID(&Input, &Output, &Setpoint, aggKp, aggKi, aggKd, DIRECT);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    void tcaselect(uint8_t i, int address) {
      if (i > 7) return;

      Wire.beginTransmission(address);
      Wire.write(1 << i);
      Wire.endTransmission();
    }

    void setup() {
      ///////////////////////////////////////////////////////////////////////////////////////////////
      //DAC
      pinMode (BCS, OUTPUT);
      digitalWrite(BCS, HIGH);
      pinMode (CCS, OUTPUT);
      digitalWrite(CCS, HIGH);
      pinMode (ACS, OUTPUT);
      digitalWrite(ACS, HIGH);

      pinMode (ATTL, OUTPUT);
      digitalWrite(ATTL, LOW);
      pinMode (CTTL, OUTPUT);
      digitalWrite(CTTL, LOW);
      pinMode (BTTL, OUTPUT);
      digitalWrite(BTTL, LOW);
      ///////////////////////////////////////////////////////////////////////////////////////////////
      //ADC
      adcOne.begin();
      adcTwo.begin();
      adcThree.begin();
      adcFour.begin();

      // 2/3x gain +/- 6.144V  1 bit = 0.1875mV (default)
      // ads1015.setGain(GAIN_ONE);     // 1x gain   +/- 4.096V  1 bit = 0.125mV
      // ads1015.setGain(GAIN_TWO);     // 2x gain   +/- 2.048V  1 bit = 0.0625mV
      // ads1015.setGain(GAIN_FOUR);    // 4x gain   +/- 1.024V  1 bit = 0.03125mV
      // ads1015.setGain(GAIN_EIGHT);   // 8x gain   +/- 0.512V  1 bit = 0.015625mV
      // ads1015.setGain(GAIN_SIXTEEN); // 16x gain  +/- 0.256V  1 bit = 0.0078125mV

      //////////////////////////////////////////////////////////////////////////////////////////////
      //Flow sensor serial number readouts
      getflows(2, 750.0, flow2);
      getflows(3, 400.0, flow3);
      getflows(4, 50.0, flow4);
      getflows(5, 400.0, flow5);

      //////////////////////////////////////////////////////////////////////////////////////////////
      //PID
      //initialize the variables we're linked to
      Input = 0;
      Setpoint = 0;

      //Define the aggressive and conservative Tuning Parameters
      float aggKp = 4, aggKi = 0.2, aggKd = 1;
      float consKp = 1, consKi = 0.05, consKd = 0.25;

      //turn the PID on
      myPID.SetMode(AUTOMATIC);
      //////////////////////////////////////////////////////////////////////////////////////////////
      // start modbus communication
      slave.begin(115200);

      // initialize SPI:
      SPI.begin();

      //Serial.begin(115200);
      gettemperatures();

      holdingRegs[Error2] = 0;
    }

    void loop() {
      //each tempfreq no of loops, it reads the temp sensors also
      loopnum++;
      if (loopnum > tempfreq) {
        gettemperatures();
        loopnum = 0;
      }

      holdingRegs[Error1] = 0;//set to 0 for normal operation, 65535 = PID control
      //Serial.print("Holding Regs Error1 "); Serial.print(holdingRegs[Error1]); Serial.print(", holdingRegs[Error2]"); Serial.println(holdingRegs[Error2]);

      //flow and pressure sensors
      tcaselect(0, TCAADDR);
      adcOne.setGain(GAIN_TWO);
      //adcTwo.setGain(GAIN_TWO);
      //adcThree.setGain(GAIN_TWO);
      //adcFour.setGain(GAIN_TWO);

      //hFP1 = adcOne.readADC_Differential_0_1();
      hFP2 = adcOne.readADC_Differential_2_3();
      //hFP3 = adcTwo.readADC_Differential_0_1();
      //hFP4 = adcTwo.readADC_Differential_2_3();
      //hFP5 = adcThree.readADC_Differential_0_1();
      //hFP6 = adcThree.readADC_Differential_2_3();
      //hFP7 = adcFour.readADC_Differential_0_1();
      //hFP8 = adcFour.readADC_Differential_2_3();

      //FPconv(hFP1, &holdingRegs[FP1a], &holdingRegs[FP1b], Pinfac);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      FPconv(hFP2, &holdingRegs[FP2a], &holdingRegs[FP2b], Poutfac);
      //Serial.print("hFP2: "); Serial.println(hFP2);
      //FPconv(hFP3, &holdingRegs[FP3a], &holdingRegs[FP3b], CO2fac);
      //Serial.print("hFP3: "); Serial.println(hFP3);
      //FPconv(hFP4, &holdingRegs[FP4a], &holdingRegs[FP4b], O2fac);
      //Serial.print("hFP4: "); Serial.println(hFP4);
      //FPconv(hFP5, &holdingRegs[FP5a], &holdingRegs[FP5b], Finfac);
      //Serial.print("hFP5: "); Serial.println(hFP5);
      //FPconv(hFP6, &holdingRegs[FP6a], &holdingRegs[FP6b], N2fac);
      //Serial.print("hFP6: "); Serial.println(hFP6);
      //FPconv(hFP7, &holdingRegs[FP7a], &holdingRegs[FP7b], Finfac);
      //Serial.print("hFP7: "); Serial.println(hFP7);
      //FPconv(hFP8, &holdingRegs[FP8a], &holdingRegs[FP8b], Finfac);
      //Serial.print("hFP8: "); Serial.println(hFP8);
      //Serial.println("");

      getflows(2, 750.0, flow2);
      getflows(3, 400.0, flow3);
      getflows(4, 50.0, flow4);
      getflows(5, 400.0, flow5);

      flowconvert();

      //modbus communication
      slave.poll( holdingRegs, HOLDING_REGS_SIZE );

      checkgasflow(1);
      checkgasflow(2);
      checkgasflow(3);

      //delay(1000);
    }

    void gasread(int gastoread) {
      switch (gastoread) {
        case 1: //O2high
          getflows(3, 400.0, flow3);
          gasreading = flow2;
          Setpt = A_set;
          CS = ACS;
          TTL = ATTL;
          truePID = trueAPID;
          //return gasreading;
          break;
        case 2: //CO2
          getflows(4, 50.0, flow4);
          Setpt = B_set;
          CS = BCS;
          TTL = BTTL;
          truePID = trueBPID;
          //return gasreading;
          break;
        case 3: //O2low
          getflows(5, 400.0, flow5);
          Setpt = C_set;
          CS = CCS;
          TTL = CTTL;
          truePID = trueCPID;
          //return gasreading;
          break;
      }
    }

    void checkgasflow(int gastoread) {
      gasread(gastoread);
      Input = (double)gasreading;
      Setpoint = (double)Setpt;
      gasdif = Input - Setpoint;
      if (abs(gasdif) < PIDdif) {
        truePID = 1;
        return;
      }
      else {
        GasPID();
      }
    }

    void GasPID() {
      holdingRegs[Error1] = 65535; //set to 0 for normal operation, 65535 = PID control

      //modbus communication
      slave.poll( holdingRegs, HOLDING_REGS_SIZE );

      do {
        eachPID(1);
        eachPID(2);
        eachPID(3);
      } while (!trueAPID || !trueBPID || !trueCPID);

      holdingRegs[Error1] = 0;
    }

    void eachPID(int gastoread) {
      gasread(gastoread);
      Input = (double)gasreading;
      Setpoint = (double)Setpt;
      gasdif = Input - Setpoint;
      if (abs(gasdif) < PIDdif) {
        truePID = 1;
        return;
      }
      else if (abs(gasdif) < 10)
      { //we're close to setpoint, use conservative tuning parameters
        truePID = 0;
        myPID.SetTunings(consKp, consKi, consKd);
      }
      else
      {
        //we're far from setpoint, use aggressive tuning parameters
        truePID = 0;
        myPID.SetTunings(aggKp, aggKi, aggKd);
      }
      myPID.Compute();
      val = (uint16_t)Output;
      DACspi(CS, val, TTL);
    }

    void FPconv (int16_t FPin, uint16_t *hRega, uint16_t *hRegb, int FPfac) {
      lconv = (FPfac * (FPref + (long)(FPbit * FPin)));
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
    }

    void Flowconv (float FPin, uint16_t *hRega, uint16_t *hRegb) {
      lconv = (long)(FPin*flowscale);
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
    }

    void Tconv (int16_t Tin, uint16_t *hRega, uint16_t *hRegb) {
      tres = T1R2 * ((vref / (Tref + (Tbit * Tin))) - 1.0);
      treslog = log(tres);
      lconv = lround(10000000.0 * ((1.0 / (sA + sB * treslog + sC * (pow(treslog, 3.0)))) - 273.15));
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
    }

    void DACspi(uint16_t CS, uint16_t val, int TTL) {
      digitalWrite(CS, LOW);
      if (val > 0) {
        digitalWrite(TTL, HIGH);
      }
      else {
        digitalWrite(TTL, LOW);
      }
      SPI.transfer16(val);
      digitalWrite(CS, HIGH);
    }

    void gettemperatures() {
      tcaselect(6, TCAADDR);
      adcOne.setGain(GAIN_FOUR);
      adcTwo.setGain(GAIN_FOUR);
      adcThree.setGain(GAIN_FOUR);
      adcFour.setGain(GAIN_FOUR);
      //temp sensors - 2 consecutive readings to allow pins to warm up first
      for (i = 0; i < tempnum; i++) {
        hT1 = adcOne.readADC_Differential_0_1();
      }
      for (i = 0; i < tempnum; i++) {
        hT2 = adcOne.readADC_Differential_2_3();;
      }
      for (i = 0; i < tempnum; i++) {
        hT3 = adcTwo.readADC_Differential_0_1();
      }
      for (i = 0; i < tempnum; i++) {
        hT4 = adcTwo.readADC_Differential_2_3();
      }
      //for (i = 0; i < tempnum; i++) {
      //  hT5 = adcThree.readADC_Differential_0_1();
     // }
      //for (i = 0; i < tempnum; i++) {
      //  hT6 = adcThree.readADC_Differential_2_3();
      //}
      //for (i = 0; i < tempnum; i++) {
      //  hT7 = adcFour.readADC_Differential_0_1();
      //}
      //for (i = 0; i < tempnum; i++) {
      //  hT8 = adcFour.readADC_Differential_2_3();
      //}

      Tconv(hT1, &holdingRegs[T1a], &holdingRegs[T1b]);
      //Serial.print("hT1: "); Serial.println(hT1);
      Tconv(hT2, &holdingRegs[T2a], &holdingRegs[T2b]);
      //Serial.print("hT2: "); Serial.println(hT2);
      Tconv(hT3, &holdingRegs[T3a], &holdingRegs[T3b]);
      //Serial.print("hT3: "); Serial.println(hT3);
      Tconv(hT4, &holdingRegs[T4a], &holdingRegs[T4b]);
      //Serial.print("hT4: "); Serial.println(hT4);
      //Tconv(hT5, &holdingRegs[T5a], &holdingRegs[T5b]);
      //Serial.print("hT5: "); Serial.println(hT5);
      //Tconv(hT6, &holdingRegs[T6a], &holdingRegs[T6b]);
      //Serial.print("hT6: "); Serial.println(hT6);
      //Tconv(hT7, &holdingRegs[T7a], &holdingRegs[T7b]);
      //Serial.print("hT7: "); Serial.println(hT7);
      //Tconv(hT8, &holdingRegs[T8a], &holdingRegs[T8b]);
      //Serial.print("hT8: "); Serial.println(hT8);
    }

    void getflows (int sensor, float range, float flowreading) {
      tcaselect(sensor, TCA2ADDR);
      Wire.requestFrom(0x49, 2);

      while (Wire.available())   // slave may send less than requested
      {
        int flowdata = Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowdata = flowdata << 8;
        flowdata |= Wire.read();    // receive a byte as character
        //Serial.println(flowdata);
        flowreading = range * ((flowdata / 16384.0) - 0.5) / 0.4;
        //Serial.print("sensor 3 flow = "); Serial.println(flow3);
        //Serial.println();         // print the character
        //Serial.println();
      }
      delay(20);
    }

    void flowconvert (){

      Flowconv(flow2, &holdingRegs[Flow2a], &holdingRegs[Flow2b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      Flowconv(flow3, &holdingRegs[Flow3a], &holdingRegs[Flow3b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      Flowconv(flow4, &holdingRegs[Flow4a], &holdingRegs[Flow4b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
      Flowconv(flow5, &holdingRegs[Flow5a], &holdingRegs[Flow5b]);
      //Serial.print("hFP1: "); Serial.println(hFP1);
    }

    /*void FPconv (int16_t FPin, uint16_t *hRega, uint16_t *hRegb, int FPfac, long FPcal) {
      lconv = (FPfac * (FPcal + FPref + (long)(FPbit * FPin)));
      memcpy((uint8_t *)hRega, (uint8_t *)&lconv, 2);
      memcpy((uint8_t *)hRegb, (uint8_t *)&lconv + 2, 2);
      }*/

    /*void GasPID() {
      holdingRegs[Error1] = 65535; //set to 0 for normal operation, 65535 = PID control

      //modbus communication
      slave.poll( holdingRegs, HOLDING_REGS_SIZE );

      tcaselect(0);

      do {
        eachPID(O2read, O2_set, BCS, trueAPID);
        eachPID(CO2read, CO2_set, CCS, trueBPID);
        eachPID(N2read, N2_set, ACS, trueCPID);
      } while (!trueAPID || !trueBPID || !trueCPID);

      trueAPID = !trueAPID;
      trueBPID = !trueBPID;
      trueCPID = !trueCPID;
      }*/

    /*
      void eachPID(int16_t gasReadfunc(), int16_t Setpt, int CS, bool truePID, int TTL) {
      Setpoint = (double)Setpt;

      for (i = 0; i < 3; i++) {
        hFP = (*gasreadfunc)();
      }
      Input = (double)hFP;
      gasdif = Input - Setpoint;
      if (abs(gasdif) < PIDdif) {
        truePID = 1;
        return;
      }
      else if (abs(gasdif) < 10)
      { //we're close to setpoint, use conservative tuning parameters
        myPID.SetTunings(consKp, consKi, consKd);
      }
      else
      {
        //we're far from setpoint, use aggressive tuning parameters
        myPID.SetTunings(aggKp, aggKi, aggKd);
      }
      myPID.Compute();
      val = (uint16_t)Output;
      DACspi(CS, val, TTL);
      }*/

    /*//Connections
      int16_t O2read() {
      gasread = adcOne.readADC_Differential_0_1();
      return gasread;
      }
      int16_t CO2read() {
      gasread = adcOne.readADC_Differential_2_3();
      return gasread;
      }
      int16_t N2read() {
      gasread = adcTwo.readADC_Differential_0_1();
      return gasread;
      }*/

    /*// SPI communication with DAC
      DACspi(BCS, holdingRegs[CO2_set], BTTL); //CO2 controller
      DACspi(CCS, holdingRegs[N2_set], CTTL); //N2 controller
      DACspi(ACS, holdingRegs[O2_set], ATTL); //O2 controller*/

  [1]: https://www.adafruit.com/product/1085
  [2]: https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout/wiring-and-test
  [3]: https://www.mouser.co.uk/datasheet/2/187/honeywell-sensing-airflow-zephyr-haf-series-digita-740409.pdf

body: I had not realised that once opened, the tca9548a channels stay open until either POR or the RESET pin is brought low. Hence when using two multiplexers I just needed to use an extra wire to the RESET pin on each from the nano.


sender: user

sender: assistant

body:
You pass `flowreading` to `void getflows (int sensor, float range, float flowreading)` as a value and therefore changing `flowreading` has no effect on the variable you pass to that function.

Instead, you need to do `void getflows (int sensor, float range, float *flowreading)`.


message:
Arduino Nano 3.0 CH340G clone cannot upload sketch from Arduino IDE

I connected my brand new Arduino Nano 3.0 clone with CH340G and installed the drivers. It detects in Device Manager as USB-SERIAL CH340 (COM6). Under the Tools menu, i selected the correct board, the processor set to ATmega328P and the COM port. I couldn't upload my sketch so i tried uploading an example Blink sketch from Arduino IDE. The uploading is stuck. I keep waiting and nothing happens. I have read somewhere else that i should enable verbose output for compilation and upload, which i did and here is the output for trying to upload the basic Blink sketch.

    Arduino: 1.8.9 (Windows 7), Board: "Arduino Nano, ATmega328P"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\admin\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\admin\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\admin\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path C:\Users\admin\AppData\Local\Temp\arduino_build_747566 -warnings=none -build-cache C:\Users\admin\AppData\Local\Temp\arduino_cache_890158 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avrdude.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.arduinoOTA.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\admin\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\admin\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\admin\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path C:\Users\admin\AppData\Local\Temp\arduino_build_747566 -warnings=none -build-cache C:\Users\admin\AppData\Local\Temp\arduino_cache_890158 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\5.4.0-atmel3.6.1-arduino2 -prefs=runtime.tools.avrdude.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14 -prefs=runtime.tools.arduinoOTA.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.2.1 -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
    Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp" -o nul
    Generating function prototypes...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp" -o "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    "C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp" -o "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using precompiled core: C:\Users\admin\AppData\Local\Temp\arduino_cache_890158\core\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a
    Linking everything together...
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566\\sketch\\Blink.ino.cpp.o" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/..\\arduino_cache_890158\\core\\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566" -lm
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.eep"
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf" "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.hex"
    "C:\\Users\\admin\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\5.4.0-atmel3.6.1-arduino2/bin/avr-size" -A "C:\\Users\\admin\\AppData\\Local\\Temp\\arduino_build_747566/Blink.ino.elf"
    Sketch uses 930 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -CC:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b115200 -D -Uflash:w:C:\Users\admin\AppData\Local\Temp\arduino_build_747566/Blink.ino.hex:i
    An error occurred while uploading the sketch

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\admin\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf"

             Using Port                    : COM6
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd8
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd8

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body:
You normally just have to press 'reset' on the board button 1 sec before clicking 'Upload'.

I had to do this with cheap Nano clone.


message:
How I can connect module GSM SIM800L?

I bought a GSM module, and I want to connect it with Arduino but I have a problem.

I linked GSM SIM800L with regular LM2596 12 V 2 VA I changed tension to 5 V, So far the GSM is working but if I connect TX_ARDUINO with RX_GSM the module enters in the loop of the restart.

The picture explains the montage.

[![Fritzing of LM2596, SIM800L and Arduino Uno][1]][1]

  [1]: https://i.stack.imgur.com/QGeI6.png "Fritzing of LM2596, SIM800L and Arduino Uno"

body:
[![Arduino Sim800l][1]][1]

Follow [this tutorial][2] on how to connect your Sim800l with Arduino.

  [1]: https://i.stack.imgur.com/tWSY5.jpg
  [2]: https://www.teachmemicro.com/arduino-sim800l-tutorial/


message:
SD.h causing constant reboot

I have a nice sketch running which monitors a few things and displays output on an OLED display. Now I want to save the data to an SD card, but with or without the card module attached I'm getting constant reboots when I add 1 single line of code:

    #include <SD.h>

Any idea what may be happening?

body:
The following libraries are probably used:

- SD Card, using a buffer of 512 bytes (see also the comment of DataFiddler below).
- SSD1306 OLED library, using a buffer of 1,024 bytes
- Serial, using a buffer of 128 bytes (64 for RX, 64 for TX, see comment of Majenko below)

Since there is only 2,048 bytes of SRAM in an Arduino, this leaves 384 bytes. If you actually READ a file you are already above the maximum.

Your own global variables also will consume a considerable amount of SRAM.

Than, if you execute your sketch, parameters and local variables are stored on the stack (in SRAM), so even if your program starts well, it might/will run in problems when calling functions.


message:
Arduino as ISP - program is being uploaded on Arduino, not breadboard

I am following [this tutorial][1], and have wired Arduino using this diagram:

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

This is what it looks like:

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

These options are selected in Arduino IDE:

[![enter image description here][4]][4]

This is the program I'm uploading:

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(9, OUTPUT);
      digitalWrite(9, HIGH);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

When I upload it, it's uploaded on the Atmega on arduino board, not the one on breadboard. Both chips are ATMEGA328P.

I also tried to put 10μF capacitor between GND and RESET pins of the arduino board, which led to following errors:

    Sketch uses 936 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\Jakub\AppData\Local\Temp\arduino_build_319338/BlinkTestAtmega.ino.hex:i

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x12
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Note that I have a homemade ATTINY programmer shield for this arduino board and it works without problems.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
  [2]: https://i.stack.imgur.com/sckRD.png
  [3]: https://i.stack.imgur.com/JTp6O.jpg
  [4]: https://i.stack.imgur.com/GUJwX.png

body:
Use the "Upload using programmer" in Sketch menu to upload a sketch over ISP

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

warning, it deletes the bootloader

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


message:
Adafruit Feather 32u4 BLE compatible with Software SPI?

Let me preface by saying that I am not super experienced with electronics. I have an Adafruit Feather 32u4 that is using Hardware SPI to communicate over Bluetooth. Unfortunately, I'm also hoping to use the SD library, which also uses Hardware SPI. I am hoping to change the board to use Software SPI instead, so that the two may work together.

The Bluefruit code by default has the following commented out:

    /* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
    Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
                                 BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
                                 BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

Which leads me to believe I could use SW SPI but simply uncommenting this and commenting out the HW SPI doesn't seem to work.

I am just not sure if it's not compatible with the board, or I need to do more than this...?

body:
Read SparkFun's guide, [Serial Peripheral Interface (SPI)][1], especially the [multiple slaves][2] section:

----

> ### Multiple slaves
>
> There are two ways of connecting multiple slaves to an SPI bus:
>
> 1. In general, each slave will need a separate SS line. To talk to a particular slave, you'll make that slave's SS line low and keep the
> rest of them high (you don't want two slaves activated at the same
> time, or they may both try to talk on the same MISO line resulting in
> garbled data). Lots of slaves will require lots of SS lines; if you're
> running low on outputs, there are binary decoder chips that can
> multiply your SS outputs.
>
> [![enter image description here][3]][3]
>
> 2. On the other hand, some parts prefer to be daisy-chained together, with the MISO (output) of one going to the MOSI (input) of the next.
> In this case, a single SS line goes to all the slaves. Once all the
> data is sent, the SS line is raised, which causes all the chips to be
> activated simultaneously. This is often used for daisy-chained shift
> registers and addressable LED drivers.
>
> [![enter image description here][4]][4]
>
> Note that, for this layout, data overflows from one slave to the next,
> so to send data to any one slave, you'll need to transmit enough data
> to reach all of them. Also, keep in mind that the first piece of data
> you transmit will end up in the last slave.
>
> This type of layout is typically used in output-only situations, such
> as driving LEDs where you don't need to receive any data back. In
> these cases you can leave the master's MISO line disconnected.
> However, if data does need to be returned to the master, you can do
> this by closing the daisy-chain loop (blue wire in the above diagram).
> Note that if you do this, the return data from slave 1 will need to
> pass through all the slaves before getting back to the master, so be
> sure to send enough receive commands to get the data you need.

  [1]: https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi/all
  [2]: https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi/all#slave-select-ss
  [3]: https://i.stack.imgur.com/dskyc.png
  [4]: https://i.stack.imgur.com/soEKe.png


message:
Shield SIM808 EVB V3.2 charge a Lithium battery?

![enter image description here](https://i.stack.imgur.com/0hOAj.jpg)

hello friends do you know if, can this shield (SIM808 EVB V3.2) charge a lithium battery directly or i need additional hardware?, I know that module has conection for battery but it can charge it?

body:
The module does not include a charging circuit for Lithium-ion cells.

----------

**EDIT**

According to the [SIM808 Hardware Design document, Page 28][1], the SIM808 module **does** integrate Lithium-ion cell charging.

It states that the battery should have it's own overcharge, over discharge, over current protection, and reverse-polarity protection.

  [1]: https://seeeddoc.github.io/Mini_GSM-GPRS_Plus_GPS_Breakout-SIM808/res/SIM808_Hardware_Design_V1.00.pdf#page=28


message:
PWM Control, How to stop LED from Flickering?

What is required is controlling the brightness of an LED using both Buttons and a Potentiometer,
Button A: Increase

Button B: Decrease /Dim

Potentiometer: Increase and Decrease,

This however must happen on 1 single circuit and must display the results on an LCD.

If I do this separately, meaning buttons without potentiometer and visa versa, I win, the moment I combine the two. I get flickering when working the buttons, due to the potentiometer.

Alternative Research:[https://www.instructables.com/id/Smooth-Potentiometer-Input/][1]

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

    #include <LiquidCrystal.h>
    #include <Wire.h>
    // ------------------------------------------------------------

    int LED1          = 9;
    int ButtonLeft    = 8;
    int ButtonRight   = 7;
    int brightness    = 0;

    // ------------------------------------------------------------
    byte buttonState1     = 0;
    byte lastButtonState1 = 0;

    byte buttonState2     = 0;
    byte lastButtonState2 = 0;

    unsigned long switchMillis;

    // ------------------------------------------------------------

    int potValue1 = 0;
    int potValue2 = 0;
    int potPin= A0;
    int readValue;
    int writeValue;

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

    // ------------------------------------------------------------
    void setup() {

      lcd.begin(16, 2);
      pinMode (potPin, INPUT);
      pinMode(LED1,OUTPUT);
      pinMode(ButtonLeft,INPUT);
      pinMode(ButtonRight,  INPUT);
      lcd.clear ();
    }

    // ------------------------------------------------------------
    void loop(){

        if (millis() - switchMillis >= 5)
      {
        switchMillis = millis();
        checkSwitches();
      }

       readValue = analogRead(potPin);
       writeValue = (255./1023.) * readValue;
       analogWrite(LED1, writeValue);

        potValue1 = analogRead(potPin) / 10;
        potValue2 = potValue1 / 1.02;

        lcd.setCursor(0,0);
        lcd.print("Potent=");
        lcd.print(potValue1);
        lcd.print("%");
        delay(100);
        lcd.print(" ");
        delay(1);
    }

    void checkSwitches() {

        analogWrite(LED1, brightness);
        delay(10);

      buttonState1 = digitalRead(ButtonLeft);

      if(buttonState1 == HIGH){
        brightness--;
        if(brightness < 0){
          brightness = 0;
        }
      }

      buttonState2 = digitalRead(ButtonRight);

      if(buttonState2 == HIGH){
        brightness++;
        if(brightness > 255){
          brightness = 255;
        }
      }

     lcd.setCursor (0,1);
     lcd.print ("Brightness=");
     lcd.print (brightness);
     lcd.print ("   ");
    }

  [1]: https://www.instructables.com/id/Smooth-Potentiometer-Input/
  [2]: https://i.stack.imgur.com/88swe.jpg

body:
Your code doesn't make much sense.

You set the LED to 2 different brightness values that don't have anything to do with each other: The pot brightness and the button-based brightness. You only adjust the LED based on switches once every 5 mS. Thus the LED is going to flicker between 2 different brightness values.

What do you want it to do? How do you want to control the brightness based on input from both the pot and your switches? (What is the relationship between the buttons and the pot? Should the button input alter max/min value of the pot up and down? Should holding the button down change the brightness by 1 value per a specific time unit? Say 2 increments/decrements per second?)

Describe the user interface you want to achieve, and then think through how you would do that in code.


message:
Why is my relay not triggering?

I have a 4 channel relay for my Arduino. Here's an image:

[![Relay][1]][1]

**From what I can tell, it's rated for 5V direct current because of the big `05VDC` at the bottom, but please tell me if I'm wrong? If I'm wrong, then that's the problem here.**

I've tested out an LED on 5V DC to work and connected it to output side of the relay.

I've connected my Arduino to the input, programmed with the following code:

    const int RELAY_PIN = 3;

    void setup() {
      pinMode(RELAY_PIN, OUTPUT);
      Serial.begin(96000);

    }

    void loop() {
      Serial.println("Relay ON");
      digitalWrite(RELAY_PIN, LOW);
      delay(1000);

      Serial.println("Relay OFF");
      digitalWrite(RELAY_PIN, HIGH);
      delay(1000);
    }

I can confirm that the corresponding LED on the relay for channel 4 does blink for 1 second and stay off for 1 second, which I'm expecting it's meant to do. I've never worked with an Arduino or a relay before.

However, the 5V DC LED on the other end never lights up. Why is my relay not switching on?

Edit: About the LED circuit. It is on and fully powered. If I bypass the relay and join the two wires, the LED lights up. If I plug the two wires into the relay, the LED never lights up.

Edit2: About the jumper: I have a secondary 5V power supply connected to the VCC for what I'm told is isolation. I've read a little on the matter, but am not fully aware of how it works.

Edit 3:

**Connections**

I have the following connections:

 - Output 3 (Arduino) to Input 4 (Relay)
 - 5V (Arduino) to Input VCC (Relay) [The one next to the input pins]
 - Power supply positive/ground to GND (Relay)
 - Power supply negative/live to VCC (the one next to the JD-VCC)

This did not work. What did work was the following configuration:

 - Output 3 (Arduino) to Input 4 (Relay)
 - 5V (Arduino) to Input VCC (Relay) [The one next to the input pins]
 - Jumper across VCC and JD-VCC on the Relay

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

body:
A relay is an electromagnet-driven switch. It opens and closes that switch, but doesn't provide power.

Assuming it's like my relays, that relay can either power the relay coils AND the logic inputs, or (if you remove the jumper) use separate power for the relay coils and the logic signals.

Since you've removed the jumper, you need to provide 2 different 5V power sources to drive the relay - one high-current supply to the VCC, which runs the logic circuits and the relay coil. Another to the logic power in. Then you ground the input pin to activate one of the relay channels.

Finally, you need to wire the screw terminals on the left side into a circuit with separate power that controls something. For an LED, you'd need power, the LED, and a current-limiting resistor wired in series with the screw terminals on LED channel 1.

For an LED this is serious overkill. You could drive the LED directly (with a current limiting resistor) from the Arduino logic signal.


body:
 - From the image in the question, the jumper across pins J5 (in the
   below schematic) or JD as on the silk screen on the PBC is missing.
[![enter image description here][1]][1]

 - Using the above schematic, a choice to power the Ardino and the relays off of one 5V power supply can be made.  This appears to be done by connecting the 5V to the VCC pin, Ground to the GND pin & placing a jumper across J5.  However, it appears that the relays can be isolated from the Arduino if desired.  This appears to be done by connecting the Arduino's 5V to pin 2 of J5.  That should be enough to light up the LED indicator and therefor the optical isolator when the Arduino's output to IN1, 2, 3 or 4 is low.  Then, connect the 2nd power source 5V to pin 1 of J5 and the ground from the 2nd power source to pin GND.  This last step should provide the power to close the relays when the Arduino takes IN1, 2, 3 or 4 low.
 - Lastly, make sure the polarity of the 2nd power supply (if one is used) is correct.  The output side of the optical coupler and the transistor driving the relay only work when the current is passing in the proper direction. Not to mention, the reverse bias [flyback diode][2] (D1, 2, 3 & 4) would short out the power supply if connected in the reverse direction.  However, this catastrophe is avoided here as the transistors (Q1, 2, 3 & 4) would not pass current in the reversed direction.

  [1]: https://i.stack.imgur.com/wXP4o.png
  [2]: https://electronics.stackexchange.com/questions/100134/why-is-there-a-diode-connected-in-parallel-to-a-relay-coil


message:
There is no PWM output

I recently made a project where output is coming from the differential between data reading and reference value. It works on my Proteus simulation but there is no PWM output on my real world device.

Here is my code listing

    for (z = 0; z <= output2; z++)
      if (output2 >= 30) {
       toggle == HIGH;
       en = !en;
      }
    if (en == true) {
      OCR1A = map(z, 0, 255, 0, ICR1); ;
      OCR1B = 0;
    } else {
      OCR1A=0;
      OCR1B = map(z, 0, 255, 0, ICR1);
    }
    if (output2 < 30) {
      en = !en;
      analogWrite(9, 0);
      analogWrite(10, 0);
    }

body:
I’m not sure what you’re trying to accomplish, but you’re writing a constant `0` to the analog output.

>     if (output2 < 30) {
>       en = !en;
>       analogWrite(9, 0);
>       analogWrite(10, 0);
>     }

To quote the [analogWrite() doc](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/)

> Syntax
>
> analogWrite(pin, value)
>
> Parameters
>
> pin: the pin to write to. Allowed data types: int.
>
> value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types: int

If you want to see an output, you have to write a value between 0 and 255.


message:
Why does current flow along a wire instead of a resistor right next to it?

I am having trouble understanding exactly what is going on in a circuit where when a button is pressed an LED goes on. Also, I have the Arduino UNO.

The schematic can be seen at:

[2:36][1] of this video: [Arduino Tutorials: Control a LED with a Button][2].

[![Fritzing of complete circuit][3]][3]

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

[![Pull down resistor on input][4]][4]

I’m a beginner but do understand concepts like voltage, amps, resistors, Ohm’s law, etc. So answers don’t have to be super simple, but simple enough that I can understand them. Thanks!

  [1]: https://youtu.be/ksNbEuhO4fU&t=156
  [2]: https://youtu.be/ksNbEuhO4fU
  [3]: https://i.stack.imgur.com/t6Nmy.png "Fritzing of complete circuit"
  [4]: https://i.stack.imgur.com/Gl4XP.png "Pull down resistor on input"

body:
> So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

Simple: It *does* go through the pull down resistor. But  it *also* goes down the "input" wire.

For simplicity you can imagine that the input is simply a very large resistor. Say, 1MΩ.

The circuit can then be simplified as:

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

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

<!-- End schematic -->

Contrary to popular belief, current does *not* take the path of least resistance. It takes *all possible* paths. The quantity of current through each path is proportional to the resistance of the paths.

In this example we have two paths - one with 10kΩ and one with 1MΩ.  That's a ratio of 1:100, and the current will be split accordingly.

You can calculate the current that flows through each resistor simple using Ohm's Law because the wires and switch are (in an ideal world) just not there. The 5V is directly connected across each of the resistors.

So for the 10kΩ resistor the current through is is:

         V      5
    I = --- = ----- = 0.0005 = 500µA
         R    10000

And for the 1MΩ it is of course 100x smaller (I'll let you do the maths for that if you want to check), so 5µA.

The full current that the circuit takes is 505µA, with it split between the two resistors.

With the Arduino instead of the 1MΩ resistor it's exactly the same (though the current values may vary somewhat).  500µA flows through the 10kΩ resistor, and "some tiny current" flows through the Arduino.

However, with all that said, the Arduino really doesn't care about the current. All it cares about is the voltage. With the button pressed both the input and the 10kΩ resistor are connected directly to the 5V supply - so the Arduino reads that as "HIGH". When you release the button the input is now connected to ground through the 10kΩ resistor, but there's no current to flow, so there's no voltage across the resistor (the voltage across a resistor is proportional to the current flowing through the resistor - Ohm's Law), so it's as if the input is connected directly to ground - and the Arduino reads that as "LOW".

To be more technically accurate the input of the Arduino is actually more akin to a tiny capacitor.  When you apply 5V to the input it charges that capacitor up. Once it reaches 60% of 5V the Arduino recognises it as a "HIGH" signal.

When you release the button that capacitor is then connected to ground through the resistor, and it discharges through that resistor. Once it drops to 30% of 5V the Arduino sees it as being "LOW".

If you don't have the pull-down resistor, when you remove the 5V from the input that capacitor is still charged. So the Arduino still sees it as a HIGH. The charge in the capacitor will slowly bleed away until it's low enough to be seen as low.

But, (and it's a *big* but), the capacitor is very sensitive and can be charged up again by ambient energy around the place (radio waves, static electricity, etc). It can harvest enough energy from the environment to get back up to the 60% of 5V and be seen as "HIGH" again. This is known as "Floating", and is something you do *not* want in your circuit. The input "flaps around" between HIGH and LOW with no control.  Which is why the pull-down resistor is absolutely essential.


message:
How can I compare two serial port readings on Arduino Mega?

I'm writing some code that compares information from two Arduino Unos by an Arduino Mega 2560. The problem that I'm having is that when I read the information coming in through `Serial1` and `Serial2` on my `if` statements, I get both inputs out on my serial monitor for the Mega, but if I try to compare them after I have read them it comes out not working the way it is intended. I don't know if I might be missing some syntax on my code or if I'm doing this wrong but I would appreciate any help I can get.

    byte inData;

    byte inDataTwo;

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial2.begin(9600);

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

    void loop()
    {
      if (Serial1.available()>0 )
      {
          inData = Serial1.read();
          Serial.print(char(inData));
      }
      if (Serial2.available()>0)
      {
        inDataTwo = Serial2.read();
        Serial.print(char(inDataTwo));
      }
      if(inData == inDataTwo)
      {
        Serial.print("true");
      }
      else
      {
        Serial.print("False");
      }
    }`

body:
I think your code is implemented wrong in general. Even if it worked "like intended" it would not behave like you might want it to.

The first problem is, that you are polling for bytes that are received **asynchronuously**. That means that  two byte sequences must not only be equal, they must also be sent "at the same time" if they should pass your comparison test. As the atmega will `loop()` very fast, there is only very little tolerance in timing.

Secondly, the variables you write received values to are not reset, meaning that once they have the same value they will pass the if statement until another byte has been received. Actually they aren't initialized and therefore will be `0` at the very beginning. So I wonder why you don't get your `Serial` interface flushed with `true`. Is this actually the entire code?

As a solution I suggest accumulating received bytes into a buffer and waiting for a soecific termination byte (often `/n`). If a termination character has been received, perform the comparison on that buffer.


message:
Help with coding Arduino Nano to run fan through slide switch at specific intervals

I’m trying to use Arduino Nano to run my 5 V PC fan, which, I know it sounds crazy, it’ll be mounted on a piece of Tupperware that’ll control the airflow through it via the fan. However I have no idea how to code the Arduino, but I do know how to code other things when I’ve done it in class. The setup is a 5 V rechargeable lithium ion portable battery connected to the switch which would be connected to the Arduino, and when the switch is triggered/flipped it would allow power to the Arduino, boot it up, and trigger the code that would tell the fan to run at specific intervals. The idea for intervals is a result of the battery only having 23 hrs and 10 minutes of continuous battery life while powering the fan. The pseudocode would look something like:

> Press bump switch, it turns on the Nano with the ensuing program. Twice an hour, the Nano starts the fan. The fan runs for 20 seconds to 30 seconds each time the fan is started. After a set of 48 on/off cycles have completed (24 hours), the Nano is set to sleep mode in order to save power. In order to restart cycles, user must press bump switch again.

I’m pretty sure I have the hardware side of things down but if I don’t please do inform me.

I’ve attached a picture of what it’ll approximately look like, with the battery at the left, switch in the middle, then the Arduino (not seen in picture), then the fan.

[![Photo of LiPo battery, switch and fan][1]][1]

I know this is asking a lot when I don’t even know where to get started with the coding, but I’d be sincerely eternally grateful.

  [1]: https://i.stack.imgur.com/K0bqg.jpg "Photo of LiPo battery, switch and fan"

body:
You can't run the fan directly from an Arduino pin. The fan will require to much current for that to work. Instead connect the fan, via a transistor/mosfet to the Arduino.

Also add a (flyback-)diode to the fan, as turning of the fan can create huge (but short) voltage spikes, which can damage the transistor/mosfet.

Pseudo code would be something like:

    for( byte i=0; i<48; i++ )
    {
      digitalWrite(fanPin, HIGH);
      delay(20000);
      digitalWrite(fanPin, LOW);
      delay(1780000);
    }

You could also put the Arduino in sleep mode, during those half hours, as well. You could use the [LowPowerSleep](https://www.arduino.cc/en/Reference/LowPowerSleep) library. Then replace the `delay(ms)` with `LowPower.sleep(ms)`.

Lastly, some powerbank will automatically shut down, if the detect nothing is using power. The Arduino, without the fan on, will use so little current (compared to charging a phone) that such a powerbank would shut of.


message:
Can I use WTV020 sound module as SD card reader?

I want to try this example, [A Simple Function for Reading CSV Text Files][1], in order to read a .csv file from an SD card, but I don't have the SD card reader module and can't find it in my country.

What I have found everywhere is this sound module, [WTV020-SD][2], and I wonder if I can use that to read a single .csv file from it, using the SD Arduino library. I checked the module's documentation and there's nothing about it in there.

  [1]: https://forum.arduino.cc/index.php?topic=340849.0
  [2]: https://dlnmh9ip6v2uc.cloudfront.net/datasheets/Widgets/WTV020SD.pdf

body:
It seems unlikely, for if you compare the schematic of the WTV020-SD (card reader part only) from the data sheet that you provided:

[![WTV020-SD (card reader part only) schematic][1]][1]

to the schematic of a bog standard SD card reader:

[![Standard SD card reader schematic][2]][2]

they are not the same. Instead of interfacing directly to the Arduino, as the standard SD card reader does, the WTV020-SD has additional logic, in the form of a WTV020SD-20S IC.

Therefore the code on the Arduino forums is highly unlikely to work.

  [1]: https://i.stack.imgur.com/1vRTv.png "WTV020-SD (card reader part only) schematic"
  [2]: https://i.stack.imgur.com/lHG42.jpg "Standard SD card reader schematic"


message:
My Code turns on my LED even when my switch is not pressed

I am trying to create a circuit that will turn my motor when I clap. When the first limit switch is low, and there is only one clap, a solenoid pin is supposed to be engaged (currently an LED), but when I clap once without pressing the limit switch, my LED turns on.

Also, I can't seem to get my code to work properly with the limit switches, to control my motor.

I am not sure what is wrong, can someone help?

I have an Arduino Uno with the following code:

```
#define sound_Sensor 2
#define EN1 9
#define IN1 8
#define IN2 7
#define solenoid_pin 6
#define LimSwitch1 4
#define LimSwitch2 3

int lastSoundValue;
int soundValue;
long lastNoiseTime = 0;
long currentNoiseTime = 0;
int solenoidPinStatus = LOW;
int status_motor = LOW;
int clap_interval = 200;
int claps = 0;
int pos1 = 1;
int pos2 = 1;

void setup() {
  pinMode(sound_Sensor, INPUT);
  pinMode(EN1, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(solenoid_pin, OUTPUT);
  pinMode(LimSwitch1, INPUT);
  pinMode(LimSwitch2, INPUT);
}

void loop() {

  soundValue = digitalRead(sound_Sensor);
  currentNoiseTime = millis();
  if (soundValue == 1 && lastSoundValue == 0 && (currentNoiseTime > lastNoiseTime + 200))
  {
      if (claps == 0) // allow first to register without much condition
      {
          claps = 1;
          lastNoiseTime = currentNoiseTime;
      }
      else
      {
          if (currentNoiseTime > lastNoiseTime + clap_interval)
          {
              claps++;
              lastNoiseTime = currentNoiseTime;
          }
      }
      Serial.print(claps);
  }
  else
  {
      if (currentNoiseTime > (lastNoiseTime + 3 * clap_interval)) // no claps for a longer duration time to print and/or reset clap
      {
          if (claps > 0)
          {
              while(status_motor == LOW){
                  if (digitalRead(LimSwitch1) == LOW && claps == 1)
                  {
                    solenoidPinStatus = HIGH;
                    digitalWrite(solenoid_pin, HIGH);
                  }

                 if (digitalRead(LimSwitch1) == LOW)
                 {
                    pos1 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                  }
                 else if (digitalRead(LimSwitch2) == LOW)
                 {
                    pos2 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor99++
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                 }
              }

              while(status_motor == HIGH){
                if (pos1 == 2 && digitalRead(LimSwitch2) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos1 = 1;
                }

                else if (pos2 == 2 && digitalRead(LimSwitch1) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos2 = 1;
                }
              }
          }
             claps = 0; ///reset
      }
  }

// if (solenoidPinStatus == HIGH && status_motor == LOW && digitalRead(LimSwitch1) == LOW)
// {
//   solenoidPinStatus = LOW;
//   digitalWrite(solenoid_pin, LOW);
// }
  lastSoundValue = soundValue;
}
```
Sorry my wire diagram may not be the easiest to look at...

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

body:
I think your problem might be connected to wiring.

This is one of the ways you can correctly connect a switch to Pin 8.

[![Arduino with switch][1]][1]

In this case you need to configure Pin 8 as INPUT_PULLUP to use internal "pullup" resistor. When switch is not pressed Pin8 is connected to 5V through that resistor and value on the pin is HIGH. When you press the switch it connects Pin 8 to ground (the resistor prevents a short) and that way value on Pin 8 is LOW.

This is code that works correctly with the design above

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

    void loop()
    {
      if (digitalRead(8) == HIGH)
      {
        Serial.println("It's HIGH");
      }
      else
      {
        Serial.println("It's LOW");
      }

      delay(1000);
    }

If you do not configure Pin 8 as INPUT_PULLUP but just normal INPUT (as you did in your code) when the button is not pressed Pin 8 is "floating" (it's not connected to anything) and on a "floating" pin values are random.

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


message:
Programming the serial description

Is it possible to program a custom description so that my python program can know exactly what USB port to connect to for that specific programming?

It should be able to find any board with that program so the best approach is if a custom description can be programmed with the active program being uploaded.

I want to make sure my setup can handle multiple Arduino boards and always know what USB to use for each specific use.

This finds a general Arduino device:

    for port in serial.tools.list_ports.comports():
     if "Arduino" in port.description:
      print "Arduino device!"

But I want something like this:

    for port in serial.tools.list_ports.comports():
     if "proximity_sensor" in port.description:
      print "My specific Arduino program!"

body:
On a normal Arduino board, no, it's not possible from a sketch POV. With a Leonardo or similar ATMega32U4 based board it may be possible to give it a unique VID/PID combination, and even possibly custom manufacturer and product strings. You may be able to do it by creating a custom board definition in boards.txt (or maybe manipulation of the AVR core) - but I have never tried that sort of thing with Arduino, so I cannot vouch for how easy it would be.

However (*shameless self-promotion coming here...*) if you were to switch away from Arduino and use a chipKIT board like the Lenny (or any of the other chipKIT boards with a direct USB connection, such as the Fubarino boards) then it is possible to craft a completely custom USB profile from within your sketch, including VID/PID, Manufacturer and Product strings, and even what devices the board implements. For example:

    USBFS usbDevice;
    USBManager USB(usbDevice, 0xf055, 0x1234, "Espentech", "My Little Widget");
    CDCACM USBSerial;

    void setup() {
        USB.addDevice(USBSerial);
        USB.begin();
    }

    void loop() {
        USBSerial.println(millis());
        delay(1000);
    }

Which results in:

    [  661.328155] usb 2-1.2.7: new full-speed USB device number 10 using ehci-pci
    [  661.458613] usb 2-1.2.7: New USB device found, idVendor=f055, idProduct=1234
    [  661.458616] usb 2-1.2.7: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [  661.458619] usb 2-1.2.7: Product: My Little Widget
    [  661.458621] usb 2-1.2.7: Manufacturer: Espentech
    [  661.458623] usb 2-1.2.7: SerialNumber: CK2660A05312F3
    [  661.459181] cdc_acm 2-1.2.7:1.0: ttyACM0: USB ACM device


message:
Analog reading with noise - Arduino Uno VS ESP12e

I was testing analog output from a microphone (Max9814) with an Arduino Uno, which came with nice results. The output provided by the microphone is converted into sound and is loud and clear.

Setup: (Max to Uno)

 - Pin Vdd to 3,3V
 - Pin GND to GND
 - Pin Out to A0

---

However when I tried to set it up with an ESP12e instead of an Uno, I got a lot of 'noise' and no clear sound at all.

Here I used the following setup: (Max to ESP)

 - Pin Vdd to VCC (VCC is measured at 3.3v with a multimeter)
 - Pin GND to GND
 - Pin Out to AD0

**A little 'side step'**

The problem arised that the analog output from the microphone delivered a voltage of around 1.24, while the ESP12e analog has 1v as max input. This made the analogRead max out all the time. For this reason I put a 10k OHM resistor between the OUT and AD0 combined with a 20k OHM resistor between gnd and AD0. This resulted into nice analog readings (instead of 1024, around 400-500 all the time).

However, like mentioned before, a lot of noise is in between and the sound is not clear. (I also tried to work with 'sample windows', here is the 'filtering mechanism' which can be found on many sites/questions and works perfectly fine):

    //(global logic is set to take n samples and than print the line)
    //Tried n of 5 to 20
    //Also instead of just samples tried the micros variant instead of just samples which is also found on many sites to create a time window to record.
    unsigned int sample = analogRead(A0);
    if (sample < 1024) {  // toss out spurious readings
      if (sample > signalMax) {
        signalMax = sample;  // save just the max levels
      } else if(sample < signalMin) {
        signalMin = sample;  // save just the min levels
      }
    }

    unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
    Serial.println(peakToPeak);

Does somebody have a clue why the Arduino gives such clear and good sound, while the ESP12e does not. (The analog values do not 'seem' to differ much in the levels)

body:
The ESP8266 is an incredibly (electrically) noisy environment.

Because you can't use anything except the internal voltage reference, which is in turn driven from the internal noisy power, you can't get anything even vaguely approaching stable readings.

It is recommended to disable the WiFI completely ("Modem Sleep") when doing ADC readings to reduce noise.

However, the ADC was never intended for this kind of work. Its primary role is for monitoring the battery voltage of your hardware - and as such it really doesn't care that much about noise, since you can average a number of samples for greater accuracy (something you can't really do with audio).


message:
WiFi Connection With a Enterprise WLAN

I have an ESP32 and want to connect it to the WLAN at my office. Based on my current knowledge of the Arduino, we use the `WiFiClass` to connect to a WLAN and then use a `WiFiClient` to use the WiFi for data transfer.

In order to connect to the WLAN at my office, a certificate is needed. I have asked the network guys to issue a x.509 certificate and plan to use the `WiFiSecureClient` class.

The problem is that my `WiFi.begin(ssid)` method never leaves the following `while` loop:

    Wifi.begin(ssid); // my office needs a certificate to connect to the wifi at the first place
    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }

Note that to connect to my office network, no password is needed. The x.509 certificate is enough for the connection to establish.

Only after a WiFi connection is established, I can set the `WiFiSecureClient` parameters of the CA. But to connect to the WiFi, I need the certificate.

This is very confusing. Could someone please clarify a way our for me in this situation.

body:
The Arduino API for ESP32 does not support your desired configuration.

The ESP32 is capable, but there is no easy "Arduino" interface to configure it.

Instead you will have to directly interface with the ESP32 SDK and configure things manually.  That won't be easy.

[This example code](https://github.com/espressif/esp-idf/tree/master/examples/wifi/wpa2_enterprise) shows you how it can be done - however that code is not designed to run in the Arduino environment, so you will first need to understand exactly what it is doing and then adapt it to suit.


message:
Problem with LCD

I'm working on this piano project. When I push a button one of the led light is suppose to turn on and a tone comes out of the piezo. The LCD screen is suppose to print out a sentence but I can't get it to work.

Here is a picture of the board ( everything works except the LCD) I think the problems lies in the power supply but I'm not sure. This is the first time I use a big breadboard. [![Image of the board][1]][1]

Here is my code:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(13,12,11,10,9,8);

    int p1 = 1;
    int p2 = 2;
    int p3 = 3;
    int p4 = 4;

    int C,D,E,F;
    int buzz = 5;

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

      lcd.print("hello, world!");

      Serial.begin(9600);
      pinMode(p1,INPUT);
      pinMode(p2,INPUT);
      pinMode(p3,INPUT);
      pinMode(p4,INPUT);

    }

    void loop()
    {

      lcd.setCursor(0, 1);

      lcd.print(millis() / 1000);

      C = digitalRead(p1);
      D = digitalRead(p2);
      E = digitalRead(p3);
      F = digitalRead(p4);

      if(C == 1){

        tone(buzz,523);
      }else if(D == 1){
        tone(buzz,587);
      }else if(E == 1){
        tone(buzz,659);
      }else if(F == 1){
        tone(buzz,698);

      }else{
        noTone(buzz);
      }
      delay(50);
    }

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

body: The LCD is not powered, there are 2 separated power rails... use a wire to connect both rails.


body:
the power rails are separated in the middle of the breadboard. bridge them with jumper wires

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

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


message:
Send data string from Arduino UNO to ESP8266-01

Is there anyway to send a string from an Arduino UNO to a ESP8266-01 (one with only 8 pins RX, TX, CH-PD, vcc, ground, reset, GPIO0, GPIO2) without using without using AT commands.  I've looked everywhere and from what I can see UART doesn't work and SoftwareSerial uses only AT commands.  I am at my wits end.  Can anyone help here? please.
I have tried Serial.write but only writes String and Esp8266 only receives ints.

I found some code I thought might work but so far I can see that the arduino is sending <100.00:200:00>, but on the esp8266 all I get is four backwards question marks

this is the code on the Arduino UNO

    #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // TX | RX
     float water = 100.00;
     float battery = 200.00;
    void setup()
    {
        Serial.begin(9600);     // communication with the host computer
        //while (!Serial)   { ; }

        // Start the software serial for communication with the ESP8266
        ESPserial.begin(57600);

    }

    void loop()
    {
       ESPserial.print("<");
              ESPserial.print(water,2);
              ESPserial.print(":");
              ESPserial.print(battery,2);
          ESPserial.print(">");
          Serial.print("<");
              Serial.print(water,2);
             Serial.print(":");
              Serial.print(battery,2);
          Serial.print(">");
         delay(10000);
    }

and here is the code on the ESP8266

    #include <SoftwareSerial.h>
    #include <string.h>

    SoftwareSerial ESPSerial(2,0);

    const byte numChars = 32;
    char receivedChars[numChars];
    boolean newData = false;

    String water;
    String battery;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      ESPSerial.begin(57600);
      delay(10);

    }

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

     water= getValue(receivedChars, ':', 0);
      battery = getValue(receivedChars, ':', 1);
    Serial.println(water);
    }

    void recvWithStartEndMarkers() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '<';
        char endMarker = '>';
        char rc;

        while (ESPSerial.available() > 0 && newData == false) {
            rc = ESPSerial.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;
            }
        }

The Arduino sends writes every 10 seconds and the esp prints the ???? every 10 seconds but with a lag.

I am not sure what the pin out to pin in should be.  Right now I have the Arduino 2(TX) attached to the GPIO0 and the Arduino 3(RX) attached to the GPIO2.

Can someone look at my code and see what I am doing wrong.  I thought I would send over two values because eventually I want to show water level and battery level.

body:
I figured this out.
send code is

Arduino Uno side

     f = String('<')+String("Hi")+String(',')+String(waterSensorOutValue)+String(',')+String(sensorBatValue)+String('>');

        Serial.print(f);

ESP side

    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;  long itt = 500;
        long itt2 = 500;

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

    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

Then connect to wifi and upload to ThingSpeak.

I had to get rid of Softwareserial and connect the RX on the Arduino Uno to the TX on the ESP8266-01 and the TX on the Arduino Uno to the RX on the ESP8266-01.

Everything worked great till I changed from an Arduino UNO R3 to an Arduino Pro Mini for size and energy conservation.

With the wiring the same (I think) and the code the same the string (f) doesn't get sent over to the ESP.  I don't see the TX led flashing on the Pro Mini when it should be transferring string(f) and nothing gets uploaded to ThingSpeak.  Not sure why but I will post another question for that one.  Thanks for everyone's help.


body:
Sending data between Arduino and NodeMcu (Serial Communication)

youtube link  (in French):

https://youtu.be/0TXmi9EgaCs


message:
Problem with String& argument of a function

I am trying to send SMSs using a GSM module with Arduino Mega. I have followed a tutorial and downloaded the SIM908IDE100 library. I am using the function

`SendSMS(String&, const char [27]);`.

It works fine when I type:

`sms.SendSMS("1234567890","Text message");`

where "1234567890" is the telephone number I want to send the SMS to and "Text message" is the text of the SMS.

If I instead try to pass to the function a String containing the telephone number

`String number = "1234567890";
sms.SendSMS(number,"Text message");`

I get the following error:

`exit status 1
no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]);'`

I don't understand what String followed by an ampersand means. What am I supposed to pass the function as its first argument?

body:
The function prototype in [sms.h][1] is

    char SendSMS(char *number_str, char *message_str);

if `number` is `String`, you should have

    sms.SendSMS((char*) number.c_str(),"Text message");

`c_str()` is a function of the Strinng class. It returns a pointer to internal char array of the String object.

The cast to `char*` is necessary because the author of the library didn't make the parameter constant with `const char*`. (It is a good practice, to declare pointers and references as constants.)

The error message `no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]);` shows the arguments you try to use. `String&` is reference to some instance of the `String` type

  [1]: https://github.com/fffaraz/gpst/blob/master/gsm-shield-arduino/branches/SIM908IDE100/sms.h


message:
Is it possible to send a float Array over I2c

I have tried it several times myself but i never could send or receive it properly. I am asking myself if it is possible and if so could someone explain how?

Cheers.

body:
Below is a simple rewrite of the Master Writer/Slave Receiver Wire Tutorial, https://www.arduino.cc/en/Tutorial/MasterWriter, for a vector of floating-point numbers.

**Master Writer Sketch**

    #include <Wire.h>

    const int DEVICE = 8;

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

    void loop() {
      const int VEC_MAX = 6;
      float vec[VEC_MAX];
      uint8_t* vp = (uint8_t*) vec;

      Wire.requestFrom(DEVICE, sizeof(vec));
      while (Wire.available()) {
        *vp++ = Wire.read();
      }

      for (int i = 0; i < VEC_MAX; i++) {
        Serial.println(vec[i]);
      }

      delay(500);
    }

**Slave Receiver Sketch**

    #include <Wire.h>

    const int DEVICE = 8;
    const int VEC_MAX = 6;
    float vec[VEC_MAX] = { ... };

    void setup() {
      Wire.begin(DEVICE);
      Wire.onRequest(requestEvent);
    }

    void loop() {
      delay(100);
    }

    void requestEvent() {
      Wire.write((uint8_t*) vec, sizeof(vec));
    }

> Is it possible to send a float Array over I2c

So I would answer - Yes.


message:
Conditions with GSM module SIM900 doesn't execute

I'm executing this code to control a LED with GSM SIM900 message but there are two problems. First, it receives messages sometimes and some times doesn't. The second is that it doesn't execute the `if` conditions that are on the GSM message when received.

Is there a problem with my GSM module? Can any one help?

    #include <SoftwareSerial.h>
    SoftwareSerial gsm(9,10);
    String msg;
    const int LED = 13;

    void setup() {
      gsm.begin(9600);
      Serial.begin(9600);
      Serial.println("PUMP CONTROL");
      Serial.println("t : to receive text");
      delay(1000);

      pinMode(LED, OUTPUT);
      digitalWrite(LED, LOW);
    }

    void loop() {
      if (Serial.available()>0)
      switch(Serial.read())
      {
        case 't':
        showSMS();
        break;
      }

      while(gsm.available() > 0)
      {
        Serial.write(gsm.read());
      }
      if ( msg == "ON")
      {
        Serial.println("ON");
        digitalWrite(LED, HIGH);
         Serial.println("ON1");
        delay(1000);
      } else if (msg == "OFF")
      {
        digitalWrite(LED, LOW);
        delay(1000);
      }
      if(msg != "") msg = "";
    }

    void showSMS()
    {
     gsm.print("AT+CMGF=1\r");
     gsm.print("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     msg = "";
     while(gsm.available() > 0)
     {
      msg += gsm.read();
     }
     Serial.println(msg);
    }

body:
I’ve solved the condition problems by making the condition with the ASCII code of ON and OFF.

I replaced:

    if ( msg == “ON”)

with

    if(msg.indexOf("ON")>=0)

and replaced:

    else if (msg == "OFF")

with

    if(msg.indexOf("OFF")>=0)


message:
ESP32 bluetooth discovery parse names

I'm running a sample code from ESP32 examples and I'm scanning available BLE devices. I can see device MAC address etc. But for few devices I can't see their names.
I am using ESP-WROOM-32 with hardware support checked out directly from their github (some bugs were fixed earlier on github than via lib manager)

When I use LightBlue app for discovery of BLE Devices I can see names for more devices that ESP. What can I change to see the names correctly? OR Can how can I parse device name from the data I'm receiving?

This callback code

    class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
        void onResult(BLEAdvertisedDevice advertisedDevice) {
          Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
          Serial.print(" RSSI: ");
          Serial.println(advertisedDevice.getRSSI());
        }
    };

produces this output:

    Advertised Device: Name: , Address: 1d:0c:c7:3a:fb:c6, manufacturer data: 4c0009060378c0a81f12, payload: 1073609632
     RSSI: -75

body:
Bluetooth has two ways of dealing with device names. A device can optionally choose to advertise its device name. It also has to respond to a "get device name" request. The former is passive, and is what you normally see when scanning. The latter is active and requires you to connect to the device and make a request. If the device doesn't advertise the device name then the only way you can get the name is to make a GATT "Name Characteristic" request to the device. The ESP32 doesn't (AFAIK) do that automatically because these things are designed to be "light weight". Your heavier-weight "reference" software can go off and do more things because it's a full-blown application.

You can sometimes see the difference in the devices because your reference application might populate the list of devices with a combination of MAC addresses and names, and then replace the MAC addresses with names in a later step. Also it probably caches names that it has queried in the past.


message:
How can I hook up multiple MMA8451 accelerometers, (I2C protocol) using one Arduino Mega?

How can I hook up four (adafruit) MMA8451 accelerometers (using I2C protocol) using one Arduino Mega? What I'm confused about is I only have one SDA and SCL on the Arduino Mega obviously. So how can I connect these all? Multiplexer? I need four because I have one on each leg of a robot. Or is perhaps this impractical to put an accelerometer on each leg of robot? I'm a little new to electronics so please explain in depth if you could. Thanks.

Note to moderators: I just would really love an answer to this even if this doesn't meet the super strict question guidelines. It seems every time I post here there's always that one person who takes it down for any number of trivial reasons. Please let me get an answer at least. Thank you!

body:
Brief explanation: When you talk to the slave device through I2C you start with (slave) device address. Then you send the message. It is like calling your colleague in an office with many other people. You say: "John", and when he is aware you continue with message, like "let's go for coffee".

This arrangement allows for adding up to 127 devices on one I2C bus. Each device must have different address (sorry, you cannot have two John's in the office, it will cause conflict). Generally two different type of devices will have different I2C addresses, but it may happen you need to use two (or more) of the same (like in your example). In this case, see below.

Many devices with I2C interface allows for address change. Using this facility you are able to communicate with many of the same devices through the same pair of cables.
You can check if your chosen accelerometer has possibility for address change: On picture below there is one with Address tab. When jumper is not fitted, you will get one address, when is fitted, the address of this device will be different, allowing of two of this accelerometers on one I2C bus. Unfortunately in this example there will be possibility of maximum of two of the same devices.
[![Accel][1]][1]

Of course there are devices with more than two possible addresses, you need to search for them.
And, yes, it is fine to use one Arduino to communicate with many I2C devices.

EDIT:
Looking after some of Adafruit accelerometers, I have found this page: [https://learn.adafruit.com/i2c-addresses][2]

And small off topic note: If you struggling on finding I2C with more than 2 addresses, check if it is easier to use SPI protocol. In this case you need (edited to correct bus lines names after user CrossRoads comment) MISO, MOSI, SCK and CS (chip select) wires. Chip select is individually connected to each slave device. This allows selecting particular device without addressing issue.

  [1]: https://i.stack.imgur.com/OuGrb.png
  [2]: https://learn.adafruit.com/i2c-addresses


body:
Talking about I2C protocol. The slave Address is of 7 Bits that means one I2c can handle 127 Slave I2C devices of different address. So you can connect 127 devices with Single I2C Port just make sure there slave address is different from each other.

Some I2C devices are provided with the option to select salve address by setting some pins high and low. If you are using some identical sensors you are set their slave address different.


body:
The general technique for addressing multiple I2C devices is:

1. If the device(s) have only one address: use an I2C bus multiplexer.
2. If the device(s) have two addresses controlled by an addressing pin: use digital output pins from the Arduino to select which device to address, e.g., set the control pin for the selected device low and others high and use the corresponding address to address the device.

With MMA8451Q, factory default it has two distinct I2C addresses 0x1C and 0x1D, controlled by the SA0 pin, use digital output pins on the Arduino Mega to address the selected device (address 0x1C) by setting the corresponding output pin low for the selected device and the control pin for the others to high (address 0x1D). Use address 0x1C to interact with the selected device.

Cheers!


body: Simple just connect all SCK and SDL accelerometer lines together and then u just need to get a specific code address in your use to get a data from any of the accelerometers


message:
Modifying a code

I use this code to turn on/off a small 5v dc motor. How can I modify it so that the arduino writes the potentiometer value to the motor when it is in ON state ?

```
int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{
     if (ButtonState == 1)
     {
         if (motorstate == 1)
         {
             motorstate = 0;
         }
         else
         {
             motorstate = 1;
         }
     }
     lastButtonState = ButtonState;
}

digitalWrite(enable, motorstate);
delay(20);
```

body:
(this is not an answer, but just a comment, used to use code alignment).

This sketch (which I aligned in your code) can be rewritten to

    int speed = analogRead(pot) / 4;
    ButtonState = !digitalRead(Switch);

    if (ButtonState != lastButtonState)
    {
         if (ButtonState == 1)
         {
             motorstate = (motorstate == 1 ? 0 : 1);
         }

         lastButtonState = ButtonState;
    }

    digitalWrite(enable, motorstate);
    delay(20);

I suggest the best way to proceed is to add print statements and use the serial monitor to check what values you get and see what you expect (which is not fully clear).


message:
D1 mini / esp8266 WifiManager

So i have a D1 mini that I want to connect to the wifi.
I found the following code on the internet that is supposed to start a web server, that you can visit and then connect to the chosen wifi through the website. It will then remember the settings and try to connect to that wifi next time before it starts a web server - which is just what I need!
The problem is that when I connect to the wifi the d1 mini thinks it did just than - but when I visit my router and check it is not connected.

I cannot figure out why it thinks it's connected but is not, can anyone help me?

    #include <FS.h>                   //this needs to be first, or it all crashes and burns...
    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

    void setup() {

      Serial.begin(115200);
      Serial.println();

      //WiFiManager

      WiFiManager wifiManager;

      //reset settings - for testing
      wifiManager.resetSettings();

      IPAddress _ip = IPAddress(192, 168, 0, 35);
      IPAddress _gw = IPAddress(192, 168, 0, 1);
      IPAddress _sn = IPAddress(255, 255, 255, 0);

      wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
      if (!wifiManager.autoConnect("WemosAP", "ConfigureMe")) {
        Serial.println("failed to connect, we should reset as see if it connects");
        delay(3000);
        ESP.reset();
        delay(5000);
      }
      //if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");
      Serial.println("local ip");
      Serial.println(WiFi.localIP());
    }
    void loop() {
    }

btw: the ip 192.168.0.35 is free, and I have checked both the gateway and the subnet mask from my laptop by running ipconfig in cmd.

body:
So it seems like the code is just broken. I found an example from the WifiManager library that is called "autoconnect". This just seems to do the exact same thing, just by also working:

    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

    //needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

    void configModeCallback (WiFiManager *myWiFiManager) {
      Serial.println("Entered config mode");
      Serial.println(WiFi.softAPIP());
      //if you used auto generated SSID, print it
      Serial.println(myWiFiManager->getConfigPortalSSID());
    }

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

      //WiFiManager
      //Local intialization. Once its business is done, there is no need to keep it around
      WiFiManager wifiManager;
      //reset settings - for testing
      //wifiManager.resetSettings();

      //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
      wifiManager.setAPCallback(configModeCallback);

      //fetches ssid and pass 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
      if(!wifiManager.autoConnect()) {
        Serial.println("failed to connect and hit timeout");
        //reset and try again, or maybe put it to deep sleep
        ESP.reset();
        delay(1000);
      }

      //if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");

    }

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

    }