message:
Serial data affected by interrupt

In my recent project, I have done everything means capture serial data and split it out in proper form.

Until now everything is fine. But when I add another portion of code which contains Interrupt. Now, whenever Interrupt come into the picture, my incoming serial data totally destroy. And when I remove that interrupt portion then everything is fine. But this interrupt is also given one my reading(RPM READING).

I tried out `detachinterrupt` function, it disables my interrupt then I can't get my RPM READING.

I also tried out `interrupts()` and `noInterrupts()` function. But I don't get any results. I think I'm not able to utilize my code with this function.

Here, below my whole code which is a little bit lengthy. But, it's necessary.

    #include<LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    String data_TPS_Json = "";
    String data_MAP_Json = "";
    String data_LOAD_TM_Json = "";

    String data_LOAD_RI_Json = "";
    String data_RPM_Json = "";
    String data_INJECTION_TIME_Json = "";

    String response = "";
    bool begin = false;

    char in;
    int len = 0;

    float TPS_Json;
    float MAP_Json;
    float LOAD_TM_Json;

    float LOAD_RI_Json;
    float RPM_Json;
    float INJECTION_TIME_Json;

    //----------------------------For MAP calculation----------------------------//
    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    int LOAD_MIN_MAP[] = {1, 2};
    int LOAD_MAX_MAP[] = {3, 4};

    float mMAP[2] = {};
    float yMAP[2] = {};

    int i, j, a;
    float MAP, mFinalMAP, yFinalMAP;

    //----------------------------For TPS calculation----------------------------//
    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    int LOAD_MIN_TPS[] = {1, 3};
    int LOAD_MAX_TPS[] = {2, 4};

    float mTPS[2] = {};
    float yTPS[2] = {};

    int k, l, b;
    float TPS, mFinalTPS, yFinalTPS;

    //----------------------------For LOAD calculation---------------------------//
    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD[] = {6.20, 6.26};
    float injTime_MAX_LOAD[] = {7.80, 8.06};

    float mLOAD[2] = {};
    float yLOAD[2] = {};

    int m, n, c;
    float LOAD, mFinalLOAD, yFinalLOAD;

    //----------------------------For RPM calculation----------------------------//
    const int kPinRPM = 3;        // RPM / Digital Pin 3
    const int RPMInterrupt = 1;   // RPM's interrrupt pin
    byte engineCylinders = 2;         // Engine cylinders = 4;
    byte engineCycles = 4;            // Engine cycle = 2
    int refreshInterval = 750;        // Milliseconds between sensor updates
    unsigned long previousMillis = 0;
    volatile int RPMpulses = 0,  RPM0 = 0;
    int RPM, Final_RPM;

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

    float injTime_MIN_RPM[] = {6.20, 7.80};
    float injTime_MAX_RPM[] = {6.26, 8.06};

    float mRPM[2] = {};
    float yRPM[2] = {};

    int o, p, d;
    float mFinalRPM, yFinalRPM;

    //------------------------For GAS PRESSURE calculation-----------------------//
    float minPosVolGas = 0.00;
    float maxPosVolGas = 2.50;

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

    //----------------------For INJECTION TIME calculation-----------------------//
    float yInjTime, injTime, gasInjTime;
    volatile uint32_t kInjTime = 0;

    const int kPinInj = 8;

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

      pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
      attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

      pinMode(kPinInj, OUTPUT);
    }

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

      MAP = analogRead(A0) * (5.0 / 1023.0);

      for(a = 0; a < 2; a++)
      {
        mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
        yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
      }

      //----------------------------TPS----------------------------//

      TPS = analogRead(A1) * (5.0 / 1023.0);

      for(b = 0; b < 2; b++)
      {
        mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
        yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
      }

      //----------------TPS/MAP CALLIBRATION / LOAD----------------//

      mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
      yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

      mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
      yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

      LOAD = (yFinalTPS + yFinalMAP) / 2;

      //----------------------------LOAD---------------------------//

      for(c = 0; c < 2; c++)
      {
        mLOAD[m] = (injTime_MAX_LOAD[c] - injTime_MIN_LOAD[c]) / (LOAD_MAX - LOAD_MIN);
        yLOAD[n] = mLOAD[m] * (LOAD - LOAD_MIN) + injTime_MIN_LOAD[c];
      }

      //----------------------------RPM----------------------------//

      if(millis() - previousMillis > refreshInterval)
      {
        previousMillis = millis();
        RPM =  getRPM();
      }

      for(d = 0; d < 2; d++)
      {
        mRPM[o] = (injTime_MAX_RPM[d] - injTime_MIN_RPM[d]) / (RPM_MAX - RPM_MIN);
        yRPM[p] = mRPM[o] * (RPM - RPM_MIN) + injTime_MIN_RPM[d];
      }

      //-----------LOAD/RPM CALLIBRATION / INJECTION TIME----------//

      mFinalLOAD = (yRPM[1] - yRPM[0]) / (LOAD_MAX - LOAD_MIN);
      yFinalLOAD = mFinalLOAD * (LOAD - LOAD_MIN) + yRPM[0];

      mFinalRPM = (yLOAD[1] - yLOAD[0]) / (RPM_MAX - RPM_MIN);
      yFinalRPM = mFinalRPM * (RPM - RPM_MIN) + yLOAD[0];

      yInjTime = (yFinalLOAD + yFinalRPM) / 2;
      injTime = (yInjTime * 1000) / 1000;

      //------------------JSON SERIAL DATA---------------------//

      while(Serial.available() || !begin)
      {
          in = Serial.read();

          if (in == '{')
          {
            begin = true;
          }

          if(begin)
          {
            response += (in);
          }

          if(in == '}')
          {
            break;
          }

          delay(1);
      }

      len = response.length();

      if(len == 39)
      {
        data_TPS_Json = response.substring(8, 12);
        data_MAP_Json = response.substring(21, 25);
        data_LOAD_TM_Json = response.substring(35, 37);

        jsonMapTps();
      }

      if(len == 52)
      {
        data_LOAD_RI_Json = response.substring(9, 13);
        data_RPM_Json = response.substring(22, 26);
        data_INJECTION_TIME_Json = response.substring(46, 50);

        jsonRpmLoad();
      }

      //------------------------GAS_PRESSURE-----------------------//

      GAS_Pressure =  analogRead(A2) * (5.0 / 1023.0);

      mGasPos = (maxInjPerPos - minInjPerPos) / (maxPosVolGas - minPosVolGas);
      yGasPos = mGasPos * (GAS_Pressure - minPosVolGas) + minInjPerPos;

      mGasNag = (maxInjPerNag - minInjPerNag) / (maxNagVolGas - minNagVolGas);
      yGasNag = mGasNag * (GAS_Pressure - minNagVolGas) + minInjPerNag;

      if(GAS_Pressure >= 0.00 && GAS_Pressure < 2.50)
      {
        gasInjTime = injTime + (injTime * yGasPos);
      }
      else if(GAS_Pressure >= 2.50 && GAS_Pressure <= 5.00)
      {
        gasInjTime = injTime - (injTime * yGasNag);
      }

      //--------------------Pulse Generation-----------------------//

      if((kInjTime > 0) && ((millis() - kInjTime) >= injTime))
      {
        kInjTime = 0;
        digitalWrite(kPinInj, 0);
      }
    }

    void countRPM()
    {
      RPMpulses++;

      digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
      if(RPMpulses & 1)
      kInjTime = millis();  // Store alternate times
    }

    int getRPM()
    {
      Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval);
      RPM0 = RPMpulses &= 1;
      RPMpulses - RPM0;
      return Final_RPM;
    }

    void jsonMapTps()
    {
        TPS_Json = data_TPS_Json.toFloat();
        MAP_Json = data_MAP_Json.toFloat();
        LOAD_TM_Json = data_LOAD_TM_Json.toFloat();

        lcd.setCursor(0, 0);
        lcd.print(TPS_Json);
        lcd.setCursor(8, 0);
        lcd.print(MAP_Json);
        lcd.setCursor(0, 1);
        lcd.print(LOAD_TM_Json);
    }

    void jsonRpmLoad()
    {
        LOAD_RI_Json = data_LOAD_RI_Json.toFloat();
        RPM_Json = data_RPM_Json.toFloat();
        INJECTION_TIME_Json = data_INJECTION_TIME_Json.toFloat();

        lcd.setCursor(0, 0);
        lcd.print(LOAD_RI_Json);
        lcd.setCursor(8, 0);
        lcd.print(RPM_Json);
        lcd.setCursor(0, 1);
        lcd.print(INJECTION_TIME_Json);
    }

body:
You need to clean up the whole sketch. I will try to mention the most important things first.

For an Arduino Uno, this sketch uses 520 bytes RAM and 1528 bytes are free to use for stack and heap. That seems enough but with heap fragmentation it might be a problem, see: [Adafruit about an increasing heap][1]

The `data_...` `String`s are only to display something. They can be replaced with normal strings. You could also make a single buffer of a char array for the "response".

The variables that are used in the interrupt routine **and** also outside the interupt routine should be made volatile.

When the variable `begin` is `false`, you still read data with `Serial.read()`. That can't be right. Could you rewrite that part ?

The variable `kInjTime` is used to store the `millis()` time and also to disable it by setting it to zero. That is not good programming since `millis()` can be zero. It is better to add an extra variable to turn that timing on and off.

The use of `digitalPinToInterrupt()` is advised when using [`attachInterrupt()`][2]. That makes it easier to see which pins are used.

The function `digitalWrite()` takes `HIGH` or `LOW`, not `0` or `1` and not a bit of a variable, only `HIGH` or `LOW`.

Try to use more local variables. You have too many variables as global, which makes it hard to read the sketch.

  [1]: https://learn.adafruit.com/memories-of-an-arduino/solving-memory-problems
  [2]: https://www.arduino.cc/en/Reference/attachInterrupt


sender: user

sender: assistant

body:
Finally got the solution. My method of capturing Serial string data is a little bit faulty. And also remove maximum strings and try to declare maximum local variables And use `ArduinoJson` library for parsing the data.

This is my modified code:

    #include<LiquidCrystal.h>
    #include <ArduinoJson.h>

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    String response = "";
    bool begin = false, finished;

    //----------------------------For MAP calculation----------------------------//
    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    int LOAD_MIN_MAP[] = {1, 2};
    int LOAD_MAX_MAP[] = {3, 4};

    float mMAP[2] = {};
    float yMAP[2] = {};

    int i, j, a;
    float MAP, mFinalMAP, yFinalMAP;

    //----------------------------For TPS calculation----------------------------//
    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    int LOAD_MIN_TPS[] = {1, 3};
    int LOAD_MAX_TPS[] = {2, 4};

    float mTPS[2] = {};
    float yTPS[2] = {};

    int k, l, b;
    float TPS, mFinalTPS, yFinalTPS;

    //----------------------------For LOAD calculation---------------------------//
    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD[] = {6.20, 6.26};
    float injTime_MAX_LOAD[] = {7.80, 8.06};

    float mLOAD[2] = {};
    float yLOAD[2] = {};

    int m, n, c;
    float LOAD, mFinalLOAD, yFinalLOAD;

    //----------------------------For RPM calculation----------------------------//
    const int kPinRPM = 3;        // RPM / Digital Pin 3
    const int RPMInterrupt = 1;   // RPM's interrrupt pin
    byte engineCylinders = 2;         // Engine cylinders = 4;
    byte engineCycles = 4;            // Engine cycle = 2
    int refreshInterval = 750;        // Milliseconds between sensor updates
    unsigned long previousMillis = 0;
    volatile int RPMpulses = 0,  RPM0 = 0;
    int RPM, Final_RPM;

    int RPM_MIN = 400;
    int RPM_MAX = 6000;

    float injTime_MIN_RPM[] = {6.20, 7.80};
    float injTime_MAX_RPM[] = {6.26, 8.06};

    float mRPM[2] = {};
    float yRPM[2] = {};

    int o, p, d;
    float mFinalRPM, yFinalRPM;

    //------------------------For GAS PRESSURE calculation-----------------------//
    float minPosVolGas = 0.00;
    float maxPosVolGas = 2.50;

    float minInjPerPos = 0.35;
    float maxInjPerPos = 0.00;

    float minNagVolGas = 2.50;
    float maxNagVolGas = 5.00;

    float minInjPerNag = 0.00;
    float maxInjPerNag = 0.25;

    float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

    //----------------------For INJECTION TIME calculation-----------------------//
    float yInjTime, injTime, gasInjTime;
    volatile uint32_t kInjTime = 0;

    const int kPinInj = 8;

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

      pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
      attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

      pinMode(kPinInj, OUTPUT);
    }

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

      MAP = analogRead(A0) * (5.0 / 1023.0);

      for(a = 0; a < 2; a++)
      {
        mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
        yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
      }

      //----------------------------TPS----------------------------//

      TPS = analogRead(A1) * (5.0 / 1023.0);

      for(b = 0; b < 2; b++)
      {
        mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
        yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
      }

      //----------------TPS/MAP CALLIBRATION / LOAD----------------//

      mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
      yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

      mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
      yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

      LOAD = (yFinalTPS + yFinalMAP) / 2;

      //----------------------------LOAD---------------------------//

      for(c = 0; c < 2; c++)
      {
        mLOAD[m] = (injTime_MAX_LOAD[c] - injTime_MIN_LOAD[c]) / (LOAD_MAX - LOAD_MIN);
        yLOAD[n] = mLOAD[m] * (LOAD - LOAD_MIN) + injTime_MIN_LOAD[c];
      }

      //----------------------------RPM----------------------------//

      if(millis() - previousMillis > refreshInterval)
      {
        previousMillis = millis();
        RPM =  getRPM();
      }

      for(d = 0; d < 2; d++)
      {
        mRPM[o] = (injTime_MAX_RPM[d] - injTime_MIN_RPM[d]) / (RPM_MAX - RPM_MIN);
        yRPM[p] = mRPM[o] * (RPM - RPM_MIN) + injTime_MIN_RPM[d];
      }

      //-----------LOAD/RPM CALLIBRATION / INJECTION TIME----------//

      mFinalLOAD = (yRPM[1] - yRPM[0]) / (LOAD_MAX - LOAD_MIN);
      yFinalLOAD = mFinalLOAD * (LOAD - LOAD_MIN) + yRPM[0];

      mFinalRPM = (yLOAD[1] - yLOAD[0]) / (RPM_MAX - RPM_MIN);
      yFinalRPM = mFinalRPM * (RPM - RPM_MIN) + yLOAD[0];

      yInjTime = (yFinalLOAD + yFinalRPM) / 2;
      injTime = (yInjTime * 1000) / 1000;

      //------------------JSON SERIAL DATA---------------------//

      StaticJsonBuffer<100> jsonBuffer;

      while (finished == false)
      {
        if (Serial.available())
        {
          const char in = Serial.read();
          if (in == '{')
          {
            response = "";  // Blank the string
            begin = true;
          }
          if (begin)
          {
            response += (in); // Only write if within the {}
          }
          if (in == '}')
          {
            begin = false;   // Prevent any chars between } and { leaking through.
            break;
          }
        }
        delay(1);
      }

      JsonObject& root = jsonBuffer.parseObject(response);

      const char* ActionOne = root["ActionOne"];
      const char* ActionTwo = root["ActionTwo"];

      //--------------------TPS/MAP/LOAD-----------------------//

      if(root.containsKey("ActionOne"))
      {
        float TPS = root["TPS"];
        float MAP = root["MAP"];
        int LOAD = root["LOAD"];

        lcd.setCursor(0, 0);
        lcd.print(TPS);

        lcd.setCursor(8, 0);
        lcd.print(MAP);

        lcd.setCursor(0, 1);
        lcd.print(LOAD);
      }

     //--------------LOAD/RPM/INJECTION_TIME-------------------//

      if(root.containsKey("ActionTwo"))
      {
        float LOAD = root["LOAD"];
        int RPM = root["RPM"];
        float INJECTION_TIME = root["INJECTION_TIME"];

        lcd.setCursor(0, 0);
        lcd.print(LOAD);

        lcd.setCursor(8, 0);
        lcd.print(RPM);

        lcd.setCursor(0, 1);
        lcd.print(INJECTION_TIME);
      }

      //------------------------GAS_PRESSURE-----------------------//

      GAS_Pressure =  analogRead(A2) * (5.0 / 1023.0);

      mGasPos = (maxInjPerPos - minInjPerPos) / (maxPosVolGas - minPosVolGas);
      yGasPos = mGasPos * (GAS_Pressure - minPosVolGas) + minInjPerPos;

      mGasNag = (maxInjPerNag - minInjPerNag) / (maxNagVolGas - minNagVolGas);
      yGasNag = mGasNag * (GAS_Pressure - minNagVolGas) + minInjPerNag;

      if(GAS_Pressure >= 0.00 && GAS_Pressure < 2.50)
      {
        gasInjTime = injTime + (injTime * yGasPos);
      }
      else if(GAS_Pressure >= 2.50 && GAS_Pressure <= 5.00)
      {
        gasInjTime = injTime - (injTime * yGasNag);
      }

      //--------------------Pulse Generation-----------------------//

      if((kInjTime > 0) && ((millis() - kInjTime) >= injTime))
      {
        kInjTime = 0;
        digitalWrite(kPinInj, 0);
      }
    }

    void countRPM()
    {
      RPMpulses++;

      digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
      if(RPMpulses & 1)
      kInjTime = millis();  // Store alternate times
    }

    int getRPM()
    {
      Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval);
      RPM0 = RPMpulses &= 1;
      RPMpulses - RPM0;
      return Final_RPM;
    }

I'm also trying to capture `response` as char array but not able to capture it. Please guide me about that otherwise this one string may not cause any heap fragmentation. I am so glad if someone helps me out for this.


message:
timer0_millis always returns 0

I am trying to make a simple debounce function as explained [here][1] but the condition `if((millis()-timeCheck)>reboundDelay)` is never met.

As you can see in my code below, I am trying to control a PWM with two push buttons. I am currently sending it on a LED.

With AS7 and vMicro I put some breakpoints and realized that `timeCheck` was stuck at 0 and was an `unsigned int` instead of the `unsigned long` I declared. With the debugger I looked inside of the `millis()` function and saw that `timer0_millis` wasn't increasing neither, stuck at 0.

Here is my short code (it's a sketch, it can surely be rewritten in a more efficient way) :

    int PWM=9;
    int dutyP=2;
    int dutyM=3;
    int duty=123;
    bool stateP=0;
    bool stateM=0;
    bool prevStateP=0;
    bool prevStateM=0;
    unsigned long reboundDelay=500;
    unsigned long timeCheck=millis();

    void setup() {
      pinMode(PWM,OUTPUT);
      pinMode(dutyP,INPUT);
      pinMode(dutyM,INPUT);
    }

    void loop() {
      stateP=digitalRead(dutyP);
      stateM=digitalRead(dutyM);
      if(stateP != prevStateP || stateM != prevStateM) {
        timeCheck=millis();
      }
      if((millis() -  timeCheck) > reboundDelay) {
        if(stateP==1) {
          duty=duty+25;
        } else if(stateM==1) {
          duty=duty-25;
        }
        analogWrite(PWM,duty);
        prevStateP=stateP;
        prevStateM=stateM;
      }
    }

And finally, the strange part. When I upload it on my Genuino Uno for like 30 seconds, the pushbuttons do nothing (it may be that the `if` works) and afterwards I can increase and decrease the duty cycle but without the delay that the condition should bring (the LED flashes really fast due to an overflow in analogWrite).

Any help is welcomed, the strange part is secondary to me but I would really like to make `millis()` work properly.

  [1]: https://www.arduino.cc/en/tutorial/debounce

body:
I would suggest a few things:

1) comment on your code -> lay out the basic logic so that you and others can help you debug it;

2) use brackets liberally -> don't rely on memory (=faulty) on the order of operations. instead, define it explicitly;

3) check your logic -> make sure that your code does what you want it to do;

4) pay attention to data type: 8-bit vs. 16-bit, etc.

5) modularize your code -> this allows more efficient debugging and code reusing.

for example, your code can be simply described as

      button_state = read_button(); //read button state, with debouncing
      if (button_state = BUTTON_UP) pwminc_dc(pwm_dc); //increase duty cycle, with boundary checking
      if (button_state = BUTTON_DOWN) pwmdec_dc(pwm_dc); //decrement duty cycle, with boundary checking

with the code modularized, you just need to worry about getting individual pieces right.


body:
I think there is just a logic error that doesn't immediately jump out: When the button state is changed, it will always set timeCheck equal to millis(). For instance, as long as you are pressing "P", stateP will not be equal to prevStateP and so "timeCheck=millis()" will executed everytime thru the loop, so the difference will never reach 500.

    if(stateP != prevStateP || stateM != prevStateM){
        timeCheck=millis();
    }

Should be something like:

    if(stateP == prevStateP && stateM == prevStateM){
        timeCheck = millis();
    }

This will continually keep timeCheck = millis() until either button is pressed. Once the button is pressed, timeCheck will remain at the value of millis() read just before the press, until the debounce value is reached (unless noise/bounce and not a real press, or button is released early as 500ms is a relatively long time).

This is probably the simplest modification to the code I can come up with. Hope it helps.


message:
Avr dude programmer

I was trying to upload a hex file to my attiny85 with an arduino,and I came across this:

    avrdude -c avrisp (followed by other codes and the flash address )

This doesn't work and it gave one of the most famous arduino errors : stk500_getsync() : not in sync: resp=0x00

Then I tried

       avrdude -c arduino

And the code was successfully downloaded, but the chip itself doesn't work as intended. So this is the question, what does the -c [programmer id] actually do, for example in this case, does it download the hex file to my arduino?

Thanks in advance.

body:
Try these steps:

1. Install ArduinoISP (in the examples menu) on your Arduino board.
2. Disable reset on the Arduino board by adding a 10µF capacitor between the RESET and GND pins.
3. Wire the ATTiny chip to the Arduino following [this schematic](https://create.arduino.cc/projecthub/arjun/programming-attiny85-with-arduino-uno-afb829).
4. Run the upload command using `-c avrisp` with your program's HEX file

Alternatively you can just install the boards package detailed in the schematic link and program it directly from the Arduino IDE instead of messing with the `avrdude` upload command.

You must also ensure that you are uploading at the right baud rate. The ArduinoISP sketch defaults to 19200 baud:

    // Configure the baud rate:

    #define BAUDRATE 19200
    // #define BAUDRATE 115200
    // #define BAUDRATE 1000000

and you must match that in your `avrdude` command with, for example, `-b 19200`.


message:
Can't get 4 digit 7 segment display to show different values

I'm an Arduino newbie having problems getting a 4 digit 7 segment display to work. The display is connected to a 74HC595 and the setup is from the elegoo tutorial 28 (I think it is download only).

I figured how to control which number to display, but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

This is the code that toggles between 2222 and 8888.
I want to be able to display any number like 1234 though.

Any help is very appreciated.

    int latch=9;  //74HC595  pin 9 STCP
    int clock=10; //74HC595  pin 10 SHCP
    int data=8;   //74HC595  pin 8 DS

    void setup()
    {
      pinMode(latch,OUTPUT);
      pinMode(clock,OUTPUT);
      pinMode(data,OUTPUT);
    }

    void Display(unsigned int num)
    {
      digitalWrite(latch,LOW);
      shiftOut(data,clock,MSBFIRST,num);
      digitalWrite(latch,HIGH);
    }

    void loop()
    {
        Display(91);
        delay(1000);
        Display(127);
        delay(1000);
    }

[![image taken from the tutorial][1]][1]

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

body:
You have a common cathode display and all your cathodes are tied to ground through resistors. You have no way at all of separating out the different digits.

You cannot directly drive such a display with a shift register like that - you need a more direct connection to the Arduino (it needs to be high speed) and rapidly switch each cathode on and off in sequence to display each of the four numbers one after another.

Also the resistors should be in the 8 anodes, not the 4 cathodes.


body:
> but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

because that's how this particular circuit is designed for.

> I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

multiplexing is no different than displaying each digit quickly (as you are doing now), and then display the next digit quickly, ....

what you are doing now will contribute to your learning multiplexing.


body:
The problem with this setup is the circuit.

The Master Reset Pin 10 on the 595 is floating.

Use a 10K resistor to pull it up to VCC (+5V) and it will work.

I was getting all sorts of odd characters until I checked out the data sheet on the 595.


message:
Arduino % symbol meaning

I dont know what meaning of this symbol - %.

for example,

buttonPressCount % numberOfLED == i

I hope anyone can tell me the name and basic function of this symbol.

body:
It is called the modulus operator, and it performs the modulo operation.

TL;CBR: It results in the remainder after division is performed.


message:
Use Female USB Type A as Power Supply for external device

I bought a female USB Type A Breakout, like this (https://www.sparkfun.com/products/12700). I thought I could use this one to simply power a USB 5v water pump. Therefore I use an external USB power supply that is regulated by a relay, that I regulate with my Arduino. But I'm wondering if it is possible to get that USB Breakout to "give out" power to my water pump.

body:
Yes. Just connect VCC to +5V and GND to GND and you can plug a 5V device into it.

If you need to use it as a charge port (for charging a phone) you will need to connect the D+ and D- pins together.


message:
How can I seriously calibrate ADC voltage readings with Arduino Nano?

I have been using Arduino Nano Analog input to measure voltages, in the range between 22-30 Volts.

I want to measure it down to a tenth of a volt.

Following the instructions found here:

[Read Analog Voltage][1] (www.arduino.cc)

Which basically states that all I need is this code:

    int sensorValue = analogRead(A0);
    float voltage= sensorValue * (5.0 / 1023.0);

5.0/1023 = 0.004888 volts per increment in analog readings.  Turning that around, voltage input divided by this value should give me the sensor value.
Clearly they are presuming an input of 0-5 Volts.

My voltage divider is 1 Mohm (R1) between the voltage input and A2, then 200K (R2) from A2 to ground

30 Volts measures as 4.2 Volts.  22 Volts measures as 3.1 Volts.

I think the range between 22 volts and 30 Volts doesn't present enough variation to the ADC - every single-digit change in the analogRead really make a big difference.

The result is that it is giving me some crazy readings.  It is definitely nonlinear, so I am having real trouble trying to get it to be accurate at both ends of my measurement range.  Each slight ADC increment makes too much of a difference in the measured voltage because I am not using the full 0-5V input range.

So I have been taking 10 readings in a row, at 500 ms intervals, then averaging.

And yet it is not working well enough.

(The biggest problem was the reference voltage and resolution were assumed to be 5/1024 which is completely incorrect.  Unless, as someone pointed out, I fed the Nanos directly at the 5V pin - which is still on the table - then it would be 5/1023)

I changed my resistor network to be 147K/23.5K

(Parts list:  1x 100K, 3x 47K)

R1 = 47K / 47K = 23.5K

R2 = 100K + 47K = 147K

Also added a 100uF 50V electrolytic across the input from the battery bank I am monitoring.

I am feeding 5V to Vin.  And have figured out that the reference is measurable on the 5V pin, after the regulator, as 4.6V.

Knowing that

Resolution/Vref = ADC/Vin

I turned that around to be

Vin = ADC * (Vref/Resolution)

Or, Vin = A2 * (4.6/1023)

Using a laboratory power supply I was able to confirm that with those settings 22 Volts came in at 3 Volts, and 29.98 came in right at 4 Volts.

So

Vbat = A2 * (4.6/1023) / (R2/(R1+R2))

Vbat = A2 * (4.6/1023.0)/(147000/170500)

It is now operating reasonably well.

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

(Yellow means the inverter is on)

--UPDATE--
  Changed resistors to 100K/20K for the divider and brought power to the 5V pin, bypassing the regulator for a reference.  It measures at 5.02 and is stable.

Results:

Charge controller meter says I am at 24.5 Volts.

Program says 24.64  (in the serial monitor).

------------------------------
--ADDENDUM:  I want to pursue the Op-Amp setup.  But if 741 won't work will need a suggestion.

--------------------------------

Similarly, I went to 147K/47K for the 11-15 Volt circuit, and moved a higher-quality P/S over to the 5V pin, where it measures 5.03V; the results are better there, too. Just very slightly high.

---------------------------
So anyway, I'll put this to rest until I can figure out an op-amp circuit.

Thank you all for your help

  [1]: https://www.arduino.cc/en/Tutorial/ReadAnalogVoltage
  [2]: https://startingelectronics.org/articles/arduino/measuring-voltage-with-arduino/
  [3]: https://electronics.stackexchange.com/questions/307586/need-help-calibrating-adc-input-using-a-voltage-divider
  [4]: https://i.stack.imgur.com/cP0gj.png

body:
Rather than mapping to a range of 0 to 4.4 V, map to the range 0 to 1.1 V and use [`analogReference(INTERNAL)`](https://www.arduino.cc/en/Reference/AnalogReference) to select the internal band-gap 1.1 V reference source.  This reference voltage might vary a small amount as Vcc varies, but the variation is likely to be just a few millivolts.

To get your input voltage into the range  0 to 1.1 V, use a voltage divider and a voltage subtractor.  The voltage divider ratio should map the 8-volt range of 22 to 30 V to a 1.1 V range, ie, should have a ratio of 8:1.1, and should map 30 V to 4.125 V and 22 V to 3.025 V.

If you use a [Unity Gain Differential Amplifier as described at electronics-tutorials.ws](http://www.electronics-tutorials.ws/opamp/opamp_5.html), the divider can use large resistors, ie, need not provide the under-10 KΩ resistance needed for ADC input; instead, the UGDA's low output impedance will meet that requirement when used as ADC input.  For example, you could have 1 MΩ in series with 160 KΩ for the main divider.

Feed that divided voltage into V1 in the diagram below.  Use a pot or another voltage divider to create a 3.025 V reference to feed into V2, perhaps based on the board's 3.3 V regulator output.

Note, use R1 = R2 = R3 = R4, with all of them some value like 10 KΩ or 20 KΩ.
[![enter image description here][1]][1]

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


body:
In my opinion, this is a very Arduino specific question.

First of all, you can't map 22-30V to 0-4.4V with a voltage divider (unless you have a negative voltage available). A opamp introduces a little more inaccuracy but can map the voltage which increases the accuracy. I suggest to first get the maximum out of the voltage divider. If that is not enough, then you can try a opamp.

The impedance of the circuit at a analog pin should be 10k or less for a accurate ADC conversion. You can add a small capacitor (1nF to 100nF) from the analog pin to GND, to keep the value stable during the ADC conversion.

The 5V VCC as a reference is a pain. The best option is to use an external voltage reference, for example a LM4040. The second best option is the internal voltage reference of 1.1V. That voltage is never 1.1V, and you have to determine the actual voltage. That 1.1V also depends on the temperature and a little on VCC.

Only 10 readings for an average is a small number. Sometimes I use 5, sometimes I use thousands.

Is the Arduino Nano used indoors, with only a small variation in temperature ? Then select the [analogReference(INTERNAL)][1]. Use for example 10k and 270k for the voltage divider and 10nF parallel with the 10k. Use the average of 100 samples. An accuracy to measure the 24-30V with 0.1V resolution should be easy to achieve and 50mV resolution should be possible.

If you prefer the 1M to measure the voltage, you can also use 1M and 33k. With the 10nF parallel to the 33k, the ADC conversion is probably still accurate enough.

[**ADDED**] You have not told us yet how accurate you want to read the battery voltage. Is ±500mV okay, or must you have ±20mV ? I say it again: 0.1V resolution is easy. But it all depends on a good reference. A bad reference means even worse results. Dit you take a look at [`analogReference`][1] to see what the INTERNAL reference is about ?

  [1]: https://www.arduino.cc/en/Reference/analogReference


body:
Thank you for your answers and there is a lot of collective knowledge there.  It helped me find the way to stabilize and calibrate this system with what I had on hand.  The biggest problem was that the reference voltage and resolution were 5/1024, which is completely incorrect.

I changed my resistor network to be 147K/23.5K  (Parts list:  1x 100K, 3x 47K)

Also added a 100uF 50V electrolytic across the input from the battery bank I am monitoring.

I am feeding 5V to Vin.  And have figured out that the reference it is using is measurable on the 5V pin.

Knowing that Resolution / Vref = ADC reading / Vin, I turned that around to be Vin = ADC * Vref / Resolution.

(Can someone please edit that previous line so the equations look right?

I found out that the proper resolution is 1023, not 1024

Then by measuring the 5V pin I found 4.6 from the 12v-to-5v converter going through the regulator.  The 12 Volts is battery-backed and is very stable.

Vin = A2 * (4.6 / 1023)

Using a laboratory power supply I was able to confirm that with those settings 22 Volts came in at 3 Volts, and 29.98 came in right at 4 Volts.

Then I divided the Vin by (R2/R1+R2) to get the Vbat reading

Vbat = A2 * (4.6/1023) / (R2/(R1+R2))

Vbat = A2 * (4.6/1023.0)/(147000/170500)

You can see it better at

https://electronics.stackexchange.com/questions/307586/need-help-calibrating-adc-input-using-a-voltage-divider/307643#307643

It is now operating reasonably well.

[![image][1]][1]

(Yellow means the inverter is on)

Next step is to try 100K/20K for the divider and bring in 5V to the 5V pin, bypassing the regulator.

I want to pursue the Op-Amp setup.  But if 741 won't work will need a suggestion.  This setup I have been asking for measures a 500Ah 24 Volt deep-cycle Marine battery bank being charged by 6x 100W poly PV panels with a single-axis positioning system.

I now also need to measure exactly half the voltage, 11-15, for the positioning circuitry that has its own battery and dedicated 50 Watt panel to run the computer and motors.  The regulated 5V out there is el-cheapo but I now have the parts on hand to give it better 5V just like I have in here with the storage bank.  Should be able to finish that part today after church.   I expect the ADC will see half the voltage.  Instead of 3-4 Volts it should see 1.5-2 Volts.

Terrible loss of precision.  I really want both systems to see 0-4 Volts at the ADC.

So my question is still the same.  I think the answer is here.

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


body:
> Changed resistors to 100K/20K for the divider

you probably want to read the datasheet about the impedance requirement on the source and potential solutions there.


message:
Stepper motor control

I'm using Arduino to control a stepper motor. I need it to make one revolution and then stop. I'm new to this and haven't ran it yet. Will this do for me?

    #include <Stepper.h>

    const int stepsPerRevolution = 200;

    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    void setup() {
      myStepper.setSpeed(60);
    }

    void loop() {
      myStepper.step(stepsPerRevolution);
    }

body:
No, that will not do what you want. That will continuously rotate the stepper round and round and round.

The clue as to why is in the name of the function you put the `myStepper.step` call: "loop". That function repeatedly loops around over and over again, so your step function will be called over and over again.

There is one piece of information lacking from your thinking at the moment, and that is *when* do you want the stepper to rotate? If it's just once when you turn the power on then it's as simple as doing everything (including calling `myStepper.step`) in `setup()` and leaving `loop()` empty. If not, then you will need to add appropriate logic to only run the step function when the required conditions are met.


message:
How many and fast interrupt pin can handle in Uno?

So I am using Arduino UNO to do phase cutting and read Fan RPM.

For phase cutting, every half frequency it will triggers interrupts and then arduino will triggers TRIAC. Half frequency(50Hz) is 20ms. And for reading rpm, my fan running at 950rpm or 15.83rps, or doing a revolution for 63ms.

I think both of that works is doing a fast work, and I am afraid if I do it simultaneously the arduino will get an error(like a skip on one half wave, or a skip on reading one revolution), or will it not? Thanks.

body:
If two interrupts happen at the same time they will both execute in the numerical order of their INT number (INT 0 will trigger before INT 1). But they will both execute - just one will be a little delayed.

If one interrupt occurs whilst the other is executing the second interrupt will trigger once the first has finished.

As long as both your interrupt routines combined take less than the time than the time between triggerings of the most rapid interrupt you won't get any issues.


body:
You can find the number of external interrupt and pcint pins from the data sheet.

If you use interrupts, the overhead is about 20 or so ticks, or just over 1us. That gives you the minimum.

If polling, and you are lucky, 1 tick is all it takes. 1 /16th of a us.


body:
Let's do some math here.

UNO works at a 16 MHz clock rate. That's a clock cycle every 62.5 nanoseconds, or 16.000 cycles every millisecond. That means plenty of processing power within 20 millisecond, if used wisely (i.e., avoiding processing-intensive functions).

Conclusion: you shouldn't find any major problem if you do a good work with your code. Just keep things simple and don't go through the roof with what you intend to do each 20 ms.


message:
Drawing bitmap on TFT

So, my .ino file is like this (do not worry about TftDisplay library, it totally works fine and myDrawPixel function just calls the adafruit drawPixel function):

    #include "TftDisplay.h"
    #include <avr/pgmspace.h>

    TftDisplay tft;

    const uint8_t myBitmapBitmap [] = {
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 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
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
      0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
    };

    void setup() {
      Serial.begin(9600);
      Serial.print("Starting...");
      tft.init();
    }

    void loop() {
      mdrawBitmap(0, 0, myBitmapBitmap, 100, 146, GREEN);
      delay(2000);
      mdrawBitmap(0, 0, myBitmapBitmap, 100, 146, RED);
      delay(2000);
      mdrawBitmap(0, 0, myBitmapBitmap, 100, 146, BLUE);
      delay(2000);
    }

    void mdrawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color) {
      int16_t i, j, byteWidth = (w + 7) / 8;
      uint8_t byte;
      for (j = 0; j < h; j++) {
        for (i = 0; i < w; i++) {
          if (i & 7) byte <<= 1;
          else byte   = pgm_read_byte(bitmap + j * byteWidth + i / 8);
          if (byte & 0x80) tft.myDrawPixel(x + i, y + j, color);
        }
      }
    }

So, I get some really weird *things* on my TFT. I have no idea what is going on...

As I said, the TftDisplay library is OK, but if you really wonder here is the code:

TftDisplay.h:

    #ifndef _TFTDISPLAY_h
    #define _TFTDISPLAY_h

    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_ST7735.h> // Hardware-specific library
    #include <SPI.h>

    //#define TFT_CS     15
    //#define TFT_RST    5
    //#define TFT_DC     2
    //#define TFT_SCLK 14
    //#define TFT_MOSI 13

    #define TFT_CS 26
    #define TFT_RST 24
    #define TFT_DC 25
    #define TFT_SCLK 22
    #define TFT_MOSI 23

    //#define TFT_CS 10
    //#define TFT_RST 8
    //#define TFT_DC 9
    //#define TFT_SCLK 22
    //#define TFT_MOSI 23

    /*#define TFT_CS   10
    #define TFT_DC   9
    #define TFT_RST  8
    #define TFT_SCLK 13   // set these to be whatever pins you like!
    #define TFT_MOSI 11*/   // set these to be whatever pins you like!

    #define BLACK           0x0000
    #define BLUE            0x001F
    #define RED             0xF800
    #define ORANGE          0xe5f442
    #define GREEN           0x07E0
    #define CYAN            0x07FF
    #define MAGENTA         0xF81F
    #define YELLOW          0xFFE0
    #define WHITE           0xFFFF

    /* TFT Dimensions */
    #define TFTHEIGHT 160
    #define TFTWIDTH 128

    class TftDisplay
    {
      public:
        TftDisplay();
        ~TftDisplay();

     void init();

     void setDefaultTextSize(int textSize);
     void setDefaultTextColor(uint16_t color);
     void setTextWrap(int status);

     void text(String text, int x, int y, uint16_t color, int textSize);
     void text(String text, int x, int y, uint16_t color);

        void clearPart(uint16_t x, uint16_t y, uint16_t w, uint16_t h);
        void clearScreen();
        void myDrawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);
        void myDrawPixel(uint16_t x, uint16_t y, uint16_t color);
        void myDrawRectangle(uint16_t x0, uint16_t y0, uint16_t w, uint16_t h, uint16_t color);
        void myDrawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color);
        uint16_t ConvertRGB( byte R, byte G, byte B);
      protected:
        Adafruit_ST7735 *tft;

     int default_textSize;
     uint16_t default_color;
    };

    #endif

TftDisplay.cpp:

    #include "TftDisplay.h"

    TftDisplay::TftDisplay()
    {

      //init cannot be here as TFT must be inited in arduino setup routine otherwise
      //it crashes everything
    }
    TftDisplay::~TftDisplay ()
    {
      delete tft;
    }

    void TftDisplay::init()
    {

      tft = new Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
      //tft = new Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
      tft->initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab
      tft->fillScreen(ST7735_BLACK);
    }

    void TftDisplay::setDefaultTextSize(int textSize){
     default_textSize = textSize;
     tft->setTextSize(textSize);
    }

    void TftDisplay::setDefaultTextColor(uint16_t color){
     default_color = color;
     tft->setTextColor(color, BLACK);
    }

    void TftDisplay::setTextWrap(int status){
     tft->setTextWrap(status);
    }

    void TftDisplay::text(String text, int x, int y, uint16_t color, int textSize)
    {
     tft->setCursor(x, y);
     tft->setTextColor(color, BLACK);
     tft->setTextSize(textSize);
     tft->print(text);
     setDefaultTextSize(default_textSize);
     setDefaultTextSize(default_color);
    }

    void TftDisplay::text(String text, int x, int y, uint16_t color)
    {
      tft->setCursor(x, y);
      tft->setTextColor(color, BLACK);
      tft->print(text);
      setDefaultTextColor(default_color);
    }

    void TftDisplay::clearPart(uint16_t x, uint16_t y, uint16_t w, uint16_t h) {
      tft->fillRect(x, y, w, h, BLACK);
    }

    void TftDisplay::myDrawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color) {
      tft->drawLine(x0, y0, x1, y1, color);
    }

    void TftDisplay::myDrawPixel(uint16_t x, uint16_t y, uint16_t color) {
      tft->drawPixel(x, y, color);
    }

    void TftDisplay::myDrawRectangle(uint16_t x0, uint16_t y0, uint16_t w, uint16_t h, uint16_t color) {
      tft->drawRect(x0, y0, w, h, color);
    }

    void TftDisplay::clearScreen(){
      tft->fillRect(0, 0, TFTWIDTH, TFTHEIGHT, BLACK);
    }

    void TftDisplay::myDrawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color){
      tft->drawBitmap(x, y, bitmap, w, h, color);
    }

    uint16_t TftDisplay::ConvertRGB( byte R, byte G, byte B)
    {
      return ( ((R & 0xF8) << 8) | ((G & 0xFC) << 3) | (B >> 3) );
    }

body:
You have duplicate instances on the tftDisplay.h.

    ///////#define TFT_CS 26
    #define TFT_RST 24
    #define TFT_DC 25
    #define TFT_SCLK 22
    #define TFT_MOSI 23

    //#define TFT_CS 10
    //#define TFT_RST 8
    //#define TFT_DC 9
    //#define TFT_SCLK 22
    //#define TFT_MOSI 23

    /*#define TFT_CS   10   --->comment this correctly
    #define TFT_DC   9
    #define TFT_RST  8
    #define TFT_SCLK 13   // set these to be whatever pins you like!
    #define TFT_MOSI 11*/   // set these to be whatever pins you like!

And if you're using a Mega, it has different pins for SPI as compared to Uno.


message:
Cannot correctly access element in array when given index

I have the following strings which are stored in the program memory. They are basically just morse code definitions, with another array of characters where each character in the array has the same index as the morse code definitions:

    const char a[] PROGMEM = ".-";
    const char b[] PROGMEM = "-...";
    const char c[] PROGMEM = "-.-.";
    const char d[] PROGMEM = "-..";
    const char e[] PROGMEM = ".";
    const char f[] PROGMEM = "..-.";
    const char g[] PROGMEM = "--.";
    const char h[] PROGMEM = "....";
    const char i[] PROGMEM = "..";
    const char j[] PROGMEM = ".---";
    const char k[] PROGMEM = "-.-";
    const char l[] PROGMEM = ".-..";
    const char m[] PROGMEM = "--";
    const char n[] PROGMEM = "-.";
    const char o[] PROGMEM = "---";
    const char p[] PROGMEM = ".--.";
    const char q[] PROGMEM = "--.-";
    const char r[] PROGMEM = ".-.";
    const char s[] PROGMEM = "...";
    const char t[] PROGMEM = "-";
    const char u[] PROGMEM = "..-";
    const char v[] PROGMEM = "...-";
    const char w[] PROGMEM = ".--";
    const char x[] PROGMEM = "-..-";
    const char y[] PROGMEM = "-.--";
    const char z[] PROGMEM = "--..";
    const char one[] PROGMEM = ".----";
    const char two[] PROGMEM = "..---";
    const char three[] PROGMEM = "...--";
    const char four[] PROGMEM = "....-";
    const char five[] PROGMEM = ".....";
    const char six[] PROGMEM = "-....";
    const char seven[] PROGMEM = "--...";
    const char eight[] PROGMEM = "---..";
    const char nine[] PROGMEM = "----.";
    const char zero[] PROGMEM = "-----";

    const char* const morse_table[] PROGMEM = {a, b, c, d, e, f, g, h, i, j, k, l, m,
        n, o, p, q, r, s, t, u, v, x, y, z, one, two, three, four, five, six,
        seven, eight, nine, zero};

    const char alphabet[] PROGMEM = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'};

I am then creating a function which is supposed to be able to take in the morse code definition and spit out a character. This function is below:

    void checkString(char * compare) {
      //Unwrap the pointer to the array into a "real" array
      char buf[7];
      for (int i = 0; i < 6; i++) {
        buf[i] = compare[i];
      }

      int correctIndex = -1;

      for (int iterator = 0; iterator < 35; iterator++) {

        char buf2[7];
        strcpy_P(buf2, (char*)pgm_read_word(&(morse_table[iterator])));

        if ((buf[0] == buf2[0]) && (buf[1] == buf2[1]) && (buf[2] == buf2[2]) && (buf[3] == buf2[3]) && (buf[4] == buf2[4])) {
          correctIndex = iterator;
        }
      }

      if (correctIndex == -1) {
        Serial.println("Failed!");
      }

      else {
        Serial.print("Success! Index: ");
        Serial.println(correctIndex);
      }

      char characterBuffer = alphabet[correctIndex];
      Serial.println(alphabet[correctIndex]);
    }

The strcpy_p line of code was essentially copied from the PROGMEM reference for Arduino. I don't understand much about it, but from my tests it appears to work in getting an actual string object out of the pointer.

If I input any of the morse code definitions given, the correctIndex integer does contain the correct location of that definition in the morse_table 2d array. However, when I pass this integer into the alphabet array hoping to get out the character at that location I am given a seemingly random character. Is there something that I'm doing wrong with this code to produce such a result? Thanks for your help.

body:
You can't access arrays that are in PROGMEM as if they were normal variables. The compiler can't tell the difference and just interprets it as a RAM address, which is wrong.

Instead you have to use `pgm_read_byte` to get the data:

    char characterBuffer = pgm_read_byte(alphabet + correctIndex);


message:
Will the Arduino's low clock speed limit wireless transmission frequencies that are higher than the clock speed of the Arduino?

I've recently used 2.4GHz and 433MHz wireless communication modules, and I was wondering if the Arduino can only process at 16MHz(Arduino UNO's clock speed), then won't the communication modules also be limited to a maximum 16MHz?

body: The frequency of a (wireless) radio is its carrier frequency. The data stream is carried on it by modulating that carrier wave in some way: by frequency-shifting, for example. A given processor could not provide data at a rate faster than its clock frequency (at least as a steady-state rate), but a packet of data, once supplied to and buffered in the radio, could then be streamed out at a speed unrelated to the physical specs of the supplier (the MCU). If the MCU had to drive the transmitter, bit-by-bit, then that would indeed limit the transmission speed.


body:
You need like 22kHz for "telephone quality" transfer of speech, but you can hardly articulate more than 4-5 syllables per second. The first is the carrier frequency, the other is data transfer speed. (And you usually need some time to think about what you want to say).

The wireless frequency is modulated by the transmitted signal, which must be lower than the frequency itself, to be able modulate it successfully and then be separated from it. There is also some overhead like headers stating who is transmitting, to who, how much, control sum and so. A lot of it is managed in hardware, without direct processor control. (You also do not generate the frequencies and tone in you head as values of sinus wave, you just send the modulation - talk - and the body makes its parts vibrate so fast with your breath).


message:
Help with my DHT22 sensor and using GET request

For some reason using my DHT22 sensor I keep getting "NaN". I have tried using older versions of the DHT22 sensor library as suggested by a few of my searches, but it still doesn't fix the issue.

Also I can't get it to work with the GET request portion. Any help would be greatly appreciated.

    #include <Adafruit_Sensor.h>
    #include <DHT.h>
    #include <ESP8266WiFi.h>
    #include <Phant.h>
    #include <ESP.h>

    #define DHTPIN 2
    #define DHTTYPE DHT22

    DHT dht(DHTPIN, DHTTYPE);
    const char* ssid = "Myyyyyyh";
    const char* password = "Ixxxxx1";
    const char* host = "script.google.com";

    //*****example address
    //https://script.google.com/macros/s/AKfycbyNsFc87GQmRP3GnWoTzK6/exec?tag=test&value=8
    const String gardenchart = "/macros/s/AKfycbyNnWoTzK6/exec?";
    const byte sleeptime = 1;
    const byte NUM_FIELDS = 5;
    const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
    String fieldData[NUM_FIELDS];

    void setup() {
      Serial.begin(115200);
      delay(10);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
      }
      fieldData[0] = 1;
      postdata();
      ESP.deepSleep(sleeptime * 60 * 1000000, WAKE_RF_DEFAULT);
    }

    void loop() {
      delay(50);
    }

    void postdata() {
      fieldData[0] = dht.readHumidity();
      fieldData[1] = dht.readTemperature(true);
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect (host, httpPort)) {
        return;
      }
      for (int i=0; i<NUM_FIELDS; i++) {
        client.print("GET ");
        client.print(fieldNames[i]); client.print("&value=");
        client.print(fieldData[i]); client.print(" HTTP/1.1");
        client.println("Host:"); client.print(host);
        Serial.print(fieldNames[i] + fieldData[i]); delay(500);
      }
      client.println("Connection: close");
    }

body:
The Adafruit DHT library causes a shortcut on the signal line. That can be a problem for Arduino boards, but it is a big problem for the ESP8266.
Issue: [DHT init sequence wrong #48][1]
I don't know what is a bigger problem, the shortcut in the code or Adafruit not fixing it.

Why do you mention the Arduino Uno with a label ?
For the "GET" you should find a good working example.

The DHT22 is not very good. There are better sensors with a normal I2C interface, for example the HTU21D-F or the BME-280. This is about a great test: [Hackaday: Humidity Sensor Shootout][2]. The BME-280 is the undisputed winner.

  [1]: https://github.com/adafruit/DHT-sensor-library/issues/48
  [2]: http://hackaday.com/2017/01/03/humidity-sensor-shootout/


message:
Is an Arduino Uno made in the USA compatible with SunFounder shields?

I bought an Arduino Uno from Radio Shack. I was under the impression it was the authentic model made in Italy. I read on Arduino.cc that the USA version is licensed and essentially the same. I then went to Amazon and ordered an RBG shield, and what I thought was the starter kit that is used with the examples on the IDE. I received the package and it is from SunFounder. Will this work with the IDE on the website and the Arduino I have from Radio Shack?

body:
Use the latest official Arduino IDE : [Arduino IDE][1]

Every Arduino Uno and all the clones are compatible. Some clones have the CH340G usb-serial chip and require an extra driver. If you look very hard, you might find an Arduino Uno board that is not version 'R3' and does not have SDA and SCL near the USB connector, or does not have the polyfuse for USB 5V, or uses an ATmega328 instead of a ATmega328P. There is a chance of maybe 1 in 10,000 that you find a wrong Uno board, and in most cases those are still compatible.

Do you mean the SunFounder RGB Matrix Driver Shield? That should be no problem.

  [1]: https://www.arduino.cc/en/Main/Software


message:
Arduino Uno unable to detect usb port on Mac OS Sierra 10.12.5

Few weeks ago my Arduino Uno (IDE version 1.8.2) detected the USB port and I was able to do some small IOT projects. I updated my OS to Sierra 10.12.5 and now suddenly the usb serial option has disappeared.

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

I followed this link : https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac  where it tells us to download and install the FTDI drivers separately. I tried that but it did not help.

Then I came across this post: https://forum.arduino.cc/index.php?topic=427825.0 where the user is having this same problem with MacOS Sierra. He suggested we remove the FTDI drivers and rely on Apple's drivers. So I removed the FTDI drivers from my Mac so it will use Apple's drivers.

Now even after doing all this when I connect my Arduino Uno to my Mac via the USB it does not get detected.

I removed the kext and pkg files for the FTDI drivers and deleted them completely, still when I open the System Report I still see the FTDI USB Serial Driver entry.

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

When I go to System Report > Hardware > USB I see this:

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

What is happening? Did the FTDI drivers got removed? If they did then why wont the serial usb port get detected on Arduino? If they are not removed completely then what did I miss?

  [1]: https://i.stack.imgur.com/0BhCH.jpg
  [2]: https://i.stack.imgur.com/vQYHA.png
  [3]: https://i.stack.imgur.com/ginO7.png

body: I installed the CH340 Driver and the board now shows the USB serial as port option: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver


message:
Is Fastled.io library suitable for SMD50500 led strip?

I was looking for a ready to use library to control my SMD5050 color led strip, and I stumbled across FASTLED.IO library , but after reading trough their website I didn't find anywhere the support for SMD5050 color LED strip. Does anyone knows another "ready to use" animation library? Are FASTLED.IO suitable anyway?
Thanks

body: No. FastLED is for addressable LEDs (like the WS2812B). Yours aren't addressable. You just need to set the colour you want with the PWM outputs of your Arduino. Changing the PWM values is not hard and you don't need a library to do it for you.


message:
Galileo Positioning System signal receiving

I want to determine my arduino's position. However, I want to use the *European* **Galileo** system instead of the *US-American GPS*.

Therefore, I searched for any possibilities receiving the Galileo signals. I figured out, that u-blox has some receivers: NEO 8 or the LEA 6 (firmware update required). However I did not find any arduino breakout board (, etc.) that uses these u-blox sensors or other Galileo-compatible hardware.

Does anyone know, how I could use the Galileo Position System?

body:
You need the hardware and a library. Most GPS modules use a serial communication, and I think that also the Galileo compatible boards use serial communication. That makes them compatible with most microcontrollers and also with Arduino boards.

I could find a few shields that can be attached to an Arduino board.
This one is in development at the moment: [Kickstarter shield with Galileo][1]
This one is compatible via the serial pins: [GA-001 Multi GNSS Ublox][2]
There is a "[NEO-M8N][3]" shield and maybe one or two others.

All those boards are very new, and I don't know if they come with a library for an Arduino. Perhaps you have to wait a few months and then it should be a lot easier to buy a complete functioning module with a library.

Before buying a module, confirm that there is a library for Arduino or good documentation to write your own library.

  [1]: https://www.kickstarter.com/projects/sodaq/the-first-nb-iot-shield-for-arduino-supported-by-t
  [2]: https://www.tindie.com/products/jrobi772/ga-001-multi-gnss-ublox-development-module/
  [3]: http://www.ebay.com/itm/NEO-M8N-GPS-Shield-for-Arduino-Indoor-Positioning-GPS-Galileo-GLONASS-BeiDou-/272086464137


message:
How can Arduino know Wire.available() is true or false?

In this part of code

    void readFrom(byte device, byte fromAddress, int num, byte result[]) {
      Wire.beginTransmission(device);
      Wire.write(fromAddress);
      Wire.endTransmission();
      Wire.requestFrom((int)device, num);
      int i = 0;
      while(Wire.available()) {
        result[i] = Wire.read();
        i++;
      }
    }

How can Arduino know that Wire.availble() is true or false?
----------------------------------------------------------------
I thought that when the microcontroller "reads" the value from the sensor, in pieces of 8 bits, he reads from 0 (n) to 5 (n+5) at the I2C address of the MPU-6050, and when he increments 6 it finds nothing, but this is my conclusion, i am not sure about it.
[![enter image description here][1]][1]

I am studying how Serial.available [works][2] and how the circular buffer works for the data comunication, because available() [inherits from the Stream utility class.][3]

The entire code is the following taken from  [this question][4]

      #include <Wire.h> //The I2C library

    int gyroResult[3], accelResult[3];

    //Function for writing a byte to an address on an I2C device
    void writeTo(byte device, byte toAddress, byte val) {
      Wire.beginTransmission(device);
      Wire.write(toAddress);
      Wire.write(val);
      Wire.endTransmission();
    }

    //Function for reading num bytes from addresses on an I2C device
    void readFrom(byte device, byte fromAddress, int num, byte result[]) {
      Wire.beginTransmission(device);
      Wire.write(fromAddress);
      Wire.endTransmission();
      Wire.requestFrom((int)device, num);
      int i = 0;
      while(Wire.available()) {
        result[i] = Wire.read();
        i++;
      }
    }

    //Function for reading the gyros.
    void getGyroscopeReadings(int gyroResult[]) {
      byte buffer[6];
      readFrom(0x68,0x1D,6,buffer);
      gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
      gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
      gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
    }

    //Function for reading the accelerometers
    void getAccelerometerReadings(int accelResult[]) {
      byte buffer[6];
      readFrom(0x53,0x32,6,buffer);
      accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
      accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
      accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
    }

    void setup() {
      Wire.begin();            //Open I2C communications as master
      Serial.begin(9600);    //Open serial communications to the PC to see what's happening

      writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
      writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
      writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
      writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
    }

    void loop() {
      getGyroscopeReadings(gyroResult);
      getAccelerometerReadings(accelResult);

      Serial.print(gyroResult[0]);
      Serial.print("\t");
      Serial.print(gyroResult[1]);
      Serial.print("\t");
      Serial.print(gyroResult[2]);
      Serial.print("\t\t");
      Serial.print(accelResult[0]);
      Serial.print("\t");
      Serial.print(accelResult[1]);
      Serial.print("\t");
      Serial.print(accelResult[2]);
      Serial.print("\n");

      delay(50);
    }

Minor Question
--------------

I am trying to undestand the difference between the register and the device address, but i did find anything on my book.
[![enter image description here][5]][5]

  [1]: https://i.stack.imgur.com/19mTn.png
  [2]: https://arduino.stackexchange.com/questions/37038/serial-available-function-for-arduino
  [3]: https://www.arduino.cc/en/Reference/WireAvailable
  [4]: https://arduino.stackexchange.com/questions/8738/understanding-digital-imu-6dof-sketch
  [5]: https://i.stack.imgur.com/IWZyu.png

body:
The simple answer is that the Arduino Wire library has an internal buffer, and it can bring in characters and have them sitting there ready for you to pick them up.

It can also sense a total disconnect because of the way it uses both data pins to establish communications.  It is more like a current loop than a simple one-is-transmit-and-the-other-is-receive.  If it disconnects the Arduino knows it is not available.

Kudos on going to the documentation, by the way.


message:
Expected unqualified ID before numeric constant

After debugging and having some conflicting declarations about analog pins, I finally thought it was done, after compiling I got this error:

    32:0,
    1:
    31:12: error: expected unqualified-id before numeric constant

    2:5: note: in expansion of macro 'B1'

I can't understand what this means. What's wrong with my code down here?

    // don't judge me if it's too long and overcomplicated :P I'm still new xD
    int AA1 = 0;
    int B1 = 1;
    int C1 = 2;
    int D1 = 3;
    int AA2 = 4;
    int B2 = 5;
    int C2 = 6;
    int AA3 = 8;
    int B3 = 9;
    int C3 = 10;
    int D3 = 11;
    int B4 = 12;
    int C4 = 13;
    int sec = 0;
    int min1 = 0;
    int min2 = 0;
    int hour1 = 8;
    bool hour2 = 0;

    void setup() {
      pinMode(AA1, OUTPUT);
      pinMode(B1, OUTPUT);
      pinMode(C1, OUTPUT);
      pinMode(D1, OUTPUT);
      pinMode(AA2, OUTPUT);
      pinMode(B2, OUTPUT);
      pinMode(C2, OUTPUT);
      pinMode(AA3, OUTPUT);
      pinMode(B3, OUTPUT);
      pinMode(C3, OUTPUT);
      pinMode(D3, OUTPUT);
      pinMode(B4, OUTPUT);
      pinMode(C4, OUTPUT);
    }

    void loop() {
      OutputOn();
      delay(1000);
      sec++;
      if(sec == 60) {
        sec = 0;
        min1++;
          if(min1 == 10) {
          min1 = 0;
          min2++;
            if(min2 == 6) {
            min2 = 0;
            hour1++;
              if(hour1 == 10) {
              hour1 = 0;
              hour2 = 1;
            }
            if(hour2 == 1, hour1 == 3) {
              hour1 = 1;
              hour2 = 0;
            }
          }
        }
      }
    }

    void OutputOn() {
      digitalWrite(B1, LOW);
      digitalWrite(C1, LOW);
      digitalWrite(D1, LOW);
      digitalWrite(A2, LOW);
      digitalWrite(B2, LOW);
      digitalWrite(C2, LOW);
      digitalWrite(A3, LOW);
      digitalWrite(B3, LOW);
      digitalWrite(C3, LOW);
      digitalWrite(D3, LOW);
      digitalWrite(B4, LOW);
      digitalWrite(C4, LOW);
      if(min1 == 1) { digitalWrite(AA1, HIGH); }
      if(min1 == 2) { digitalWrite(B1, HIGH); }
      if(min1 == 3) { digitalWrite(B1, HIGH); digitalWrite(AA1, HIGH); }
      if(min1 == 4) { digitalWrite(C1, HIGH); }
      if(min1 == 5) { digitalWrite(C1, HIGH); digitalWrite(AA1, HIGH); }
      if(min1 == 6) { digitalWrite(D1, HIGH); digitalWrite(B1, HIGH); }
      if(min1 == 7) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); digitalWrite(B1, HIGH); }
      if(min1 == 8) { digitalWrite(D1, HIGH); }
      if(min1 == 9) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); }
      if(min2 == 1) { digitalWrite(AA2, HIGH); }
      if(min2 == 2) { digitalWrite(B2, HIGH); }
      if(min2 == 3) { digitalWrite(B2, HIGH); digitalWrite(AA1, HIGH); }
      if(min2 == 4) { digitalWrite(C2, HIGH); }
      if(min2 == 5) { digitalWrite(C2, HIGH); digitalWrite(A2, HIGH); }
      if(min2 == 6) { digitalWrite(C2, HIGH); digitalWrite(B2, HIGH); }
      if(hour1 == 1) { digitalWrite(AA3, HIGH); }
      if(hour1 == 2) { digitalWrite(B3, HIGH); }
      if(hour1 == 3) { digitalWrite(B3, HIGH); digitalWrite(AA3, HIGH); }
      if(hour1 == 4) { digitalWrite(C3, HIGH); }
      if(hour1 == 5) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); }
      if(hour1 == 6) { digitalWrite(C3, HIGH); digitalWrite(B3, HIGH); }
      if(hour1 == 7) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); digitalWrite(B3, HIGH); }
      if(hour1 == 8) { digitalWrite(D3, HIGH); }
      if(hour1 == 9) { digitalWrite(D3, HIGH); digitalWrite(C3, HIGH); }
      if(hour2 == 1) { digitalWrite(B4, HIGH); digitalWrite(C4, HIGH); }
    }

It's supposed to be code for a clock (if it wasn't obvious enough) hooked up to 4 7-segment decoders, also connected to 4 7-segment LED displays.

body:
Bad luck. There is a file within Arduino called "binary.h", and it contains a define called "B1". Which means you may not use "B1" as a variable. In my opinion, that file "binary.h" is totally unnecessary.

In the preferences you can turn on extra output for the compiler and turn on line numbers. The compiler will tell what is wrong, but you have to know how the compiler does that. The first compiler error is the most important.

"*.../hardware/arduino/avr/cores/arduino/binary.h:31:12: error: expected unqualified-id before numeric constant #define B1 1*" means that the compiler was reading the file "binary.h" and at line 31 it noticed something it did not understand and it has to do with "B1".


message:
How do I use an ATMega 328 (not P) chip with an Arduino board?

I just burned the bootloader on an ATMega328 chip and then I put in on the Arduino board. But when I try to upload a program to it, it says programmer not in sync and programmer not responding.

For burning the bootloader I changed the address in the avrconfig file and reset it back to the original one. Do I need to keep changing the address of the board?

How do I use this as a normal Arduino board, as I fried my original chip? Do I need to get an ATMega328P chip?

body:
You can force the 'P' bootloader into it and use it as an Arduino board. The extra possibilities of the 'P' are not used by the standard Arduino libraries and when uploading it does check the bootloader but it does not check the chip signature.

I think you have already done this. Perhaps something else is wrong.


body:
So I found the solution:

Here is [the link][1] to the method that worked for me. I think the reason my previous method didn't work was because of fuses for the clock as mentioned by Majenko in the comments.

  [1]: http://3g1l.com/blog-burn-bootloader-blank-atmega328atmega328p-arduino-uno


message:
Custom boards list

Is there a simple way to create or modify my boards list? I find having a full library listing confusing. I have about 6 boards I program regularly, but using the listings from the board manager gives me about 60 things to look through, which gets tedious fast.

Here is a list of MCUs I frequently use:

 - Teensy2.0
 - Adafruit Trinket 16Mhz
 - Adafruit Trinket Pro 16MHz
 - Adafruit Circuit Playground
 - Adafruit feather Huzzah
 - Arduino Uno R3

How can I make a boards list that only includes the boards I own?

body: Throwing out the unneeded boards from the boards.txt files will do what you want.


message:
GSM SIM900A SMS content not displaying

I am trying to read messages sent from my mobile to a GSM SIM900A module on my Arduino Serial monitor. Neither does the AT+CMGR command nor does the AT+CMGL command display SMS content. I also tried increasing the receiver buffer size in the SoftwareSerial Library but to no avail. I am simply trying to read 'check123'. I want to further store the SMS received as a string for further processing. But I am stuck with no display of SMS content on the serial monitor.

My code is:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(9, 10);
    String content = "";
    char character;
    int i;

    void setup() {
      mySerial.begin(9600);
      Serial.begin(9600);
      delay(100);
    }

    void loop() {
      ReceiveSMS();
      delay(2000);
    }

    void ReceiveSMS() {
      mySerial.println("AT+CMGF=1");
      delay(2000);
      toSerial();
      mySerial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
      delay(2000);
      toSerial();
      mySerial.println("AT+CMGL=\"ALL\"\r");
      delay(5000);
      toSerial();
      mySerial.println("AT+CMGD=1,4");
      delay(2000);
      toSerial();
    }

    void toSerial() {
      while (mySerial.available() != 0) {
        Serial.write(mySerial.read());
      }
    }

Output is:

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

**Edit:**

SoftwareSerial.cpp file. I have marked the area where I have changed the value from 64 to 256 according to some previous help post.[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/sqctz.png
  [2]: https://i.stack.imgur.com/ropPO.png

body:
Your code is absolutely correct. As I tested it with my Mega with Serial3 connected to GSM SIM900. I think there is something fishy about SoftwareSerial. Double-check the location of SoftwareSerial.

>C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial\src

Maybe you can see if RAM usage is exceeding the safe limit. Here is my output:

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

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


message:
HX711 sporadic wrong values

Am interfacing HX711 with arduino to measure the load of something. However, in my project, I need to continuously monitor the load.

I get fairly accurate values most of the time however, at times I suddenly get a junk value. For example, I call the weight function every 3 seconds and I have placed a 10kg weight, this is what I get. 17.25 is the concern.

10.04, 10.03, 17.25, 10.04, 10.03, 10.03

Am using HX711 library and my process function is a simple call as shown below.

    float Processweight()
    {
      Serial.print(scale.get_units(40), 2);

      scale.power_down();              // put the ADC in sleep mode
      delay(500);
      scale.power_up();
    }

is there something that am missing? What could cause the wrong values?

body:
> I get fairly accurate values most of the time however, at times I suddenly get a junk value.

if you use the ebay board, it has the incorrect grounding, which may contribute to the sporadic values you saw.

> For example, I call the weight function every 3 seconds

poor quality libraries could be another possibility.

I have used the board quite extensively and aside from its tempco, it is fairly reliable. you can see here: https://dannyelectronics.wordpress.com/2015/10/25/a-hx711-based-milliohm-meter/

when everything is done right (and in a constant temperature environment), it has very good consistency.


body: Finally I got this right by adding a code to check if 5 consecutive values are fairly close enough and only then respond. That way I was able to flush out sudden changes. However, I still am not sure as to what is causing that jump.


message:
Arduino 101 I/O voltage levels

As per the [Arduino 101 schematic][1].

The Arduino 101 has level shifters (TI make LSF0108) connected to the I/O ports I guess these are to make them Arduino compatible(5V) since the Intel Curie Module is 3.3V rated.

I have 2 doubts regarding this

1. The level shifters are also connected to the analog pins so I was wondering how do these shifters pass through analog signals?

2. I have some 3.3V sensors that I want to interface to the Arduino 101 via I2C. My question is can I use 3.3V levels at the I/O ports or am I restricted to 5V?

TIA

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino101-REV4Schematic.pdf

body:
An [*Exploring the I/O Performance of the Arduino 101* webpage by Dan Watson](http://syncchannel.blogspot.com/2016/01/exploring-io-performance-of-arduino-101.html) has a number of relevant comments:

>The board uses three Texas Instruments LSF0108 level translators to accommodate all of the I/O lines (including the analog inputs). This is an interesting part. It's not really a level "shifter", and it's not a buffer. The Curie is still sourcing and sinking current to the pins, but the voltage levels are clamped at 3.3V on the Curie's side of the chip. In this regard it's kind of like a fancy analog switch. The on resistance of each signal path is in the neighborhood of 10 ohms.

Somewhat later in the article:

> Analog Input Linearity:  Next I tested the analog inputs. I was curious if the level translators affect the accuracy of the readings. I applied a DC voltage on pin A5, starting at 0V and increasing to 3.3V in 100 mV steps. At each step, I recorded the 10-bit analog-to-digital (ADC) readings reported by the Arduino 101. I then created a graph of the data, which is shown [on the webpage]. As you can see, the results are pretty linear across the entire input range. Spot-checking a few values, I found that there might have been a +20mV bias on the readings at the top end of the scale.

To summarize:  As a consequence of being like an analog switch, the LSF0108 allows the Curie's analog input pins to accept analog inputs, and apparently it works ok.

Regarding the second question, whether 3.3 V levels are ok at the I/O ports, I think they are.  See the article mentioned above for more comments.  Here is one that may be relevant:

>Digital Input Logic Transitions:
I applied a DC voltage to pin D7 and varied it up and down while the Arduino 101 reported the logic state in the serial monitor. This was done in order to discover the logic transition levels. Going from high to low, it returned a low state after crossing 1.26V. Going from low to high, however, the transition occurred at 1.55V.

---

*Edit 1:*  Regarding two questions in a comment...

> 1. What is the function of the level translators.. do they actually map the 0 to 5V levels to 0 to 3.3V on the curie side. ?

See the LSF0108 datasheet.  The LSF0108 has eight A, B pairs: (A1,B1);  (A2,B2); ... (A8,B8).  If you drive Ai low, Bi goes low too; and vice versa, if you drive Bi low, Ai goes low too.  That translates low to low. If neither side is driven low, connected inputs can pull up to an individual-pullup level but not higher than a reference level (VREFA or VREFB).  This translates high to high.

> 2. If I give a 0 to 5V analog voltage at the headers will the 3.3V to 5V level part of the signal be lost, I mean does the board only take care of the 0 to 3.3V part of the signal and the adc will give max counts at 3.3V?

It *should* be 'lost', because as noted in the Curie datasheet's *Table 2-5. ADC - DC I/O specifications*, the AIN Full-scale input range is ≤ ADC_3P3_VCC and ≤ AON_IO_VCC.  (The latter voltage is 1.8 or 3.3 V.)  I'm not clear on why the LSF0108 doesn't interfere with ADC measurements.  Maybe the switches operate in a linear mode when pullups are turned off?


message:
Reading pulse train with DC offset

One of the analog inputs to Arduino is a pulse train with DC something like 1.5V to 3.9V pulse. This of course changes by time and Im only interested in the difference voltage (peak-to-valley). Like I want Arduino to measure (3.9V-1.5V) in the loop. I can use two analog inputs if there's no other way.

How to code this kind of measurement?
Does anybody have experience with this?

duty cycle is 50% freq 3.3kHz.

body:
The proper method to use depends in part on what the data is for, and on what other processing your loop needs to do.  The following example assumes there is nothing to do except compute the difference between the highest and lowest readings from among the most recent 8.

    enum { nReads = 8 }; // # of readings = 2**3
    enum { rMask = 7 };  // index-mask of 3 bits
    enum { aIn = A3 };   // analog input pin #
    int reads[nReads];
    byte rindex=0;

    void loop() {
      int vhi, vlo, vdiff, r;
      r = reads[rindex] = analogRead(aIn); // Analog read takes about .1 ms
      vhi=0; vlo=1024;
      for (byte i=0; i<nReads; ++i) {
        if (r > vhi) vhi = r;
        if (r < vlo) vlo = r;
      }
      rindex = (rindex+1) & rMask;
      vdiff = vhi - vlo;
      //
      // In this section, scale or use or report vdiff
      //   ...
    }

An analog read takes about 104 μs.  That, plus any time taken to scale, use, or report `vdiff`, will be the major determinant of how rapidly `loop()` runs, because the `for` loop that calculates `vhi` and `vlo` should take less than 10 or 15 μs.

For example, if `loop()` takes 125 μs per pass, the code will get about one reading per half cycle of input.  (3.3 KHz is 303 μs per full cycle.)  This will produce a steady precession of where the analog readings are taken within the input waveform's cycle.  If that phenomenon is undesirable, you may need to use interrupt-triggered ADC reads.

If you don't need new differences as frequently as the above code produces them, you could instead on demand take several readings in a row and produce a result.  For example:

    int getDiff() {
      enum { nReads = 6 };
      enum { aIn = A3 };   // analog input pin #
      int vhi=0, vlo=1024, r;
      for (byte i=0; i<nReads; ++i) {
        r = analogRead(aIn); // Analog read takes about .1 ms
        if (r > vhi) vhi = r;
        if (r < vlo) vlo = r;
      }
      return vhi - vlo;
    }

    void loop() {
      int vdiff;
      if (readingIsNeededNow) {
        vdiff = getDiff();
        // do stuff with voltage difference
      }
      // etc
    }


message:
Renaming folders in Arduino Uno' SD card

I want to rename folders through the SD shield but it does not rename them, because It renames It in another default name
How Can i rename it using the name that I want?

body:
According to this post (https://forum.arduino.cc/index.php?topic=73265.0) this library should be able to rename the folders (https://github.com/greiman?tab=repositories) but there are a lot of posts out there saying they are having problems.

It might be worth checking you can rename them on a PC, there may be problems with name lengths etc that will just complicate matters.


message:
Switch case inside a switch case with serial input

I'm trying to build a test program for some hardware. Basically I want to select the piece of hardware with the outer switch case then select the test with the inner switch case. I'm trying to accomplish this by using serial input in the Arduino IDE monitor.

I can't make it work whatever I do. I either end up stuck in the outer switch case or I never enter the inner switch case where I want to select the test.

I've got a bit of code below:

    char select_addon;
    char select_test;

    void setup() {
      Serial.begin(9600);
      Serial.println("(1) PB1");
      Serial.println("(2) PB2");
      Serial.println("(3) PB3");
    }

    void loop() {
      if (Serial.available() > 0) {
        select_addon = Serial.read();
        switch (select_addon) {
          case '1':
            Serial.println("Test");
            if (Serial.available() > 0 ) {
              select_test = Serial.read();
              switch (select_test) {
                case '4':
                  Serial.println(" Test 1.1");
                  break;
                case '5':
                  Serial.println(" Test 1.2");
                  break;
                case '6':
                  Serial.println(" Test 1.3");
                  break;
              }
            }
            break;
          case '2':
            Serial.println("TEST 2");
            break;
          case '3':
            Serial.println("TEST 3");
            break;
        }
      }
    }

Obviously this isn't the finished code, but it's the switch case structure I've been trying to implement. Any suggestions on how I can enter the inner switch case?

body:
What happens of the `if (Serial.available() > 0)` call fails?  That's the problem, because when there isn't anything available it's skipping the second switch statement.

On a point of style it actually might be better to implement the inner switch as a separate function. Imagine what your code will look like with 5 cases in the outer switch, each with 5 cases in the inner switches.

Also it might be worth, for debugging purposes, to always have a default statement, at least then you will know what key it was that you pressed.


message:
Arduino Uno R3 stuck in DFU mode/Port not recognized

I have an Arduino Uno R3 that is simultaneously stuck in DFU mode and won't be recognized as a port in the Arduino IDE on my Macbook Pro (El Capitan). Upon receiving power, the Arduino is automatically in DFU mode (I can use dfu-programmer via Terminal to access it, even though the Arduino is not 'recognized'), and by using the process normally reserved for entering DFU mode (connecting the two pins on the left side of the ICSP) the Arduino actually exits DFU mode. However, by neither entering or exiting DFU mode, the Arduino is still not 'recognized' as a port by the Arduino IDE. Prior to this happening, I had been attempting to flash files to the bootloader with success (I got this same predicament in that process previously once, but I do not know what happened differently).

Thanks,
wblegoboy

body:
It sounds like your ATMega16U2 has lost its CDC/ACM firmware and is entering DFU mode by default to allow you to install firmware.

Installing the CDC/ACM firmware using `dfu-programmer` would get it working again.


message:
Bluetooth Communication Not Working with DC Power But Works With USB Power?

I am running a HM-10 Bluetooth Low Energy (BLE) module to transmit serial data (using SoftwareSerial) from an analog sensor onboard my Arduino Uno to a serial terminal app on my Android phone. When I power the Arduino with a USB power bank, the data transmits flawlessly.

When I tried to power the Arduino with a 9V battery through the DC power jack instead of USB power, the BLE module connects to my phone, but no data is transmitted when a serial connection is established.

Any ideas why this would be?

body:
A PP3 battery is not a suitable power source for an Arduino.

For battery powered operations I would recommend a set of AA batteries with between 6 and 8 volts (if you don't care about bulk) or a Li-Ion battery (or two) and a suitable buck or boost (depending on number of cells) regulator to bypass the inefficient linear regulators on the Arduino.