body:
In code attached below I am using tftlcd display of 2.4 inch in which i want to show clock as home page, when user click on tftlcd screen then a screen appears which can show three options to user which are about the sensors user want to use. There are three sensors in this code: Pulse oximeter, glucose meter, pedometer. After choosing some option(sensor) the data of sensor will appear on screen.
I have write code for all this procedure which is given below:

    //include all libraries
    #include <Wire.h>
    #include <SPFD5408_Adafruit_GFX.h>
    #include <SPFD5408_Adafruit_TFTLCD.h>
    #include <SPFD5408_TouchScreen.h>
    #include "MAX30105.h"
    #include "spo2_algorithm.h"

    //Exit buttons
    bool backsensed = false;
    bool resetsensed = false;

    //Include Max30102 lib
    MAX30105 particleSensor;

    //Define LCD pins
    #define YP A1  // must be an analog pin, use "An" notation!
    #define XM A2  // must be an analog pin, use "An" notation!
    #define YM 7   // can be a digital pin
    #define XP 6   // can be a digital pin

    //pedometer
    const int xpin = A3;
    const int ypin = A4;
    const int zpin = A5;
    byte p[8] = {0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F
    };
    float threshold = 100;
    float xval[100] = {0};
    float yval[100] = {0};
    float zval[100] = {0};
    float xavg, yavg, zavg;
    int steps, flag = 0;
    //pulseoxi
    #define MAX_BRIGHTNESS 255
    #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    uint16_t irBuffer[100]; //infrared LED sensor data
    uint16_t redBuffer[100];  //red LED sensor data
    #else
    uint32_t irBuffer[100]; //infrared LED sensor data
    uint32_t redBuffer[100];  //red LED sensor data
    #endif
    int32_t bufferLength; //data length
    int32_t spo2; //SPO2 value
    int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
    int32_t heartRate; //heart rate value
    int8_t validHeartRate; //indicator to show if the heart rate calculation is valid
    byte pulseLED = 11; //Must be on PWM pin
    byte readLED = 13; //Blinks with each data read

    // LCD Calibrate values
    #define TS_MINX 100
    #define TS_MINY 120
    #define TS_MAXX 920
    #define TS_MAXY 940

    // For better pressure precision, we need to know the resistance between X+ and X- Use any multimeter to read it
    // For the one we're using, its 300 ohms across the X plate
    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

    #define LCD_CS A3
    #define LCD_CD A2
    #define LCD_WR A1
    #define LCD_RD A0
    #define LCD_RESET A4

    Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

    int BLUE = tft.color565(50, 50, 255);
    #define TFT_BLACK   0x0000
    #define TFT_DARKBLUE 0x0010
    #define VIOLET 0x8888
    #define TFT_RED     0xF800
    #define TFT_GREEN   0x07E0
    #define TFT_CYAN    0x07FF
    #define TFT_MAGENTA 0xF81F
    #define TFT_YELLOW  0xFFE0
    #define TFT_WHITE   0xFFFF
    #define TFT_GREY    0x5AEB
    #define TFT_BLUE    0x001F
    #define GOLD 0xFEA0
    #define BROWN 0xA145
    #define SILVER 0xC618
    #define LIME 0x07E0
    #define BLUE  0x001F

    //button screen
    int currentpcolour;
    int currentpage;
    bool running;

    //Minimum and maximum pressure to sense the touch
    #define MINPRESSURE 10
    #define MAXPRESSURE 1000

    //clock
    float sx = 0, sy = 1, mx = 1, my = 0, hx = -1, hy = 0;
    float sdeg = 0, mdeg = 0, hdeg = 0;
    uint16_t osx = 120, osy = 120, omx = 120, omy = 120, ohx = 120, ohy = 120;
    int16_t x0 = 0, x1 = 0, yy0 = 0, yy1 = 0, x00 = 0, yy00 = 0;
    uint32_t targetTime = 0;
    uint16_t xpos;
    uint8_t conv2d(const char* p) {
      uint8_t v = 0;
      if ('0' <= *p && *p <= '9')
        v = *p - '0';
      return 10 * v + *++p - '0';
    }
    uint8_t hh = conv2d(__TIME__), mm = conv2d(__TIME__ + 3), ss = conv2d(__TIME__ + 6);
    boolean initial = 1;
    char d;

    //for buttons
    void drawHome()
    {
      tft.fillScreen(TFT_BLACK);
      tft.drawRoundRect(0, 0, 319, 240, 8, TFT_YELLOW);     //Page border

      tft.fillRoundRect(60, 180, 200, 40, 8, TFT_DARKBLUE);
      tft.drawRoundRect(60, 180, 200, 40, 8, TFT_YELLOW);  //PEDO

      tft.fillRoundRect(60, 130, 200, 40, 8, TFT_DARKBLUE);   //Glu
      tft.drawRoundRect(60, 130, 200, 40, 8, TFT_YELLOW);

      tft.fillRoundRect(60, 80, 200, 40, 8, TFT_DARKBLUE);
      tft.drawRoundRect(60, 80, 200, 40, 8, TFT_YELLOW); //Pulse oxi and heart rate

      tft.setCursor(25, 20);
      tft.setTextSize(3);
      tft.setTextColor(TFT_WHITE);
      tft.print("Welcome Here..");
      tft.setCursor(25, 50);
      tft.setTextSize(2);
      tft.setTextColor(TFT_YELLOW);
      tft.print("Choose Your Sensor");
      tft.setTextColor(TFT_WHITE);
      tft.setCursor(110, 195);
      tft.print("Pedometer");

      tft.setCursor(80, 145);
      tft.print("Glucose Sensor");

      tft.setCursor(80, 95);
      tft.print("Pulse Oximeter");
      //  delay(500);

      }

      void setup()
    {
      tft.reset();
      tft.begin(0x9341);
      tft.setRotation(1);
      currentpage = 0; //clock page
      tft.setTextColor(TFT_WHITE);// text color
      tft.fillScreen(TFT_BLACK);// background color

      xpos = tft.width() / 2;
      tft.drawCircle(xpos, 120, 125, TFT_YELLOW);
      tft.fillCircle(xpos, 120, 118, TFT_BLUE);
      tft.fillCircle(xpos, 120, 110, TFT_BLACK);
      for (int a=95; a<104; a++){
      tft.drawCircle(xpos, 120, a, TFT_WHITE);}

      for (int i = 0; i < 360; i += 30) {
        sx = cos((i - 90) * 0.0174532925);
        sy = sin((i - 90) * 0.0174532925);
        x0 = sx * 114 + xpos;
        yy0 = sy * 114 + 120;
        x1 = sx * 100 + xpos;
        yy1 = sy * 100 + 120;
        tft.drawLine(x0, yy0, x1, yy1, TFT_YELLOW);
      }
      for (int i = 0; i < 360; i += 6) {
        sx = cos((i - 90) * 0.0174532925);
        sy = sin((i - 90) * 0.0174532925);
        x0 = sx * 102 + xpos;
        yy0 = sy * 102 + 120;
        x00 = sx * 92 + xpos;
        yy00 = sy * 92 + 120;
        // Draw minute markers
        tft.drawPixel(x0, yy0, TFT_GREEN);
        tft.drawLine(x0, yy0, x00, yy00, TFT_BLACK);
        tft.drawLine(x0+1, yy0+1, x00+1, yy00+1, TFT_BLACK);
        // Draw main quadrant dots
        if (i == 0 || i == 180) tft.fillCircle(x0, yy0, 2, TFT_WHITE);
        if (i == 90 || i == 270) tft.fillCircle(x0, yy0, 2, TFT_WHITE);
      }
      tft.fillCircle(xpos, 121, 3, TFT_WHITE);
      targetTime = millis() + 1000;
      //touch event
      tft.setCursor (80, 250);
      tft.setTextSize (1);
      tft.setTextColor(TFT_BLACK);
      tft.println("Touch to proceed");
      waitOneTouch(); // Wait touch
      drawHome(); //buttons screeen
    }

    void loop(){
      if (currentpage == 0){
      if (targetTime < millis()) {             //clock code
        targetTime = millis() + 1000;
        ss++;
        if (ss == 60) {
          ss = 0;
          mm++;
          if (mm > 59) {
            mm = 0;
            hh++;
            if (hh > 23) {
              hh = 0;
            }
          }
        }
        sdeg = ss * 6;                     // 0-59 -> 0-354
        mdeg = mm * 6 + sdeg * 0.01666667; // 0-59 -> 0-360 - includes seconds, but these increments are not used
        hdeg = hh * 30 + mdeg * 0.0833333; // 0-11 -> 0-360 - includes minutes and seconds, but these increments are not used
        hx = cos((hdeg - 90) * 0.0174532925);
        hy = sin((hdeg - 90) * 0.0174532925);
        mx = cos((mdeg - 90) * 0.0174532925);
        my = sin((mdeg - 90) * 0.0174532925);
        sx = cos((sdeg - 90) * 0.0174532925);
        sy = sin((sdeg - 90) * 0.0174532925);
        if (ss == 0 || initial) {
          initial = 0;
          // Erase hour and minute hand positions every minute
          tft.drawLine(ohx, ohy, xpos, 121, TFT_BLACK);
          ohx = hx * 62 + xpos + 1;
          ohy = hy * 62 + 121;
          tft.drawLine(omx, omy, xpos, 121, TFT_BLACK);
          omx = mx * 84 + xpos;
          omy = my * 84 + 121;
        }
        // Redraw new hand positions, hour and minute hands not erased here to avoid flicker
        tft.drawLine(osx, osy, xpos, 121, TFT_BLACK);
        osx = sx * 90 + xpos + 1;
        osy = sy * 90 + 121;
        tft.drawLine(osx, osy, xpos, 121, TFT_RED);
        tft.drawLine(ohx, ohy, xpos, 121, TFT_CYAN);
        tft.drawLine(omx, omy, xpos, 121, TFT_WHITE);
        tft.drawLine(osx, osy, xpos, 121, TFT_RED);
        tft.fillCircle(xpos, 121, 3, TFT_RED);
        tft.setCursor(xpos-30, 50);
        tft.setTextSize(2);
        tft.print("Glucoxy");

      // Draw MINI clock face "SECOND"
      tft.drawCircle(xpos, 155, 20, TFT_YELLOW);
      tft.drawCircle(xpos, 155, 18, TFT_BLUE);
      tft.drawCircle(xpos, 155, 17, TFT_CYAN);
      tft.drawCircle(xpos, 155, 16, TFT_CYAN);
      tft.fillRect(xpos-10, 149,22,15,TFT_BLACK); //erase
      if(ss<10){tft.setCursor(xpos-10, 149); tft.setTextSize(2);
      tft.print('0'); tft.setCursor(xpos+2, 149);}
      else{
      tft.setCursor(xpos-10, 149);}
      tft.setTextSize(2);
      tft.print(ss);
      // Draw MINI clock face "Minutes"
      tft.drawCircle(xpos+35, 117, 20, TFT_YELLOW);
      tft.drawCircle(xpos+35, 117, 18, TFT_BLUE);
      tft.drawCircle(xpos+35, 117, 17, TFT_CYAN);
      tft.drawCircle(xpos+35, 117, 16, TFT_CYAN);
     tft.fillRect(xpos+25, 111,22,15,TFT_BLACK); //erase
      if(mm<10){tft.setCursor(xpos+25, 111); tft.setTextSize(2);
      tft.print('0'); tft.setCursor(xpos+37, 111);}
      else{
      tft.setCursor(xpos+25, 111);}
      tft.println(mm);
      // Draw MINI clock face "Hour"
      tft.drawCircle(xpos-35, 117, 20, TFT_YELLOW);
      tft.drawCircle(xpos-35, 117, 18, TFT_BLUE);
      tft.drawCircle(xpos-35, 117, 17, TFT_CYAN);
      tft.drawCircle(xpos-35, 117, 16, TFT_CYAN);
      tft.fillRect(xpos-45, 111,22,15,TFT_BLACK); //erase
      if(hh<10){tft.setCursor(xpos-45, 111); tft.setTextSize(2);
      tft.print('0'); tft.setCursor(xpos-33, 111);}
      else{
      tft.setCursor(xpos-45, 111);}
      tft.setTextSize(2);
      tft.print(hh);
      //tft.setCursor(xpos-65, 111);
      //tft.println(':');
      if (hh>=0 && hh<12) d='A'; else {d='P';}
      tft.drawRoundRect(xpos-14,72,29,21,5,TFT_CYAN);
      tft.fillRect(xpos-11, 75,23,15,TFT_BLACK); //erase
      tft.setCursor(xpos-11, 75);
      tft.setTextSize(2);
      tft.print(d);
      tft.println('M');
      }
      }
      //home page
      if (currentpage == 1){
      digitalWrite(13, HIGH);
      TSPoint p = ts.getPoint();     // Read touchscreen
      digitalWrite(13, LOW);
      pinMode(XM, OUTPUT);
      pinMode(YP, OUTPUT);
      {if (p.z > 10 && p.z < 1000)
        {
          if (p.x > 736 && p.x < 855 && p.y > 255 && p.y < 725  && p.z > MINPRESSURE && p.z < MAXPRESSURE)
          {
            Serial.println("Pedometer");
            tft.fillRoundRect(60, 180, 200, 40, 8, TFT_WHITE);
            delay(70);
            tft.fillRoundRect(60, 180, 200, 40, 8, TFT_WHITE);
            tft.drawRoundRect(60, 180, 200, 40, 8, TFT_YELLOW);
            tft.setCursor(65, 195);
            tft.println("  Pedometer");
            delay(70);
            currentpage = 2;
            startPedo();
          }
          else if (p.x > 563 && p.x < 683 && p.y > 275 && p.y < 750)
          {
            Serial.println("Glucose Sensor");

            tft.fillRoundRect(60, 130, 200, 40, 8, TFT_WHITE);   //rgb led
            delay(70);
            tft.fillRoundRect(60, 130, 200, 40, 8, TFT_WHITE);   //rgb led
            tft.drawRoundRect(60, 130, 200, 40, 8, TFT_YELLOW);   //rgb led
            tft.setCursor(105, 145);
            tft.print("Glucose Sensor");
            delay(70);
            currentpage = 3;
            startGlu();
          }
          if (p.x > 403 && p.x < 525 && p.y > 271 && p.y < 725)
          {
            Serial.println("Pulse Oximeter");
            currentpage = 4;
            tft.fillRoundRect(60, 80, 200, 40, 8, TFT_WHITE);
            delay(70);
            tft.fillRoundRect(60, 80, 200, 40, 8, TFT_WHITE);
            tft.drawRoundRect(60, 80, 200, 40, 8, TFT_YELLOW);
            tft.setCursor(80, 95);
            tft.print("Pulse Oximeter");
            delay(70);
           // startPulse();

          }
        }
      }
      if (currentpage == 2) //pedo
      {
        senseBack();
        if (backsensed)
        {
          currentpage = 1;
          drawHome();
        }
        sensereset();
        calibrate();
      }
      if (currentpage == 3) // glucose
      {
         senseBack();
         if (backsensed)
         {
          currentpage = 0;
          drawHome();
         }
        sensereset();
      }

      if (currentpage == 4)  //pulse oxi
      {
        senseBack();
         if (backsensed)
         {
          currentpage = 1;
          drawHome();
         }
        sensereset();
        pinMode(pulseLED, OUTPUT);
      pinMode(readLED, OUTPUT);
      if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed  // Initialize sensor
      {
        Serial.println(F("MAX30105 was not found. Please check wiring/power."));
        while (1);
      }
      Serial.println(F("Attach sensor to finger with rubber band. Press any key to start conversion"));
      while (Serial.available() == 0) ; //wait until user presses a key
      Serial.read();
      byte ledBrightness = 60; //Options: 0=Off to 255=50mA
      byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
      byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
      byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
      int pulseWidth = 411; //Options: 69, 118, 215, 411
      int adcRange = 4096; //Options: 2048, 4096, 8192, 16384
      particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings
      startPulse();
      }
    }

    }
    // Wait one touch
    TSPoint waitOneTouch() {
      TSPoint p;
      do {
        p= ts.getPoint();
        pinMode(XM, OUTPUT); //Pins configures again for TFT control
        pinMode(YP, OUTPUT);
      } while((p.z < MINPRESSURE )|| (p.z > MAXPRESSURE));
      return p;
    }
    void sensereset()
    {
      digitalWrite(13, HIGH);
      TSPoint p = ts.getPoint();     // Read touchscreen
      digitalWrite(13, LOW);
      pinMode(XM, OUTPUT);
      pinMode(YP, OUTPUT);
      if (p.x < 199 && p.y < 293 && !running)
        resetsensed = true;
      else
        resetsensed = false;
    }
    void startPedo()        //-------------------pedometer function--------------------------
    {
      int acc = 0;
      float totvect[100] = {0};
      float totave[100] = {0};
      float xaccl[100] = {0};
      float yaccl[100] = {0};
      float zaccl[100] = {0};
      for (int a = 0; a < 100; a++)
      {
        xaccl[a] = float(analogRead(xpin) - 345);
        delay(1);
        yaccl[a] = float(analogRead(ypin) - 346);
        delay(1);
        zaccl[a] = float(analogRead(zpin) - 416);
        delay(1);
        totvect[a] = sqrt(((xaccl[a] - xavg) * (xaccl[a] - xavg)) + ((yaccl[a] - yavg) * (yaccl[a] - yavg)) + ((zval[a] - zavg) * (zval[a] - zavg)));
        totave[a] = (totvect[a] + totvect[a - 1]) / 2 ;
        Serial.println("totave[a]");
        Serial.println(totave[a]);
        delay(100);
        if (totave[a] > threshold && flag == 0)
        {
          steps = steps + 1;
          flag = 1;
        }
        else if (totave[a] > threshold && flag == 1)
        {
          // Don't Count
        }
        if (totave[a] < threshold   && flag == 1)
        {
          flag = 0;
        }
        if (steps < 0) {
          steps = 0;
        }
        Serial.println('\n');
        Serial.print("steps: ");
        Serial.println(steps);
        delay(1000);
      }
      delay(1000);
      //print results on lcd
      tft.setCursor(130, 145);
      tft.setTextSize(3);
      tft.setTextColor(TFT_WHITE);
      tft.print(steps);

      }
    void calibrate()            //<----------------------calibrate funtion--------------------->
    {
      float sum = 0;
      float sum1 = 0;
      float sum2 = 0;
      for (int i = 0; i < 100; i++) {
        xval[i] = float(analogRead(xpin) - 345);
        sum = xval[i] + sum;
      }
      delay(100);
      xavg = sum / 100.0;
      Serial.println(xavg);
      for (int j = 0; j < 100; j++)
      {
        yval[j] = float(analogRead(ypin) - 346);
        sum1 = yval[j] + sum1;
      }
      yavg = sum1 / 100.0;
      Serial.println(yavg);
      delay(100);
      for (int q = 0; q < 100; q++)
      {
        zval[q] = float(analogRead(zpin) - 416);
        sum2 = zval[q] + sum2;
      }
      zavg = sum2 / 100.0;
      delay(100);
      Serial.println(zavg);
    }
    void senseBack()
    {
      digitalWrite(13, HIGH);
      TSPoint p = ts.getPoint();     // Read touchscreen
      digitalWrite(13, LOW);

      pinMode(XM, OUTPUT);
      pinMode(YP, OUTPUT);
      if (p.y < 305 && p.x < 285 && p.x > 239 && !running)
      {
        backsensed = true;

      }
      else
        backsensed = false;
    }
    void startGlu()                 //-------------------------------startGlu-------------------------
    {
      }
    void startPulse()             //--------------------------------startpulse-----------------------
    {
      bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps

      //read the first 100 samples, and determine the signal range
      for (byte i = 0 ; i < bufferLength ; i++)
      {
        while (particleSensor.available() == false) //do we have new data?
          particleSensor.check(); //Check the sensor for new data
        redBuffer[i] = particleSensor.getRed();
        irBuffer[i] = particleSensor.getIR();
        particleSensor.nextSample(); //We're finished with this sample so move to next sample
        Serial.print(F("red="));
        Serial.print(redBuffer[i], DEC);
        Serial.print(F(", ir="));
        Serial.println(irBuffer[i], DEC);
      }
      //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
      maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
      //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
      while (1)
      {
        //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
        for (byte i = 25; i < 100; i++)
        {
          redBuffer[i - 25] = redBuffer[i];
          irBuffer[i - 25] = irBuffer[i];
        }
        //take 25 sets of samples before calculating the heart rate.
        for (byte i = 75; i < 100; i++)
        {
          while (particleSensor.available() == false) //do we have new data?
            particleSensor.check(); //Check the sensor for new data
          digitalWrite(readLED, !digitalRead(readLED)); //Blink onboard LED with every data read
          redBuffer[i] = particleSensor.getRed();
          irBuffer[i] = particleSensor.getIR();
          particleSensor.nextSample(); //We're finished with this sample so move to next sample
          //send samples and calculation result to terminal program through UART
          Serial.print(F("red="));
          Serial.print(redBuffer[i], DEC);
          Serial.print(F(", ir="));
          Serial.print(irBuffer[i], DEC);
          Serial.print(F(", HR="));
          Serial.print(heartRate, DEC);
          Serial.print(F(", HRvalid="));
          Serial.print(validHeartRate, DEC);
          Serial.print(F(", SPO2="));
          Serial.print(spo2, DEC);
          Serial.print(F(", SPO2Valid="));
          Serial.println(validSPO2, DEC);
        }

        //After gathering 25 new samples recalculate HR and SP02
        maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
        //print results on lcd
        tft.setCursor(130,145);
      tft.setTextSize(3);
      tft.setTextColor(TFT_WHITE);
      tft.print(heartRate);

      }

    }
Please see above code whether it works perfect as i want. I am getting error when i try to compile this code which is given below
[![enter image description here][1]][1]

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

My questions are:
1. whether this code is right, if not then point out my mistakes.
2. Solution of error shown in image.

title: Arduino Uno with Sensor, Bluetooth Module and tftlcd

Answers: 3

body:
The Arduino Uno doesn't have enough SRAM, the current Rev3 has just 2 KB. You can circumvent that by using less variables, use `#define xpin` instead of `const int`, etc.
[Here][1] is an article about how to reduce memory usage, give it a try.

Another option is to use a different Microcontroller with more SRAM, with at least 3KB like a Arduino Mega, ESP32. But first try to optimize your program, if you don't have another unused board lying around anyway.

**EDIT:**

You might also take a look at the header files if you can optimize anything there.

  [1]: https://create.arduino.cc/projecthub/john-bradnam/reducing-your-memory-usage-26ca05

body:
Arduino Mega has **8192 bytes** of SRAM which will solve your problem.

Reduce the RAM usage ([ref][1])

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

  [1]: https://arduinojson.org/v6/how-to/reduce-memory-usage/
  [2]: https://i.stack.imgur.com/4Pn8B.png

body:
Look [at this post][1], where I have implement the clock using a tft touch-enabled screen, with touch-enabled choice boxes for setting the time.  I used a Teensy 3.2, which handles the memory requirements nicely.  From the compile report

    Compiling 'Teensy_LCDClockV4' for 'Teensy 3.2 / 3.1'
    Using previously compiled file: C:\Users\Frank\AppData\Local\Temp\VMBuilds\Teensy_LCDClockV4\teensy31\Release\pch\Arduino.h.gch
    Program size: 117,320 bytes (used 45% of a 262,144 byte maximum) (4.14 secs)
    Minimum Memory Usage: 5936 bytes (9% of a 65536 byte maximum)

So you might have some trouble fitting it into a typical Arduino board

  [1]: https://www.fpaynter.com/2021/02/digital-clock-project/


body: I am trying to get both a SPI LED matrix display and an NRF24L01 to both work on the same Arduino Pro Micro. I know they both want to use the clock pin but how do I get them to share? Can I use the CS pin to turn off one device while trying to use the other? The display does can be set only when something needs to change so it's not always running.

title: Sharing clock pin on Pro Micro

Answers: 1

body:
It is indeed possible and supported to use [different CS (chip select) or SS (“slave select”) lines to address individual SPI devices on a single bus](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Independent_slave_configuration) run by an SPI “master”.

[![SPI three slaves on single bus][1]][1]
*Image from Wikipedia*

Many SPI TFT Touch displays need this to address the display controller and the touch controller as individual SPI devices and/or an integrated SD Card interface (wich also uses SPI).

The MOSI, MISO and SCLK lines can be reused and shared between perpiheral devices, as long as only one device is actively being addressed at any point in time. I.e. only one SS/CS may be active at any time and the software must support such sharing of SPI resources.

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


body:
I am currently experimenting with two MPU6050 which the AD0 is connected via PIN 7 and PIN 8 respectively, and if this is working, I plan to add another 2 more MPU6050 to it.

I am using i2cdevlib's MPU6050 library and what I did in a flow is:

 1. Initialize one MPU6050 object
 2. Set MPU6050 Object as 0x68 (LOW AD0)
 3. Set all to HIGH, but one to LOW (to select the MPU6050)
 4. Calculate offset and calibrate, store everything in array. (offsets and etc)
 5. Repeat steps 3 to 4 unless all are calibrated.
 6. Start to loop between two MPU, setting everything to HIGH and the one to be used as low.
 7. Write the LOW's (current selected) MPU with offset that is stored in array, then getMotion6 (Raw data).
 8. Write selected MPU to high, repeat from step 6 to step 7.

Everything is working, however when I am having a loop to collect data, it gives me corrupted data, the problem I find is in this function

```
void loop{
    for (int i = 7; i <= 8; i++) {
      pinMode(i, OUTPUT);

      digitalWrite( i, LOW);
      //      Serial.print("\nWriting pin: ");
      //      Serial.print(i);
      //      Serial.println(" to LOW");
      delay(2);
      int index = i - 7;
      Serial.print("Offsets:\t");
      Serial.print(ax_offset[index]);
      Serial.print("\t");
      Serial.print(ay_offset[index]);
      Serial.print("\t");
      Serial.print(az_offset[index]);
      Serial.print("\t");
      Serial.print(gx_offset[index]);
      Serial.print("\t");
      Serial.print(gy_offset[index]);
      Serial.print("\t");
      Serial.println(gz_offset[index]);

      accelgyro.setXAccelOffset(ax_offset[index]);
      accelgyro.setYAccelOffset(ay_offset[index]);
      accelgyro.setZAccelOffset(az_offset[index]);
      accelgyro.setXGyroOffset(gx_offset[index]);
      accelgyro.setYGyroOffset(gy_offset[index]);
      accelgyro.setZGyroOffset(gz_offset[index]);

      Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t");
      Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t");
      Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t");
      Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t");
      Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t");
      Serial.print(accelgyro.getZGyroOffset()); Serial.println("\t");

      //      delay(1000);
      //      accelgyro.getMotion6(&ax[index], &ay[index], &az[index], &gx[index], &gy[index], &gz[index]);
      int ax, ay, az, gx, gy, gz;
      accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

      Serial.print("PIN ");
      Serial.print(i);
      Serial.print("'s data is:");
      Serial.print("aX:" ); Serial.print(ax); Serial.print("\t");
      Serial.print("aY:" ); Serial.print(ay); Serial.print("\t");
      Serial.print("aZ:" ); Serial.print(az); Serial.print("\t");

      Serial.print("gX:" ); Serial.print(gx); Serial.print("\t");
      Serial.print("gY:" ); Serial.print(gy); Serial.print("\t");
      Serial.print("gZ:" ); Serial.println(gz);

      pinMode(i, INPUT_PULLUP);
    }
}
```

The first few loops will return accurate data (as in, all the sensors are close 0 [no motion])

I am suspecting because there is a huge difference between both sensors and the getMotion6 is comparing with the old sensor, can that be the case?

Attached is the output of my sensors reading, untouched.

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

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

title: Arduino MPU6050 AD0 Tricks with offset setting gives corrupted data

Answers: 0


body:
I'm using  **[botletics / SIM7000-LTE-Shield][1]** with Arduino Uno, I selected all examples but all end up with the same Error

    C:\Users\lenovo\Documents\Arduino\libraries\SIM7000\Adafruit_FONA.cpp: In member function 'boolean Adafruit_FONA::postData(const char*, uint16_t, const char*, const char*, const char*)':
    C:\Users\lenovo\Documents\Arduino\libraries\SIM7000\Adafruit_FONA.cpp:2045:3: error: expected ';' before 'readline'
    readline(10000);
    ^~~~~~~~
    exit status 1
    Error compiling for board Arduino Uno.

  [1]: https://github.com/botletics/SIM7000-LTE-Shield

title: Error compiling for board Arduino Uno SIM7000

Answers: 1

body:
I cloned botletics comparatively gigantic repo.  They've modified the Adafruit library without changing the name.

The problem appears to be that you are working out of the current master branch.  Switch to the latest tag, 1.1.0, and the SMS_Response example will compile just fine.  I didn't try all of the others.

[Direct link to the zip file for the 1.1.0 tag.][1]

  [1]: https://codeload.github.com/botletics/SIM7000-LTE-Shield/zip/1.1.0


body:
I'm working on a project where I'll need to establish a connection between two HC-05 modules, each connected to an Arduino, but for now I'm just trying to get one to work and connect to my phone, but I'm not sure if I'm doing anything right...

I'm not able to give AT-Commands, and as a result the device is not able to pair with my phone.
My setup looks something like this:

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

With minor differences being that I'm using an Uno board instead of a Mega, the RX and TX pins are connected to...well, I tried a lot of different pins, from the default RX/TX pins to specifying other pins like the ones in the code, as well as reversing the connections (RX to TX, TX to RX), also this schematic neglected to mention the 'ENABLE' pin, which I connected to my Arduino's 3,3V pin.

I tried a lot of different code samples, the latest one I tried is the following:
```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(38400);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}
```
Which I blatantly ripped-off from [this answer][2], with minor changes.

So, I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen, just an alternating sequence of the characters *'x'* and *'?'*, to my understanding that's actually the message *"Enter AT commands:"* written in my code...

Now, with this exact setup, I'm now actually receiving a response to my commands, except the response is also gibberish, this is as far as I've gotten.

EDIT: By following some of the comments and setting the Serial baud rate to 38400, I managed to get other Reponses to my commands, but it's just a new type of gibberish and it's still not actually responding to my commands.

The thing is, all of the tutorials I've seen online are contradicting each other, some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board, some don't bother with the ENABLE pin entirely, some don't use a voltage divider, some connect VCC pin to the 3,3V instead of the 5V, some even skip the AT-Command setup entirely!

One last detail I feel like I should mention, **there's a red light that blinks on and off every two seconds**, I believe that means the module is read to receive commands but I've seen contradicting information about this as well so I'm not sure.

I want to know what I'm doing wrong, and what's the right way to do this?

  [1]: https://i.stack.imgur.com/IIk7l.png
  [2]: https://arduino.stackexchange.com/a/53794/73186

title: HC-05 Module not receiving commands and not pairing

Answers: 1

body:
You have seen contradictory statements, because there are many variables here, that might be different for each of the tutorials.

> some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board

There are basically 2 ways to communicate between the Serial Monitor and the HC-05:

- You can connect the HC-05 directly to the USB Serial chip on the Arduino board, thus you would communicate directly with the HC-05. In that case the `TX` and `RX` pins are used, since they are connected to the USB Serial chip. But the labels `TX` and `RX` are referring to the Arduinos chip (Atmega328p at the Arduino Uno). Since serial connections need to be connected alternating (RX to TX and TX to RX), the pin labeled `TX` leads to the `RX` pin of the USB Serial chip and vice versa.

    Thus you would connect TX of HC-05 to the TX pin on the Arduino and RX of HC-05 (through the voltage divider) to the RX pin on the Arduino. Also you should program the Arduino with an empty sketch before doing that, so that the Arduino does not interfere in the Serial communication with its own Serial usage.

- Or you can use a `SoftwareSerial` interface and let the Arduino code translate between the devices. The Arduino received from the PC and sends the data to the HC-05. Also it receives from the HC-05 and sends that data to the PC. This is what you were trying. But you absolutely need to specify a different set of pins for the `SoftwareSerial` interface, than 0 and 1. These pins are doing the hardware Serial interface, which is connected to the PC. So change these pin numbers (for example to 2 and 3).

    In fact: Whenever you see a code for Uno, Nano or Mega using `SoftwareSerial` on pins 0 and 1, you can be sure, that it is garbage.

>  I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen

Even when you change the pins as described above, your code still uses 9600 baud for the connection to the PC. When you set the Serial Monitor to 38400 while the code uses 9600 baud for that interface, you will get just gibberish. Either change your Serial Monitor to 9600 baud or change your code to `Serial.begin(38400)`. The last option is better, since that makes sure, that you are using the same baudrate for both interfaces.

> some don't bother with the ENABLE pin entirely

The ENABLE pin seems to have a pulldown resistor on the HC-05 board, which pulls it to ground, when nothing is connected. Ground means data mode, HIGH command mode. So when they don't connect anything, they want to stay in data mode. Though this also depends on if the specific HC-05 board has a pulldown or pullup resistor there. Pulldown is more likely, but since there is no one single producer of these modules, you cannot be sure. Since you want to get into AT mode, you should use command mode and connect it to 3.3V. For normal operation it would go to ground. Though you can also connect it to a digital output pin of the Arduino and let the code decide in which mode the module should be.

> some don't use a voltage divider

The chip on the HC-05 board is a 3.3V device. The actual breakout boards, that can be bought everywhere, mostly only add a voltage regulator from 5V to 3.3V, an LED for status display and break out the necessary pins. The data pins are mostly directly connected to the chip. There are many resources, that claim the HC-05 to be 5V tolerant, but also many that antagonize that. To be sure not to destroy the HC-05, you should also use a voltage divider.

> some connect VCC pin to the 3,3V instead of the 5V

This is only done, when the used board does not have a 5V to 3.3V voltage regulator. Depends on the exact board, that you own.

> some even skip the AT-Command setup entirely!

When they don't need to configure the HC-05 in a special way, why would they go into command mode. That might be different for you.


body:
I have a teensy 4.1, and I am trying to install NUTTX the Real Time Operating System ( RTOS ). Teensy is a supported platform.
I am trying install nuttx compiled from source, and upload it using the [teensy loader program][1]. my current issue is that the hex file is too large. the file size is 229Kb, which shouldn't be an issue where the flash size for a teensy 4.1 is 8MB.

 I have been following the steps on these websites:
this one where [Nuttx is installed on a teensy 3][2], and the documentation for [nuttx on their website][3]

any tips or recommendations to install nuttx on a teensy 4.1 would be greatly appreciated.

[![nutt.hex file too large][4]][4]

  [1]: https://www.pjrc.com/teensy/loader_linux.html
  [2]: https://acassis.wordpress.com/2016/04/16/running-nuttx-on-teensy-3-1/
  [3]: https://nuttx.apache.org/docs/latest/quickstart/compiling.html
  [4]: https://i.stack.imgur.com/gqszO.png

title: nuttx hex too large

Answers: 1

body:
OK, so I pressed the reset button and the teensy loader program reset, and reloaded the hex file. Now it lists as I would expect it to, using 1% of the flash space. and uploads without error. [![enter image description here][1]][1]

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


body:
I'm converting a 0-5v PWM signal to an analog signal using an LM358D. I've connected the output to an oscilloscope to look at the signal but I'm not really sure what I'm looking at. The PWM looks ok but I'm unsure of the analog signal.

Here's some images, please let me know what you think.

Both pics are at 50% signal strength. The oscilloscope is set to defaults, simply connected the probe.

Thanks

![Text](https://i.ibb.co/PmJqFQ2/CAM02299.jpg)

![Text](https://i.ibb.co/P5pr78T/CAM02304.jpg)

**EDIT:**

Here's the schematic for the PWM to analog converter. The cap is a tantalum. The dip switch changes the analog from 5v to 10v, the signal looks the same on both and is correct voltage so seems to be ok?

![Text](https://i.ibb.co/w73sThS/pwm-to-analog.png)

title: PWM and Analog Signal Quality

Answers: 2

body:
Something like this should work:

[![PWM to analog circuit][1]][1]

With this code on a Uno:

    void setup () { }

    void loop () {
      analogWrite (3, analogRead (A0) / 4);
    }

For slightly more details see [my post about doing that](http://www.gammon.com.au/forum/bbshowpost.php?id=11395).

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

body:
> The PWM looks ok but I'm unsure of the analog signal.

The “analog signal” looks like the PWM smoothed by a first-order
low-pass filter. It still has some oscillations, 584 mV
peak-to-peak. If you can tolerate that, then it's perfectly fine. If
not, then increase the time constant of your filter.

A first-order low-pass filter behaves, in its stop band, like an
integrator. Thus, a square signal is turned into a triangle. You are
seeing exactly the expected behavior.

> The oscilloscope is set to defaults

There are no “default” settings in the oscilloscope. You probably used
the “autoset” button instead. This button tries to find some settings
that let you see _something_ on the screen. I mean, some kind of signal,
not just straight line. If the signal is almost flat, the autoset will
increase the gain until you can see it is not flat. In this case, it
increased the gain by a factor 10 (200 mV / division instead of
2 V used previously). It also added a negative offset in order to
avoid the trace going out of the screen. See the small pentagon on the
far left with a “1” inside? On the first picture this tells you where
the zero (the reference potential) is relative to your signal. On the
second picture, the polygon pointing at the bottom of the chart tells
you the zero is off-scale.

If you want to really appreciate the smoothing action of the filter, you
have to look at its input (the PWM signal) and its output (the “analog”
signal) using the exact same settings. Connect the input, hit “autoset”,
and look. Then connect the output, _do not_ change the settings (do not
hit “autoset”) and look at the output.

Better yet: forget the autoset button, adjust the settings manually and
mind their values.

Better yet: as you have a two channel scope, display _both_ signals
simultaneously, using the exact same settings on both channels.


body:
I am thinking to use Arduino to control a DC motor and apply a small torque to move the mirrors of my interferometer experiment. I have the components from the Arduino Starter Kit K000007, just to understand how it works because I am approaching it just now.

The mirror mount has a knob with a 2mm Hex hole and each revolution corresponds to a displacement of 50 microns: I would need a speed around 1/50 revolution/second, or even less. Is it possible to move the motor that slow?
Moreover, I should use a coupler to interface the motor with the knob, basically some joint to connect the shaft to a 2mm Hex bar or something: could you suggest a way to do so?

title: DC motor with slow speed to actuate mirrors

Answers: 1

body:
DC motors are made for spinning. Trying to spin it in sub full revolution steps is not really possible. But you can use a geared DC motor, where the rotor after the gear is slow enough for your purpose. Also this can give you enough torque for moving the knob (since small DC motors are often rather weak by their own). You can find geared DC motors with many different values (torque, voltage, speed, gear ratio, size...) at the typical online sellers. The small ones are rather cheap, so you might just buy some and test out, whats fitting for you. Otherwise you would need to set exact requirements for torque and speed (and maybe other parameters) and then search for a fitting one.

Also keep in mind, that you need something like a driver circuit for the motor. Since you will want to drive it in both directions, a H-bridge is needed. You can build those yourself with transistors, or buy a small chip, which incorporates the complete H-bridge (make sure to use one with MOSFETs in it, since they are more efficient). Also don't forget the flyback diode to avoid killing the electronics with the induction voltage from the motor.

> I should use a coupler to interface the motor with the knob, basically some joint to connect the shaft to a 2mm Hex bar or something: could you suggest a way to do so?

Yes, you need some kind of coupler. But we cannot really suggest something here. It depends totally on your exact setup. This mechanical part will be something, that you have to design. There are different kinds of couplers available online, but I don't know, if they are good for your purpose.

Also maybe you should make sure to make the coupler flexible on the other axes than the rotation axis. That way the motor will not stall when a small disalignment happens, and the vibrations from the motor might not get transmitted to your mirror as much. I know this principle from my 3D printer, which uses a coupler like this one:

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

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


body:
So i connected my ublox neo 6m gps breakout board GY-GPS6MV2 to the arduino software serial and got this result, i used resistors and only supplied 3.3v to the board, gps encode library couldn't give me anything out of this. if possible please help and if this is the wrong forum please suggest a better one. also the board thinks that the date for some reason is Mar 17 2011 16:18:34*59. which is pretty wierd.

 ```

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$GPTXT,01,01,02,ANTSUPERV=AC SD PDoS SR*20

$GPTXT,01,01,02,ANTSTATUS=DONTKNOW*33

$GPRMC,,V,,,,,,,,,,N*53

$GPVTG,,,,,,,,,N*3⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$GPTXT,01,01,02,ANTSUPERV=AC SD PDoS SR*20

$GPTXT,01,01,02,ANTSTATUS=DONTKNOW*33

$GPRMC,,V,,,,,,,,,,N*53

$GPVTG,,,,,,,,,N*3⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 F⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$⸮$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

$GPTXT,01,01,02,HW UBX-G60xx 00040007 FFF9FFFFp*5D

$GPTXT,01,01,02,ROM CORE 7.03 (45969) Mar 17 2011 16:18:34*59

$GPTXT,01,01,02,ANTSUPERV=AC SD PDoS SR*20

$GPTXT,01,01,02,ANTSTATUS=DONTKNOW*33

$GPRMC,,V,,,,,,,,,,N*53

$GPVTG,,,,,,,,,N*30

$GPGGA,,,,,,0,00,99.99,,,,,,*48

$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30

$GPGSV,1,1,00*79

$GPGLL,,,,,,V,N*64

$GPTXT,01,01,02,u-blox ag - www.u-blox.com*50

 ```
**Here is the full unedited output after 40 mins**
https://drive.google.com/file/d/148W_6shE0U2lprimApvtvG1i3Vf2-Izx/view?usp=sharing

edit:- i also connected the tx pin to the rx and vice versa and used a resistor as told by an tutorial on the tx pin from the arduino or the rx pin of the board. it is also sending many gptxt messages which some say on other forums are usally send when some error occurs or the board restarts. idk why it is coming on my board.

title: Neo 6m outputting something i as a noob can't understand

Answers: 1

body:
someone on ublox portal recommended me to connect the boards vcc to 5v's and when i did that, it stopped rebooting, and after 20 mins got a lock, thanks for your help.

the guy on ublox portal

> Post a photo of the board and a link of where you bought it so that we can point out that 5V is needed.
The reboot symptom is usually caused by an inadequate voltage source --- when the 6m starts, current draw is low, when it finishes initial startup, it goes to work looking for sats and current draw jumps up. The higher current draw on a poor power source causes supply voltage to drop too.low which then causes the 6m to reset and restart and will happily repeat the cycle forever.
Use a good DVM or oscilloscope to verify the inadequate voltage source.

after connecting the board to 5v supply the problem seemed to be fixed


body:
I am working in a project in which I need to control at the same time three NEMA17 stepper motors. In order to do so, I am using three DRV8825 drivers working at 12V connected to an Arduino MEGA.

This Arduino is generating the pulses in velocity ramps so that we have an accelerated movement to reach the goal.

The schematic I am using for connecting the drivers is the one that the manufacturer recommends:
[![enter image description here][1]][1]

With a digital analyzer, I can see that my velocity ramp is being generated properly:

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

In this picture below you can see how steps (ST) are generated once the direction (DR) is set for each of the motors. The time waiting after the direction change is bigger than the necessary established by the manufacturer and also does the duration of the step pulses.

Following this, the motors are supposed to make an accelerated movement until reaching a certain position and then, decelerate and stop.

Although, I am facing the problem that, in some cases, one of the motors (not always the same one) makes a few steps in the opposite direction of the movement and, after that, it executes the expected movement. This leads to, even of making the three motors perform the same movement, one of them finishes differently.

I tried to change the drivers but the same happens. Also, as I said before, I have checked that the pulses are correctly generated.

I would like to know if anyone has faced a similar problem or knows any reason that could lead to this strange behavior.

Thanks.

  [1]: https://i.stack.imgur.com/siqDp.png
  [2]: https://i.stack.imgur.com/AIR8i.png

title: Stepper Motors Strange Behaviour

Answers: 1

body:
So, apparently the motors I am using have a optimal work range that doesn't start at 0 but 200PPS. Though, even generating properly the velocity ramps, when using a low acceleration, my motors would be running for some steps outside this optimal range, causing strange movements at the beginning of the movement.

In order to solve it, these non-optimal low velocities are avoided while accelerating so that motors enter directly to the optimal work area.


body:
Do you have to build the circuit on an external board every time you decide there is a need
for a pull-up or pull-down circuit? If not, then what is the alternative and how can you use
it?

title: pull-up or pull-down

Answers: 1

body:
This depends on what you are doing.

The IO hardware of the Uno (more specific the Atmega328p, which is the used chip) has internal pullup resistors, that can be used, when the pin is configured as input. This can be done in one line:

    pinMode(pin_number, INPUT_PULLUP);

This is true for all AVR based chips.

Other, more complex and capable chips also have an internal pulldown resistor (as I remember this is true for the ESP32 for example). In this case you can do

    pinMode(pin_number, INPUT_PULLDOWN);

If you are using special hardware of the Arduino, it depends on the hardware itself, since in most cases the normal IO hardware is internally not connected to the pin, when using this hardware. For example: The internal pullup resistor will not be active, when doing an analog measurement with the ADC (like via `analogRead()`).


body:
Hey i'm trying to make an Arduino that can log key presses from a keypad and save that as a variable. When it receives information from another arduino via serial I want it to create a variable from each position (like comma separated values "/" in this case).Then if its being asked for its data by the master to transmit its string of data.

The code I have below is recording key presses, when it receives serial it puts it in to a string then looks at the first position in that string this becomes the variable RSVP, if RSVP is equal to the Arduinos address (iAm) and later if the checksum adds up, I would like it to respond with its serial string.
for some reason every serial command i send to it, it mirrors back the command i sent to it correctly but when i tell it to separate the first position in to the RSVP variable it always returns 1. Not sure if this is to do with converting characters to integers or something if that's all then hopefully an easy fix once you know how.

I have seen a few posts saying its best to use an array rather than a string (but this is based on the IDE serial example so not sure if that's correct)and presumable would need fully re writing which doesn't sound like an easy fix. Also I don't know how I would go about making an array from serial, and I might not to know how to separate CSVs I have seen a few examples but unfortunately i'm a dimwit. Been on this one problem for 3 days now and i'm still in exactly the same place, but with a slightly fried brain.

    #include <Keypad.h>

    String inputString = "";         // a String to hold incoming data
    bool stringComplete = false;  // whether the string is complete

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //three columns
    char keys[ROWS][COLS] = {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},

    };
    byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    int iAm = 1;                                    //this is device number 1
    float checkSum = 0.00;                          //check sum to send as serial
    float voltage = 5.26;                           //system voltage
    int data[20] {0, 0, 0, 0, 0, 0, 0, 0, 0};       //keypad output call
    char rsvp = 0;
    int rsvp1 = 0;
    void setup() {
      Serial.begin(9600);

      inputString.reserve(200);    // reserve 200 bytes for the inputString:
    }

    void loop() {

      int key = keypad.getKey();

      if (key) {
          int key1 = key -48;

          if (data[key1] == 1){
           data[key1] = 0;

          }
          else {
            data[key1] = 1;
          }

      }
        // print the string when a newline arrives:
      if (stringComplete)  {
        rsvp = inputString.charAt(0);
        rsvp1 = int(rsvp);

        if (rsvp1 = iAm) {
          checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
          Serial.print(inputString);
          Serial.println(rsvp1);
          Serial.print(iAm);
          Serial.print("/");
          Serial.print(data[1]);
          Serial.print("/");
          Serial.print(data[2]);
          Serial.print("/");
          Serial.print(data[3]);
          Serial.print("/");
          Serial.print(data[4]);
          Serial.print("/");
          Serial.print(data[5]);
          Serial.print("/");
          Serial.print(data[6]);
          Serial.print("/");
          Serial.print(data[7]);
          Serial.print("/");
          Serial.print(data[8]);
          Serial.print("/");
          Serial.print(data[9]);
          Serial.print("/");
          Serial.print(voltage);
          Serial.println("/");
          Serial.println(checkSum);
        // clear the string:
        inputString = "";
        stringComplete = false;
        }
      }
    }
    void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          stringComplete = true;
        }
      }
    }

    /*
      SerialEvent occurs whenever a new data comes in the hardware serial RX. This
      routine is run between each time loop() runs, so using delay inside loop can
      de
       if (Serial.available() > 0) {
        int recieved = Serial.read();
        if (recieved == iAm){
          checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
          Serial.print(iAm);
          Serial.print("/");
          Serial.print(data[1]);
          Serial.print("/");
          Serial.print(data[2]);
          Serial.print("/");
          Serial.print(data[3]);
          Serial.print("/");
          Serial.print(data[4]);
          Serial.print("/");
          Serial.print(data[5]);
          Serial.print("/");
          Serial.print(data[6]);
          Serial.print("/");
          Serial.print(data[7]);
          Serial.print("/");
          Serial.print(data[8]);
          Serial.print("/");
          Serial.print(data[9]);
          Serial.print("/");
          Serial.print(voltage);
          Serial.println("/");
          Serial.println(checkSum);
        }
       }
    }

title: processing data received via serial

Answers: 0


body:
I am attempting to make an Arduino counter using a 4 digit 7 segment display. The problem I am encountering is the display flickers. I am using an Arduino Uno and 5641AS digit display (so common cathode). Here is my program:

```
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
    Serial.println("The value of buttonPress is:  ");
    Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}
```

I suspect this issue has to do with `sevseg.refreshDisplay()`, I have tried moving it in the program with no avail. My wiring is correct, as the program displays the correct digits. Thank you!

title: 4 Digit 7 segment display flickering

Answers: 1

body:
With the help of Majenko and jsotola in the comments, I've got it fixed! It was the text I was displaying in the Serial Monitor that was slowing the display down. Here is the updated program that works:
```
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
// THE NEXT TWO LINES HAVE BEEN COMMENTED OUT FOR IT TO WORK
   // Serial.println("The value of buttonPress is:  ");
   // Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}
```
I'm leaving the program modifications here in case anyone else gets the same problem.


body:
Trying to control this LED with those 2 pushbuttons - one button that starts a short flashing sequence, another pushbutton acts like a toggle switch, one press bulb is on, another press bulb is off.

If I switch the LED on and then push the flashing button, the on-off flashing starts but then the LED is shut off because off is the last state of the flashing sequence. How do I make the led turn to original state?

    #include <ezButton.h>

    const int flashing_pin = 2;
    const int switch_pin = 3;
    const int led_pin = 8;

    ezButton button(switch_pin);

    int ledState = LOW;

    void setup() {
      Serial.begin(9600);
      pinMode(led_pin, OUTPUT);
      pinMode(switch_pin,INPUT_PULLUP);
      pinMode(flashing_pin,INPUT_PULLUP);
      button.setDebounceTime(50);
    }

    void loop() {
      button.loop();

      if(button.isPressed()) {
        Serial.println("Press");

        ledState = !ledState;

        digitalWrite(led_pin, ledState);
      }

      if( digitalRead(flashing_pin) == LOW )   {
        doFlash(4);
      }
    }

    void doFlash(uint8_t number_of_times)  {
      while(  number_of_times-- > 0 ) {
        digitalWrite(led_pin,HIGH);
        delay(250);
        digitalWrite(led_pin,LOW);
        delay(250);
      }

    }

To explain what I want in short;

- if LED is off - flashing sequence works like "ON OFF ON OFF"
- if LED is on - flashing sequence works like "OFF ON OFF ON"

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

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

title: Single LED controlled by two pushbuttons - one of which acts like a toggle switch

Answers: 0


body:
This is my first post. I seek you guys' help with my problem. Basically, my project is a Mobile-App Bluetooth Controlled WheelChair. Everything's done except a minor problem comes out during testing. After connecting everything, the wheelchair moves accordingly to the code that I wrote. However, after a few sec/min, the HC-05 drops connection, and the wheelchair drives its own by moving forward. I hope you can understand what I am saying.

When I set the speed = 100. I think I did not face the issue as above (confirmed).

Hardware:

PowerBank

Arduino Uno

HC 05

MDD20A Motor Driver

X2 24V DC Motor

X2 12V Battery

    //including the libraries
    #include <SoftwareSerial.h> // TX RX software library for bluetooth

    //Initializing pins for bluetooth Module
    int bluetoothTx = 0; // bluetooth tx to 0 pin
    int bluetoothRx = 1; // bluetooth rx to 1 pin
    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

    //Motor 1
    int Motor1_Pin = 2;
    int Enable1 = 3;

    //Motor 2
    int Motor2_Pin = 4;
    int Enable2 = 5;

    char command ; //variable to store the data
    int velocity = 0; //Variable to control the speed of motor

    void setup()
    {
      //Set the baud rate of serial communication and bluetooth module at same rate.
      // Serial Setup
      Serial.begin(9600); // default communication rate of the HC-06 Bluetooth module;
      bluetooth.begin(9600);

      // Motor Setup
      pinMode(Motor1_Pin,OUTPUT);
      pinMode(Enable1,OUTPUT);
      pinMode(Motor2_Pin,OUTPUT);
      pinMode(Enable2,OUTPUT);

      //Setting the enable as HIGH.
      digitalWrite(Enable1, LOW);
      digitalWrite(Enable2, LOW);
    }

    void loop(){
      if(bluetooth.available() > 0){  //Checking if there is some data available or not
        command = bluetooth.read();   //Storing the data in the 'command' variable
        Serial.println(command);      //Printing it on the serial monitor

        //Change pin mode only if new command is different from previous.
        switch(command){
        case 'F':  //Moving the Car Forward
          analogWrite(Enable1, 175);
          analogWrite(Enable2, 175);
          digitalWrite(Motor1_Pin, HIGH);
          digitalWrite(Motor2_Pin, HIGH);
          break;
        case 'B':  //Moving the Car Backward
          analogWrite(Enable1, 175);
          analogWrite(Enable2, 175);
          digitalWrite(Motor1_Pin, LOW);
          digitalWrite(Motor2_Pin, LOW);
          break;
        case 'L':  //Moving the Car Left
          analogWrite(Enable1, 175);
          analogWrite(Enable2, 100);
          digitalWrite(Motor1_Pin, HIGH);
          digitalWrite(Motor2_Pin, LOW);
          break;
        case 'R':   //Moving the Car Right
          analogWrite(Enable2, 175);
          analogWrite(Enable1, 100);
          digitalWrite(Motor2_Pin, HIGH);
          digitalWrite(Motor1_Pin, LOW);
          break;
        case 'S':   //Stop
          analogWrite(Enable1, 0);
          analogWrite(Enable2, 0);
          digitalWrite(Motor1_Pin, 0);
          digitalWrite(Motor2_Pin, 0);
          break;
    //    case 'I':  //Moving the Car Forward right
    //      digitalWrite(Motor2_Pin2, LOW);
    //      digitalWrite(Motor2_Pin1, LOW);
    //      analogWrite(enable1, 0);
    //      analogWrite(enable2, 0);
    //      break;
    //    case 'J':  //Moving the Car backward right
    //      digitalWrite(Motor2_Pin2, LOW);
    //      digitalWrite(Motor2_Pin1, LOW);
    //      analogWrite(enable1, 0);
    //      analogWrite(enable2, 0);
    //      break;
    //    case 'G':  //Moving the Car Forward left
    //      digitalWrite(Motor2_Pin2, LOW);
    //      digitalWrite(Motor2_Pin1, LOW);
    //      analogWrite(enable1, 0);
    //      analogWrite(enable2, 0);
    //      break;
    //    case 'H':  //Moving the Car backward left
    //      digitalWrite(Motor2_Pin2, LOW);
    //      digitalWrite(Motor2_Pin1, LOW);
    //      analogWrite(enable1, 0);
    //      analogWrite(enable2, 0);
    //      break;
        break;

        //Controlling the Speed of Car
        default:  //Get velocity
          if(command=='q'){
            velocity = 255;  //Full velocity
            analogWrite(Enable2, velocity);
            analogWrite(Enable1, velocity);
          }
          else{
            //Chars '0' - '9' have an integer equivalence of 48 - 57, accordingly.
            if((command >= 48) && (command <= 57)){
              //Subtracting 48 changes the range from 48-57 to 0-9.
              //Multiplying by 25 changes the range from 0-9 to 0-225.
              velocity = (command - 48)*25;
              analogWrite(Enable2, velocity);
              analogWrite(Enable1, velocity);
            }
          }
          }
        }

      }

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

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

title: HC-05 drops connection, then DC Motors won't stop moving 'forward'

Answers: 1

body:
I assume that you want the chair to stop if the connection is lost. Is the 'state' pin on your HC-05 implemented, and does it distinguish between connected and not-connected (or something else)? If it's the former you should be monitoring that state pin. Otherwise, your Arduino and the mobile app need to agree on an "Are you there?" protocol; a handshake that takes place every 0.5 sec or so (off the wall guess!), and if the chair controller hasn't got a response darn near immediately, it stops. If the mobile misses a response, it should send a 'stop' (a backup which might not be heard by the chair controller), and alert the operator.
It wouldn't be a half-bad idea to have a watchdog timer (in hardware) on the chair that stops the motors if the chair controller doesn't reset it on short intervals. The chair controller is software; software sometimes fails. You'd like to detect that in hardware in time to cut the drive to the chair before it hits an obstruction or drives into the street.


body:
I am trying to interface TGS 2600 gas sensor to Arduino, particularly to detect methane gas.
Can anyone tell me the conversion equation between Rs/Ro and ppm, so that I can get ppm values from the Rs/Ro ratio. I am looking to detect between 1-10ppm.

title: Interfacing Figaro TGS2600

Answers: 0


body:
I am trying write four digit number to SPIFFS file, and read that four digit from SPIFFS file and display on seven segment.

The code, I am writing as below, I got "0" on each segment, but if manually make number = 4567; then seven segment show proper number on every segment.

Please help me to learn more about how to read & write and convert to object data.

Here is my code;
```
#include <FS.h>

const char* filename = "/InputInt.txt";
int digit_1 = 0;
int digit_2 = 0;
int digit_3 = 0;
int digit_4 = 0;

int Anode_1 = 16;
int Anode_2 = 14;
int Anode_3 = 5;
int Anode_4 = 4;
int count = 0;
int digits[4] ;
int AnodePins[4] = {4, 5, 14, 16};

int clockPin = 12;
int latchPin = 13;
int dataPin = 15;

int number = 0; //declear the variables

byte numbers[10] {B00000011, B10011111, B00100101, B00001101, B10011001, B01001001, B01000001, B00011111, B00000001, B00001001};

void setup() {
  Serial.begin(115200);
  Serial.println();

  bool success = SPIFFS.begin();

  if (!success) {
    Serial.println("Error mounting the file system");
    return;
  }
  SPIFFS.format();
  File fw = SPIFFS.open(filename, "w");

  if (!fw) {
    Serial.println("Error opening file for writing");
    return;
  }
  char Written = fw.print("1234");

  if (Written == 0) {
    Serial.println("File write failed");
    return;
  }
  fw.close();

  pinMode(Anode_1, OUTPUT);
  pinMode(Anode_2, OUTPUT);
  pinMode(Anode_3, OUTPUT);
  pinMode(Anode_4, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

} //End of setup

void loop() {
  int i;
  File fr = SPIFFS.open(filename, "r");

  if (!fr) {
    Serial.println("Failed to open file for reading");
    return;
  }

  for (i = 0; i < 4; i++) {
    byte number = (Serial.write(fr.read()));
  }
  fr.close();
  break_number(number);
  display_number();
  delay(3000);
} // End of loop

// seperate the input number into 4 single digits
void break_number(int num) {
  Serial.println("");
  digit_1 = num / 1000;
  digits[0] = digit_1;
  Serial.print(" Digit_1: ");
  Serial.println(digit_1);
  int dig_1_remove = num - (digit_1 * 1000);

  digit_2 = dig_1_remove / 100;
  digits[1] = digit_2;
  Serial.print(" Digit_2: ");
  Serial.println(digit_2);
  int dig_2_remove = dig_1_remove - (digit_2 * 100);

  digit_3 = dig_2_remove / 10;
  digits[2] = digit_3;
  Serial.print(" Digit_3: ");
  Serial.println(digit_3);
  digit_4 = dig_2_remove - (digit_3 * 10);

  digits[3] = digit_4;
  Serial.print(" Digit_4: ");
  Serial.println(digit_4);
}

void display_number() {                                             //scanning
  digitalWrite(AnodePins[count], HIGH);                            //turn on the relevent digit
  digitalWrite(latchPin, LOW);                                      //put the shift register to read
  shiftOut(dataPin, clockPin, LSBFIRST, numbers[digits[count]]);    //send the data
  digitalWrite(latchPin, HIGH);                                     //put the shift register to write mode
  delay(0);
  digitalWrite(AnodePins[count], LOW);                            //turn on the relevent digit
  count++;                                                          //count up the digit
  if (count == 4) {                                                 // keep the count between 0-3
    count = 0;
  }
}
```
Here is the result;
```
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0
```
Thanks,

title: How to write & read from SPIFFS file as object data on ESP8266

Answers: 1

body:
I directly see 3 problems with your code:

1. `Serial.write()` will not return the written data, but the number of send bytes. This means that in your for loop you are only assigning the written number of bytes to the variable, not the data. But I guess you want to display the actual data, which was read from the file. You should assign the return value of `fr.read()` to a variable. Then you can send it via `Serial.write()` and still use that variable for other things later (like displaying).

2. You need to look into variable scope. You have a global variable `number`. But in the for loop you are defining a local variable with the same name via

        byte number = ...

    This variable is only valid in that specific for loop iteration. When the iteration ends, the variable is thrown away and redeclared in the next iteration. It will not be there anymore, when you leave the for loop. So currently you are saving your data in a variable local to the for loop. It does NOT touch the global variable. Thus the other functions only see the value zero, with which the global variable `number` was initialized. You can remove the type `byte` before the variable in the for loop. That makes it an assignment instead of a definition. Thus then you really write the data into the global variable.

3. Data encoding: Clearly you have your number in the file as ASCII encoded text. But you seem to handle it as binary data. That cannot work. For example: When you read the first character of `1234` (which is written in the file), then you get `'1'` (the character, not the number). When looking at an ASCII table you can see, that this character corresponds to a decimal number of 49 (or `0x31` in hex). You can convert an ASCII encoded digit to a real number by subtracting the value of the character `'0'`:

        int number = fr.read() - '0';

    or

        int number = fr.read() - 48;

    (both are equivalent).

    Also you are currently just saving the read character into a single variable. That means, that after the for loop only the last character is left. Since this is a composite number, you should do something to compose it. Like this:

        number = 0;
        int factor = 1000;
        for(int i = 0; i<4; i++){
            number += (fr.read() - '0') * factor;
            factor /= 10;
        }

    Note: This is untested, it is not the best way, but the easiest at this point, and it only works for numbers between 1000 and 9999 (4 digit numbers). You can implement this more versatile.

    First we are resetting the `number` variable, so that old values are not getting in our way. We are using a variable holding the current factor (starting with 1000, since that is the figure in which the first digit lies). Then we go through the 4 characters, reading them. We subtract the character `'0'` (as described above) and then multiply by the factor. That resulting number is added to the variable `number`. Then we divide the factor by 10 (getting from 1000 to 100, then to 10 and finally to 1). At the end we can use `number` like any other integer variable.

---

Alternative implementation of reading the number, which is suitable for different numbers of digits:

    number = 0;
    // Prepare character buffer to read the number in
    char buffer[10] = ""; // space for maximum 9 digits
    int pos = 0; // position variable in the buffer
    while(fr.available() && pos < 9){ // loop while there is data left to read in the file or we have no pace left in buffer (leaving one character for the terminating null character
        char c = fr.read(); // read character into variable
        if(isDigit(c)){
            buffer[pos] = c; // save digit in buffer
            pos++; // increment position for the next character
        } else {
           break; // break out of loop, if read character is not a digit (we don't want to read further when a non-digit character comes up)
        }
    }
    buffer[pos] = 0; // terminate buffer with null character
    number = atoi(buffer); // use standard function to convert to integer number

Note:
- This code is not tested, though it compiles without errors
- You see, that it is not smaller, than the other one, but can handle different number of digits.
- You can still use the first version with smaller numbers, if you always pad them with zeros. So instead `991` you would write `0991` to the file. That will make the first version work.


body:
Yesterday i downloaded the new version of the IDE to take advantage of all the new features, but it just won't open. I tried installing it to different paths, different PC's, i deleted the package_index.json and the cache folder, but nothing. It stucks in the opening screen (see image below), any other ideas?[![enter image description here][1]][1]

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

title: Arduino IDE 2.0 Beta doesn't start

Answers: 1

body: I have a very slow internet connection and the Arduino IDE seems to depend a lot on it. When I launch it, I shut down internet and it opens in a breeze.


body:
````
//Make an LED Turn ON after pressing a push button switch for five times. Add a reset switch to turn OFF the LED whenever the reset switch is pressed

**void setup()

{

  pinMode(11, OUTPUT);

  pinMode (4,INPUT);

}

void loop()

{

  int y= digitalRead(6); // push button 2

  static int counter {} ;

  int x= digitalRead(4);// push button 1

  if (x==1&& y==0 )

    counter++;

else if (counter == 5) // If counter is pressed 5 times

{

  digitalWrite(11, HIGH); // Turn on the LED

}

if (counter >= 5) // If counter is greater than 5 led will still on

{

  digitalWrite (11, 1);

}

  else if

   (y==1&& x==0 ) // if pressed push button 2  led of
  {

    digitalWrite(11,0);

}

  counter = 0; // Make counter variable = 0

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

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

title: Make an LED Turn

Answers: 1

body:
You can try implementing a counter system in your Arduino program.

For example, if this is your loop() function:

```
void loop(){
int buttonState = digitalRead(1); // Give the variable buttonState the value of pin 1, or whatever your button is connected to
static int counter{}; // Have a counter variable. Static means it doesn't reset to 0 after loop() restarts

if (buttonState == HIGH) // If the button is pressed
{
  ++counter; // Increase the value of counter by 1
}

else if (counter == 5) // If counter is pressed 5 times
{
  digitalWrite(11, HIGH); // Turn on the LED
}
// RESET:
if (counter > 5) // If counter is greater than 5 (you clicked the button again)
{
  digitalWrite (11, LOW);
  counter = 0; // Make counter variable = 0
}
}
````
*Edit* In the comments, Python Schlage made very good suggestions: to change `buttonState` to a boolean and change `int` to `byte` to save space on board the Arduino

Try following this tutorial: https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button and modifying it to work with the counter.
Hope this helps! Please let us know if you need help with the setup() function or if anything is unclear.


body:
Working on my first real Arduino project.

I opened my code in the Arduino IDE and hit build and I get errors "not declared in the scope" on every single call to the Arduino library. For instance, digitalWrite, digitalRead, INPUT, OUTPUT, etc.

I open other projects with my Arduino IDE and they build fine, so it's clearly the code in this project. I've restarted. No change.

Ideas?

title: Arduino IDE not seeing Arduino library

Answers: 1

body: Still not sure what the problem was, but I included `Arduino.h` and everything worked. This is a hack, but an effective one. If someone else knows what I did wrong, let me know.


body:
I'm a beginner using a new Arduino Nano 33 BLE to power a low voltage motor. I've tested that the motor can run using a standard 1.5V AA battery when connected directly, but I cannot get it to work when using the Nano to complete the circuit using a BC547 transistor.

I've attached a photo of my circuit that's as clear as I could get.
[![My circuit][1]][1]

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

The 1.5V motor is attached on the orange wires, I couldn't fit it in the photo.

The code I've uploaded to the Nano is as follows:

    int power = 1023;
    int outPin = D10;

    void setup() {

      pinMode(outPin, OUTPUT);
    }

    void loop() {
      digitalWrite(outPin, HIGH);
      delay(1000);
      digitalWrite(outPin, LOW);
      delay(1000);
    }

When I complete the circuit with the AA battery, I can see the red LED, that's in series with the battery to the collector of the transistor, does light up but very dimly and so therefore the motor does not run either. I've also tried 2xAA and 4xAA batteries and that lights up the LED very brightly, but the motor still does not run. What could be wrong with this circuit?

Thanks!

title: Motor not working when using Nano 33 BLE and transistor because of low voltage

Answers: 0


body:
Let's say I want to modify a global variable from inside an [interrupt][1] service routine. I must ensure that any variables I modify are volatile. Does it work to use a volatile pointer to data I want to modify if the data itself is not volatile?

In my case the data is a struct, but does the answer change if the data is a class, array, or just a variable?

``` c++
#include <Arduino.h>

#define PIN_INTERRUPT  2

typedef struct MyStruct
{
    int a_field;
} MyStruct;

MyStruct struct_data;
int array_data[32];

volatile bool _flag_ISR = false;
volatile MyStruct *_struct_ISR = &struct_data;
void myISR()
{
    // just some example stuff
    int read = digitalRead(PIN_INTERRUPT);
    _struct_ISR->a_field = read;
    _arr_data_ISR[4] = read;

    _flag_ISR = true;
}

void setup()
{
    attachInterrupt(digitalPinToInterrupt(PIN_INTERRUPT), myISR, CHANGE);
}

void loop()
{
    if (_flag_ISR)
    {
        // do processing here...
        _flag_ISR = false;
    }
}
```

  [1]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

title: When accessing a variable from an ISR, is a volatile pointer enough?

Answers: 1

body:
First, beware that what you have written is not a volatile pointer, it's
a pointer to volatile data. If you always access the object through this
pointer, you should be fine. If you use the pointer in the ISR, but
access the data directly in the main code (bypassing the `volatile`
qualifier), then the program could fail.

Consider the following:

```c++
void loop()
{
    if (_flag_ISR) {
        _flag_ISR = false;
        Serial.println(struct_data.a_field);
    }
}
```

Once the compiler inlines the call to `loop()` from `main()`, the
main program looks like

```c++
int main()
{
    init();  // Arduino core initialization
    setup();
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(struct_data.a_field);
        }
    }
}
```

And now, since `struct_data` is not volatile, the compiler can
legitimately optimize the code by avoiding repeatedly accessing the same
RAM location:

```c++
int main()
{
    init();  // Arduino core initialization
    setup();
    register int data_copy = struct_data.a_field;
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(data_copy);
        }
    }
}
```

And now the program prints only zeros.


body:
Can anyone explain me the difference between the symbols for Arduino nano in KiCad? Is there any important difference at all? All of them seem to have all basic pins.

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

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

title: Arduino nano KiCad symbols

Answers: 1

body:
In short, there aren't any substantial differences.  But it makes sense to use the one that actually matches what you have.

My KICAD symbols are out of date, so I downloaded and unpacked the [current archive for MCU Module symbols][1].  These things are defined in text files, so doing this allows you to employ the usual diff tools to them, if you break the parts of interest out into separate files, which is what I did to produce the below images.

Index Entries
-------------

Besides the name, they're different in what datasheet they refer to:
[![Comparison of index entries][2]][2]

Definitions
-----------

In the below, on the left you'll see in dark blue background that both the Nano v2.x and v3.x are actually defined in the same file.  So, they are in fact sharing a definition; so, no differences there at all.  The original Nano boards varied in that some had ATMega168P and some had ATMega328P.  These are practically but not quite the same chip.  The significant difference is sizes of the various memories.  And they had different bootloaders.  Nothing that would make their symbols or footprints significantly different.

On the right is the Nano-Every, which is a fairly different beast from the older Nanos in that it's an ATMega4809, one of the new-series AVR parts, and different significant ways greater than just memory sizes.  But, it was designed to have the same layout as the prior Nano boards.  They even went so far as to make [classes and objects to try to "emulate" the more traditional style GPIO ports][3] of the Nano for Nano Every users.

As you can see there's really no differences besides the names of the pins and a few changes in drawn locations between the v2/v3 symbol on left and the "Every" symbol on the right.  Some of the pin names are different, but it's the pin numbers that matter when mating it to a footprint in Kicad, and those are the same between the two.

For whatever reason pin number 29 changed from `W` (in 2/3) to `N` (in "Every"), which according to [their documentation][4] is a change from *power input* to *not connected*.  I suppose this might make a difference between whether or not you need to add a `PWR_FLAG` symbol somewhere in your design to satisfy electrical rules check (ERC).  In the "Every", for whatever reason when they (slightly) rearranged the pins locations in the symbol, they stuck pin number 29 right on top of pin 4.  So, if you're having a hard time seeing pin 29, that (and the light gray text) are why.

[![Symbol Definitions Differences][5]][5]

  [1]: https://kicad.github.io/symbols/MCU_Module
  [2]: https://i.stack.imgur.com/ZAGSh.png
  [3]: https://github.com/arduino/ArduinoCore-megaavr/blob/1.8.7/cores/arduino/NANO_compat.h#L22
  [4]: https://kicad.org/help/legacy_file_format_documentation.pdf
  [5]: https://i.stack.imgur.com/CbfVM.png


body:
So I have created this project to have an LED blinking at a constant speed whenever the program is running. The first LED (green) will blink faster and faster the closer an object gets to the sensor. The second LED (Blue(is referenced in code as white)) should be blinking constantly. The LED (blue) is only blinking when my ultrasonic sensor has something in range. I would like to make it so it blinks no matter the circumstances.
This is probably something obvious Im missing - excuse my noob-ness
NOTE: if the picture of the circuit isnt correct (pins not being correct) know that it is correct in real life, this is what I get for doing a quick mock up and post at 1:00 AM

    #include "DHT.h";

    #define DHTTYPE DHT22   // DHT Type is DHT 22 (AM2302)
    #define DHTPIN 7       // DHT-22 Output Pin connection
    #define trigPin 5
    #define echoPin 6
    #define beepPin 12
    #define scalingfactor 10
    #define blueLed 11

    #define ledPin2 10

    float hum;    // Stores humidity value in percent
    float temp;
    float soundsp;
    float soundum;
     DHT dht(DHTPIN, DHTTYPE);  // Initialize DHT sensor for normal 16mhz Arduino

    int centi = 0;

    const long erval = 500;

    unsigned long previous = 0;
    unsigned long lastduration = 0;
    unsigned long duration = 0; //time it takes for sound to return
    unsigned long maxtime = 2000;
    unsigned long i = 1;  //variable to determine actual distance
    unsigned long time2 = 0;
    unsigned long time1 = 0;

    void setup() {
      Serial.begin (9600);  //open monirot channel
      dht.begin();  //start temp and humidity sensor
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(beepPin, OUTPUT);
      pinMode(blueLed, OUTPUT);
    }

    void calculate(){
          // Calculate the Speed of Sound in M/S in accordance with temp
        soundsp = 331.4 + (0.606 * temp) + (0.0124 * hum);

        // Convert to cm/us
        soundum = soundsp / 10000;
    }

    void logdistance() {
      digitalWrite(trigPin, HIGH); // send sound signal
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);  // stop sound signal
      duration = pulseIn(echoPin, HIGH);  // listen for sound signal
      centi = (duration* soundum)/2;   // determine delay of sound signal in one direction
      maxtime = scalingfactor * centi;  // change max time in accordance to the distance of the previous object
    }

    void beep() {
      digitalWrite(beepPin, HIGH);   // turn on the beep pin (or LED pin)
      delay(60);
      logdistance();   // run the log distance function again so we get accurate data
      if (time2 - time1 < 30) {  // delay based on how close an object is
        delay((60 - (time2 - time1)));
      }
      digitalWrite(beepPin, LOW);  // turn off beeper (or LED)
      i = 1;
        while (1) {
        if (i % 60 == 0) {
          logdistance();  // run my log distance funciton
        }
        delay(1);
        ++i;  // add one to i to report that we have recorded the distance
        if (i >= maxtime) { // dont report distanc if sound took longer than max time to return
          break;
          }
        }
    }

    void BlinkBlue (int interval){
       static long prevMill = 0;
       if (((long)millis() - prevMill) >= interval){
        prevMill = millis();
        digitalWrite(blueLed, !digitalRead(blueLed));
       }
    }

    void temps(){
      hum = dht.readHumidity();  // Get Humidity value
      temp= dht.readTemperature();  // Get Temperature value
    }

    void loop() {
      BlinkBlue(500);
      beep();

      temps();
      calculate();

      //print results
      Serial.print (duration);
      Serial.print("c. ");
      Serial.print(centi);
      Serial.print(" ");
      Serial.print(temp);
      Serial.println(" ");
    }

[![circuit][1]][1]

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

title: Problem using sequential loop

Answers: 0


body:
[Scheduler_example00_Blink][1] is ~300 lines. For just an Arduino Uno, what is a minimal example?

It's hard to know what belongs and what doesn't. This example has six different approaches, and I'm just trying to extract one of them.

  [1]: https://github.com/arkhipenko/TaskScheduler/tree/master/examples/Scheduler_example00_Blink

title: Minimal example of Task Scheduler Blink?

Answers: 1

body:
    #include <TaskScheduler.h>

    // Scheduler
    Scheduler ts;

    /*
       Approach 1: LED is driven by the boolean variable; false = OFF, true = ON
    */
    #define PERIOD1 500
    #define DURATION 10000
    void blink1CB(); // <-------------------------------------------|
    Task tBlink1 ( PERIOD1 * TASK_MILLISECOND, DURATION / PERIOD1, &blink1CB, &ts        , true );
    //           (     500 * 1UL (ms)        , 100000 ms/ 500    , function , just put it,  ?   )

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

    void loop()
    {
      ts.execute();
    }

    inline void LEDOn() {
      digitalWrite( LED_BUILTIN, HIGH );
    }

    inline void LEDOff() {
      digitalWrite( LED_BUILTIN, LOW );
    }

    // === 1 =======================================
    bool LED_state = false;
    void blink1CB()
    {
      if ( LED_state )
      {
        LEDOff();
        LED_state = false;
      }
      else
      {
        LEDOn();
        LED_state = true;
      }
    }


body:
I’m trying to create a link between two nRF24L01 units. Each nRF24L01+-based module ([purchased][1]) is connected to Arduino Nano on a custom-designed PCB.

[![][2]][2]

The printed wiring is per the hardware application, and is functionally verified by the positive result of the `isChipConnected()` method.

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

The NRF24L01 is fed from the Nano 3.3V output. According to the component’s datasheet this should be OK:

• According to the datasheet the max consumption is 9mA when transmitting in high power. The Nano output can source up to 150mA. So it doesn't close to the limit.

• I measured the 3.3V supply line and the value is 3.23V on both modules (the specified minimum is 3.0V).

• The supply line is being filtered by a 10uF cap.

The two stations are using the same code; the roles are being defined by the level of an IO pin. It contains two modules - the application and the high-level driver class.

Now to the problem: According to the Arduino screenshots it appears that the transmitter does not sending the data. Since the low-level transmitting routine (`radio.write()`) is waiting for the receiver auto acknowledge, I considered also the possibility that receiver side doesn't send the auto-ACK. However, I Switched off the auto acknowledge in both stations and the result wasn't changed.

Any clue will be helpful. Thank tou.

    #define Radio0_IRQ   2
    #define TerminalPin  6
    #define CsnPin       10
    #define terminalRole 1

    String msgHeader;
    bool role;
    /************************************************/
    void(*resetFunc) (void) = 0;//declare reset function at address 0
    /***********************************************************/
    #include "radioPortClass.h"
    RadioPort communicationPort;

    /************************************************/
    void setup(void)
    {
      pinMode(TerminalPin, INPUT_PULLUP);
      role = !digitalRead(TerminalPin);
      if(role == terminalRole)
        msgHeader = "Terminal: ";
      else
        msgHeader = "Field unit: ";

      Serial.begin(9600);
      while (!Serial)
        delay(10);
      if (communicationPort.portInit(role))
        Serial.println(msgHeader + "Port initiated successfully\n\n");
      else if (!radio.isChipConnected ())
      {
        Serial.println(msgHeader + "Port initiation failed\n\n");
        delay(2000);
        resetFunc();
      }
    }
    /***********************************************************/
    void loop(void)
    {
      if (role == terminalRole)
      {
    // Terminal role. Transmit a message and receive the reply
        if (!communicationPort.tx("Terminal to field unit"))
          Serial.println(msgHeader + "Failed, transmit timed out.\n\n");
        else
        {
          Serial.print(msgHeader + "Got response: ");
          delay(1000);
          Serial.println(communicationPort.rx());
          started_waiting_at = millis();
        }
        delay(3000);
      }
      else  // Field unit role. Receive each packet, print it and reply
      {
        String receive_payload = communicationPort.rx();
        if (receive_payload == "\0")
        {
          if((millis() - started_waiting_at) > rxDelay)
          {
            Serial.println(msgHeader + "Failed, receive timed out.\n\n");
            delay(100);
            resetFunc(); //call reset
          }
        }
        else
        {
          Serial.print  (msgHeader + "Got payload: ");
          Serial.println(receive_payload);
          if (!communicationPort.tx("Field unit to terminal"))
            Serial.println(msgHeader + "Failed, transmit timed out.\n\n");
          else
            Serial.println(msgHeader + "Sent response.\n\n");
        }
      }
    }

    Radio Driver
    class RadioPort
    {
      public:
        bool tx(String txData);
        String rx(void);
        bool portInit(bool role);
    };
    #include "RF24.h"
    RF24 radio(9, CsnPin);

    const uint64_t pipes[2] = {0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL};
    #define rxDelay   1000
    #define txDelay   100
    unsigned long started_waiting_at;

    /************************************************/
    bool RadioPort::tx(String txData)
    {
    // First, stop listening so we can talk.
      radio.stopListening();
      bool success = radio.write(&txData, txData.length());
      radio.startListening();
      return success;
    }
    /************************************************/
    String RadioPort::rx(void)
    {
     // if there is data ready
      if (radio.available())
      {
    // Fetch the payload, and see if this was the last one.
        uint8_t len = radio.getDynamicPayloadSize();
        char receive_payload[len + 1];
        radio.read(receive_payload, len);
    // Put a zero at the end for easy printing
        receive_payload[len] = 0;
        return receive_payload;
      }
      else return "\0";      // Dummy statement, for the compiler warning
    }
    /************************************************/
    bool RadioPort::portInit(bool role)
    {
      pinMode(Radio0_IRQ, INPUT_PULLUP);
      radio.begin();//(5,CsnPin)
      if(!radio.isChipConnected ())
        return false;

      radio.enableDynamicPayloads();
      radio.setRetries(15,15);
      radio.setPALevel(0, true);
      radio.setChannel(105);
      radio.setAutoAck(false);//true);

      if (role == terminalRole)
      {
        radio.openWritingPipe(pipes[0]);
        radio.openReadingPipe(1,pipes[1]);
      }
      else
      {
        radio.openWritingPipe(pipes[1]);
        radio.openReadingPipe(1,pipes[0]);
        started_waiting_at = millis();
      }
      radio.startListening();
      return true;
    }

  [1]: https://www.ebay.com/itm/NRF24L01-PA-LNA-Wireless-Transceiver-Module-with-SMA-antenna-Power-amplifier-New/182666165978?hash=item2a87c07eda:g:hzAAAOSwgu9ZZxrF
  [2]: https://i.stack.imgur.com/uKFnP.png
  [3]: https://i.stack.imgur.com/3Jm9M.png

title: nRF24L01 +pa +lna link does not communicate

Answers: 0


body:
I found this [ESP8266-MQTT program on Github.](https://github.com/rkubera/ESP8266-MQTT-to-Serial-Bridge)

How can I compile this thing with the Arduino IDE?

I only can open one sketch at a time. If I try to compile this then parts of the program are missing for AVRDUDE - but they are in the same folder.

Please can you help me?

title: Problems with compiling more then one sketch in the Arduino IDE

Answers: 1

body:
That sketch is written for the ESP8266, not the ESP32. The two are very different chips, and the libraries used are very different.

You will have to learn how the sketch works, and how the ESP32 libraries work, and port the sketch to the ESP32 once you have learned how.


body:
**TL;DR:** How would one send a fixed radio signal at 447,54MHz with Arduino?

**Background:** I recently purchased a (receive only) SDR and recorded my garage door fob. I found it sends a fixed signal at the frequency 447,54MHz, which I was able to decode. Now I want to try activating the garage door via Arduino. The standard 433MHz senders obviously don't work, since they have a totally different frequency.

I tried searching for senders of my frequency (447MHz) and also for senders with different or variable frequencies. I didn't really find much. Also I read in some post (that I don't remember currently), that building an own sender circuit is not easy (since the exact PCB design plays a big role in the behavior in the ciruit). It didn't seem, that this would be a valid way for me.

Has someone here experience with such frequencies? While I know, that this site doesn't do product recommendations, maybe I just searched for the wrong term and you can help me with that. Or maybe there are no (or very very few) "maker-ready" products for this out there currently. Maybe the creator of the garage door system wanted a non-standard frequency for security-through-obscurity (since that doesn't protect against attackers with a sending SDR).

Also I researched about frequency bands. Normally I would think of a garage door fob as a Short Range Device (SRD), but instead my frequency is right above (and outside) of the band PMR. Maybe this is because the system is really old (can easily be between 15 and 30 years).

I'm kinda lost on how to proceed here, or if proceeding is even viable here.

title: How would one send radio signals from Arduino at a non-standard frequency

Answers: 1

body:
>The standard 433MHz senders obviously don't work, since they have a totally different frequency.

I think "433 MHz" is used as a band name, with 433 MHz actually being at the lower limit of a band that covers approximately 40 MHz. Your garage door opener will likely be referred to as a "433 MHz garage door opener", even though it operates at 447.54 MHz.

For your experiments, you might try the [HC-12 module](https://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/). It's billed as a 433 MHz radio, but in fact it covers 433 MHz to 473 MHz in 100 bands with 400 kHz spacing, so it will cover your desired 447.54 MHz. The link above has some Arduino code examples that might help get you started. And of course there is much [more information on this topic](https://duckduckgo.com/?q=hacking+rf+transmitter+for+garage+door+openers&t=ffnt&ia=web) if you're interested.


body:
I've been having an odd issue with a new custom ESP board. I can't push deep-sleep time past 35 minutes no matter how I adjust the timing.

Below is my current pertinent code, but basically the device wakes up, reads several environmental sensors, sends them to the cloud and then turns off. I'm aiming to sleep for an hour between readings to preserve battery power.

     #include <esp_deep_sleep.h>

    int SLEEP_TIME;

    #define uS_TO_S_FACTOR 9e9  //Conversion factor for micro seconds to seconds
    #define TIME_TO_SLEEP  9e8 //Time ESP32 will go to sleep (in seconds)

    SLEEP_TIME = (uS_TO_S_FACTOR * TIME_TO_SLEEP);
    esp_sleep_enable_timer_wakeup(SLEEP_TIME);

    esp_deep_sleep_start();

title: Why isn't my ESP32 staying in Deep Sleep longer than 35 minutes?

Answers: 0