# Question
Title: Why Would Declaring a Global Variable Change How An Unrelated Conditional is Evaluated?
Here is my entire sketch. This is my first Arduino project. I included all of it because I don't know what's relevant. I am printing out to a 4-digit 7 segment display. To do that I use sprintf to format the contents of a char\[\] called tempString and that gets sent to the display. I declared a new local char\[\] each time I needed one. I had a problem with the Arduino Pro Mini running out of memory. I tried declaring a global chart\[\] and reusing it when I needed it, but that changed the way the program executed. That was the only change I made.

After I made that change, the Arduino would always evaluate this true:

```
 if (countDownTimer.TimeCheck(0, 0, 0))

```

The CountDownTimer was always evaluating to a time of 0, even after it had been assigned a valid time and the timer hadn't started running. I verified I was setting it correctly, but by the time the conditional was reached, the Timer was back to 0.

If I remove the global declaration for tempString\[\] and go back to locals the logic works as designed. I made tempString\[\] smaller as a local and that seems to have fixed the memory issue but I would like to know why declaring a global caused a problem.

```
 #include <SoftwareSerial.h>
#include <CountUpDownTimer.h>
#include <EEPROM.h> //Needed to access the eeprom read write functions

//values for EEPROM
int stepsToWrite = 0;
int stepsToRead = 0;
int priorValue = 0;

// addresses to write to and read from
const int thirtySecondAddress = 0;  // constant
const int threeMinuteAddress = 4;   // constant
int addressToUse = 0;   // this will change depending on time user selects

// set uo the serial display
const int displayTx = 5;  // the pins we need to create the software serial instance
const int displayRx = 7;   // we will only use Tx
SoftwareSerial s7s(displayRx, displayTx);

//set up the timer
CountUpDownTimer countDownTimer(DOWN);
const long displaychangeInterval = 10000; // in milliseconds
const long countdownInterval = 1000; // in milliseconds

long previousMillis = 0; // for changing between time left and step count
long previousTimerMillis = 0;  // for updating the display with the new time
const int thirtySecondTime = 30;
const int threeMinuteTime = 180; // 3 minutes expressed as seconds
int timerStartValue = 0;  // needed for some control logic

// booleans to control what is displayed
bool doDisplayStepCount = false;
bool doDisplayCountDown = false;
bool doDisplayHighScore = true;  // we want to display this at startup

// set up the buttons
const int timerbuttonPin = 6;     // the number of the timer pushbutton pin
const int resetbuttonPin = 4;     // the number of the reset button pin

int timerbuttonPushCounter = 0;   // counter for the number of button presses
int timerbuttonState = 0;         // current state of the button
int timerlastButtonState = 0;     // previous state of the button

int resetbuttonPushCounter = 0;   // counter for the number of button presses
int resetbuttonState = 0;         // current state of the button
int resetlastButtonState = 0;     // previous state of the button

int stepsTaken = 0; // the number of steps (jumps)
boolean timerStarted = false;

// for the force resistor
const int FSR_PIN = A0; // Pin connected to FSR/resistor divider
const float VCC = 5.10; // Measured voltage of Ardunio 5V line
const float R_DIV = 3265.0; // Measured resistance of 3.3k resistor

double currentForce = 0;
double previousForce = 0;
boolean previousPos = false;
boolean currentPos = false;

boolean doChangeDisplay = false;

char tempString[4];
void setup() {

  boolean debug = true;
  if (debug)
  {
    EEPROMWriteInt(thirtySecondAddress, 0);  // zero out EEPROM
    EEPROMWriteInt(threeMinuteAddress, 0);  // zero out EEPROM
  }
  // start serial connection
  Serial.begin(9600);

  // set up pins
  pinMode(FSR_PIN, INPUT);
  pinMode(timerbuttonPin, INPUT);
  pinMode(resetbuttonPin, INPUT);

  // serial display
  // Must begin s7s software serial at the correct baud rate.

  // Clear the display
  //  The default of the s7s is 9600.
  s7s.begin(9600);
  //clearDisplay();  // Clears display, resets cursor
  // s7s.print("-HI-");
  // delay(1000);

  displayHighScores();

}

void loop() {

  // Serial.print("freeMemory()=");
  // Serial.println(freeMemory());

  //  Serial.println("Starting loop");
  // button pushes
  // if tinmerbuttonPushCounter = 1, set timerValue to 30 seconds
  // if 2 pushes, set to 3 minutes and reset push counter to 0

  //Serial.println("Reading timer button, state is: " + timerbuttonState);
  timerbuttonState = digitalRead(timerbuttonPin);
  // Serial.println("Reading reset button, state is: " + resetbuttonState);
  resetbuttonState = digitalRead(resetbuttonPin);

  // compare the buttonState to its previous state

  if (timerbuttonState != timerlastButtonState)
  {
    Serial.println("selecting time");
    if (timerbuttonState == HIGH)
    {

      doDisplayHighScore = false;
      timerbuttonPushCounter++;
      // if the current state is HIGH then the timer button went from off to on:
      if (timerbuttonPushCounter == 1)
      {
        doChangeDisplay = false;
        doDisplayCountDown = true;
        timerStartValue = thirtySecondTime;
        addressToUse = thirtySecondAddress;
        Serial.println("timer button pushed: " + String(timerbuttonPushCounter));
        Serial.println("start value: " + String(timerStartValue));
        clearDisplay();
        setDecimals(0b010000);  // Turn on colon
        sprintf(tempString, "%04d", thirtySecondTime);
        Serial.println("Timer set to: " + String(tempString));
        s7s.print(tempString);
      }

      else if (timerbuttonPushCounter == 2)
      {
        timerStartValue = threeMinuteTime;
        addressToUse = threeMinuteAddress;
        doChangeDisplay = true;

        int timerinminutes = timerStartValue / 60;
        Serial.println("timer button pushed: " + timerbuttonPushCounter);
        Serial.println("start value  " + timerStartValue);
        timerbuttonPushCounter = 0;
        clearDisplay();
        setDecimals(0b010000);  // Turn on colon
        sprintf(tempString, "0%d00", timerinminutes);
        Serial.println("Timer set to: " + String(tempString));
        s7s.print(tempString);
      }
    }  // end of if timer state high

    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  timerlastButtonState = timerbuttonState;

  // for reset button, logic is much simpler
  // if state is high, button has been pushed so reset everything
  if (resetbuttonState != resetlastButtonState)
  {
    if (resetbuttonState == HIGH)
    {
      Serial.println("Reset button pushed!");
      doDisplayHighScore = true;
      resetStepCounter();
      // Delay a little bit to avoid bouncing
      delay(50);
    }
  }

  resetlastButtonState = resetbuttonState;

  // step pad logic
  int fsrADC = analogRead(FSR_PIN);
  previousForce = currentForce;
  currentForce = calculateForce(fsrADC);
  // trying this using force values
  // when we step force is always positive
  // when we lift our foot force is always negative

  if (currentForce > 0)
  {
    currentPos = true;
    Serial.println("Force detected!");
    delay(1000);
  }
  if (previousForce < 0)
  {
    previousPos = true;
  }

  if (currentPos && previousPos)
  {
    // start the timer on the first step
    if (!timerStarted)
    {
      Serial.println("First steop!");
      timerStarted = true;
      // Serial.println("Timer start value: " +String(timerStartValue));
      countDownTimer.SetTimer(0, 0, timerStartValue);
      countDownTimer.StartTimer();

      //  char tempstring[10];
      sprintf(tempString, "%4d", countDownTimer.ShowMinutes(), countDownTimer.ShowSeconds());
      Serial.println("Timer set to: " + String(tempString));
      //  Serial.println("Timer started");
      //  delay(2000);
      doDisplayCountDown = true;
    }

    stepsTaken++;
    Serial.println("Step Detected!");
    currentPos = false;
    previousPos = false;
  }

  // if timer is 0 we have run out of time
  // this needs to be done here as it must always be done and can't depend
  // on displayCountDown being true

  if (timerStarted)
  {
    if (countDownTimer.TimeCheck(0, 0, 0))
    {
      //Serial.println("out of time");
      //delay(500);
      timerStarted = false;  // set timerRunning to false
      countDownTimer.StopTimer();
      if (timerStartValue == thirtySecondTime)
      {
        WriteHighScore(thirtySecondAddress, stepsTaken);
      }

      if (timerStartValue == threeMinuteTime)
      {
        WriteHighScore(threeMinuteAddress, stepsTaken);
      }
      Serial.println("wrote high score");
      delay(500);
      // clearDisplay();
      //displayStepCount();
      // resetStepCounter();

      // displayCountDownTimer();
    }

    //else

    if (!(countDownTimer.TimeCheck(0, 0, 0))) // && timerStarted)
    {

      countDownTimer.Timer(); // run the timer
      Serial.println("Timer is running");
      // timer logic
      // every 10 seconds, change booleans on what gets displayed
      unsigned long currentMillis = millis();
      // the last 10 seconds only display the step count
      //if (countDownTimer.TimeCheck(0, 0, 10))
      // {
      //
      //   displayStepCount();
      // }

      // else
      //  {

      if (doChangeDisplay)
      {
        if ((currentMillis - previousMillis) >= displaychangeInterval)
        {
          // save the last time we checked the interval
          //  Serial.println("10 second interval!");
          previousMillis = currentMillis;

          // if this is true, set it to false
          // set the countdown display to true
          if (doDisplayStepCount)
          {
            doDisplayStepCount = false;
            doDisplayCountDown = true;
          }

          else
            // countdown display is true, so set it to false
            // and set stepcount display to true
          {
            doDisplayStepCount = true;
            doDisplayCountDown = false;
          }

        }
      }

      // only display step count if this is the interval to do it
      if (doDisplayStepCount)
      {
        displayStepCount();
      }

      // only display countdown timer if this is the 10 second interval to do it
      if (doDisplayCountDown)
      {
        displayCountDownTimer();
      }

      //  }

    }
  }

}

// Send the clear display command (0x76)
//  This will clear the display and reset the cursor
void clearDisplay()
{
  s7s.write(0x76);  // Clear display command
}

// Turn on any, none, or all of the decimals.
//  The six lowest bits in the decimals parameter sets a decimal
//  (or colon, or apostrophe) on or off. A 1 indicates on, 0 off.
//  [MSB] (X)(X)(Apos)(Colon)(Digit 4)(Digit 3)(Digit2)(Digit1)
// (0b010000) - colon only
//  (0b111111) - all decimals
void setDecimals(byte decimals)
{
  s7s.write(0x77);
  s7s.write(decimals);
}

void resetStepCounter()
{
  timerbuttonPushCounter = 0;
  if (timerStarted)
  {
    countDownTimer.StopTimer();
    timerStarted = false;
  }

  // clean up
  stepsTaken = 0;
  clearDisplay();
  timerStartValue = 0;
  doDisplayHighScore = true;
}

void displayStepCount()
{
  setDecimals(0b000000);  // Turn off the colon
  // Will be used with sprintf to create strings
  sprintf(tempString, "%04d", stepsTaken);
  Serial.print("Steps taken: " + String(tempString));
  clearDisplay();
  s7s.print(tempString);
}

void displayCountDownTimer()
{
  // example formats
  //sprintf(tempString, "%4d", deciSecond); //Convert deciSecond into a string that is right adjusted
  //sprintf(tempString, "%d", deciSecond); //Convert deciSecond into a string that is left adjusted
  //sprintf(tempString, "%04d", deciSecond); //Convert deciSecond into a string with leading zeros
  //sprintf(tempString, "%4d", deciSecond * -1); //Shows a negative sign infront of right adjusted number
  unsigned long currentMillis = millis();
  int seconds = 0;
  int minutes = 0;

  // only update the display if 1 second has passed
  // if(currentMillis - previousTimerMillis >=  countdownInterval)
  // CountUpDownTimer TimeHasChanged() returns boolean (in seconds)

  if (countDownTimer.TimeHasChanged())
  {
    // previousTimerMillis = currentMillis;
    seconds = countDownTimer.ShowSeconds();
    Serial.println("Time left: " + seconds);
    minutes = countDownTimer.ShowMinutes();
    sprintf(tempString, "%02d%02d", minutes, seconds);

    clearDisplay();
    setDecimals(0b010000);  // Turn on colon
    Serial.println(tempString);
    s7s.print(tempString);
  }
}
void EEPROMWriteInt(const int p_address, const int p_value)
{
  byte lowByte = ((p_value >> 0) & 0xFF);
  byte highByte = ((p_value >> 8) & 0xFF);

  EEPROM.write(p_address, lowByte);
  EEPROM.write(p_address + 1, highByte);
}

//This function will read a 2 byte integer from the eeprom at the specified address and address + 1
int EEPROMReadInt(const int p_address)
{
  byte lowByte = EEPROM.read(p_address);
  byte highByte = EEPROM.read(p_address + 1);

  return ((lowByte << 0) & 0xFF) + ((highByte << 8) & 0xFF00);
}

void WriteHighScore(int address, int value)
{
  // int valueRead = EEPROMReadInt(address);
  //if (valueRead < value)
  // {
  EEPROMWriteInt(address, value);

  delay(500);
  sprintf(tempString, "%04d", value);
  Serial.print("high score: " + String(tempString));
  clearDisplay();
  s7s.print("-HI-");
  delay(500);
  clearDisplay();
  s7s.print("SCOR");
  delay(500);
  clearDisplay();
  s7s.print(tempString);
  delay(500);

  // }
}
void displayHighScores()
{
  int thirtySecondScore = EEPROMReadInt(thirtySecondAddress);
  int threeMinuteScore = EEPROMReadInt(threeMinuteAddress);
  sprintf(tempString, "%04d", thirtySecondScore);
  Serial.println("thirty second score: " + String(tempString));
  sprintf(tempString, "%04d", threeMinuteScore);
  Serial.println("Three minute score: " + String(tempString));

  clearDisplay();  // Clears display, resets cursor
  s7s.println("-HI-");
  delay(1000);
  clearDisplay();
  Serial.println("SCOR");
  s7s.print("SCOR");
  delay(1000);
  clearDisplay();
  sprintf(tempString, "%04d", thirtySecondScore);
  Serial.println(tempString);
  s7s.print(tempString);
  delay(1000);

  clearDisplay();
  sprintf(tempString, "%04d", threeMinuteScore);
  Serial.println(tempString);
  s7s.print(tempString);
  delay(1000);
  clearDisplay();
}

float calculateForce(int pinvalue)
{
  // Use ADC reading to calculate voltage:
  float fsrV = pinvalue * VCC / 1023.0; // 1023 is # of units of voltage between 0 and 5V
  // Use voltage and static resistor value to
  // calculate FSR resistance:
  float fsrR = R_DIV * (VCC / fsrV - 1.0);
  // Serial.println("Resistance: " + String(fsrR) + " ohms");
  // Guesstimate force based on slopes in figure 3 of
  // FSR datasheet:
  float force;
  float fsrG = 1.0 / fsrR; // Calculate conductance
  // Break parabolic curve down into two linear slopes:
  force = (fsrG - 0.00075) / 0.00000032639;
  return force;
}

```

# Answer
> 3 votes
This line:

```
sprintf(tempString, "%04d", thirtySecondTime);

```

writes 5 characters to tempString, the four digits and a terminating null. You only gave the array room for four.

This:

```
Serial.println("Timer set to: " + String(tempString));

```

is a total waste of resources. If you want to talk about memory usage then don't use the String class and definitely don't use it where it simply is not needed.

Write that as:

```
Serial.print("Timer set to: ");
Serial.println(tempString);

```

or better yet from a memory standpoint as:

```
Serial.print(F("Timer set to: "));
Serial.println(tempString);

```

---
Tags: programming, arduino-pro-mini, sketch
---


# Question
Title: Servo starts to shake when I added SIM900.begin(19200);
Hello I'm working on this mini project. This project works this way, Whenever someone type wrong password, LCD will display "Access Denied" and send an alert to SMS using GSM module. I used 2 Arduinos for this project, The 1st Arduino is powered up by my laptop this is where the signal pins are connected the RX/TX of GSM is connected in (pin 10 and 11) respectively and the LCD is in pin (2-9) and Servo to (A4) . The second Arduino I used is powered up with a charger and used it for GSM power source it function well as it blinks every 2 sec. I'm really wondering why my servo is shaking whenever I add the SIM900.begin(9600); at the setup in Arduino IDE?

This is the code

```
#include <Keypad.h>
#include <Password.h>
#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#include <SoftwareSerial.h>
SoftwareSerial SIM900(10, 11);

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
Password password = Password( "9999" );
Servo myservo;

const byte ROWS = 4;
const byte COLS = 4;

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {7, 8, 9, 10};

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

void setup(){

  Serial.begin(9600);
  SIM900.begin(9600);

  myservo.attach(13);
  lcd.begin(16, 2);
  lcd.print("Arduino Password");
  lcd.setCursor ( 0, 1 );
  lcd.print (" Door  Lock ");
  delay ( 2000 );
  setup1();

}
void setup1(){

  lcd.clear();
  lcd.home();
  lcd.print("Enter your code:");
  keypad.addEventListener(keypadEvent);
}

void loop(){
  keypad.getKey();
}

//take care of some special events
void keypadEvent(KeypadEvent eKey){
  switch (keypad.getState()){
    case PRESSED:
        Serial.println(eKey);
        switch (eKey){
          case '4': checkPassword(); break;
          case '2': password.reset(); break;
          case '8': lock(); break;
          default: password.append(eKey);
     }
  }
}

void checkPassword(){
  if (password.evaluate()){
    lcd.clear();
    lcd.print("Access granted");
    delay(1000);
    unlock();
  }else{
    lcd.clear();
    lcd.print("Access denied");
    delay(2000);
    sendSMS();
    delay(1000);

  }
  password.reset();
  delay(1000);
  setup1();
}

void unlock(){
  lcd.clear();
  lcd.print("Unlocking...");
  delay(2000);
  pos = 90;
  myservo.write(pos);
  lcd.clear();
  lcd.print("Unlocked! Press");
  lcd.setCursor(0, 1);
  lcd.print("* to lock!");
  delay(1000);
}

void lock(){
  lcd.clear();
  lcd.print("Locking...");
  delay(1000);
  pos = 0;
  myservo.write(pos);
  setup1();
}
void sendSMS() {

  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
  SIM900.print("AT+CMGF=1\r");
  delay(100);
  SIM900.println("AT + CMGS = \"+6XXXXXXXXXX\"");
  delay(100);
  SIM900.println("Wrong password Typed");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  // Give module time to send SMS
  delay(5000);
}

```

# Answer
Servo.h use interrupts to generate the control signal. However, SoftwareSerial really messes interrupts up.

You can't use SoftwareSerial with anything that relies on interrupts for timing, like Servo.h.

Solutions:

1. Use a better Arduino with an unused hardware UART
2. Use an external hardware PWM controller to drive the servos
3. Use the internal hardware PWM (you'd need to find a library to do this) to drive the servos.
> 1 votes

# Answer
Both SoftwareSerial and Servo are trying to use the same hardware timer, Timer1. There are other servo libraries like ServoTimer2 that will allow you to use SoftwareSerial and there are other soft serial libraries that will allow you to use Servo. It is a pretty common topic that comes up a lot. If you search a little bit you should find several solutions.
> -1 votes

---
Tags: servo, gsm, simulator, keypad
---


title: Pilot the the reset line by two input

text:
# Question
Title: Pilot the the reset line by two input
I have two input signal that when activated have to restart the ardiuno board so I have to connect them to the RESET pin. As you know the arduino board have only one RESET pin so I can't connect both to the same pin. I think that a good idea is a circuit that takes the two inputs and activate the RESTART pin when one of the two is active. Have you any idea to solve that problem?

Thank you.

# Answer
> 1 votes
Just use diode logic.

The resistor is probably not needed because the Arduino has an internal pullup resistor.

This assumes that the two reset inputs are `active low`

simulate this circuit – Schematic created using CircuitLab

# Answer
> -1 votes
What you want is an AND gate (e.g., 74HC08, which contains 4 AND gates).

An AND gate is a chip which sets its output HIGH when *both* inputs to it are HIGH.

Symbolically it looks like:

simulate this circuit – Schematic created using CircuitLab

This, of course, is assuming that both your reset signals are *active low* \- that is, they are normally in the HIGH state, but when they want to reset the board they go LOW.

You can do the same thing with three transistors. Two transistors in series make a NAND gate (like an AND gate but the output is inverted), and a third makes a NOT gate to invert the output:

simulate this circuit

Note that R4 is optional, since the RESET pin already has a 10KΩ pullup resistor in it.

---
Tags: arduino-uno
---


# Question
Title: Why is dtostrf() not working for this one value?
I'm building a weather station using an ESP32 and BME280. I'm feeding the data via MQTT and Python into a database that is then used to make a nice dashboard for the data.

The MQTT message needs to be a char, and the sensor readings are floats, so I'm using `dtostrf()` to convert them. This works fine for the temperature and pressure readings, but for some reason not for the humidity reading.

I declare my variables:

```
float temp;
float hum;
float pres;

char mqttTemp[6];
char mqttHum[6];
char mqttPres[5];

```

Then I get my readings:

```
temp = mySensor.readTempC();
Serial.print("Temp: ");
Serial.print(temp);
hum = mySensor.readFloatHumidity();
Serial.print("Hum: ");
Serial.print(hum);
pres = mySensor.readFloatPressure();
Serial.print("Pres: ");
Serial.print(pres);

```

This returns:

`Temp: 25.57 Hum: 40.15 Pres: 97684.39`

Then I run the results through the function:

```
dtostrf(temp,4,2,mqttTemp);
dtostrf(hum,4,2,mqttHum);
dtostrf(pres,5,0,mqttPres);

```

Then I output these to Serial:

```
Serial.print("Temperature: ");
Serial.print(mqttTemp);
Serial.print("Humidity: ");
Serial.print(mqttHum);
Serial.print("Pressure: ");
Serial.print(mqttPres);

```

Which gives me:

```
Temperature: 25.57
------------------------------
Humidity:
------------------------------
Pressure: 97684

```

There is also no message sent via MQTT for humidity, but it works perfectly for the other two readings. What gives?

# Answer
What is happening is that the variables you declared for mqttTemp etc are stored in memory something like this

```
variable   memory address
mqttPres @ 1000-1004 (5 bytes)
mqttHum  @ 1005-1010 (6 bytes)
mqttTemp @ 1011-1015 (6 bytes)

```

For a start, you only have enough room (with the mandatory NUL byte string terminator) for 4, 5 and 5 characters

When you convert pressure, the NUL byte is being placed as the first byte in mqttHum, therefore, when printing mqttHum you get an empty string output (since the first byte is NUL)

To really see what's happening, here's some code that illustrates the issue

```
char mqttTemp[6] = "TTTTT";
char mqttHum[6] = "HHHHH";
char mqttPres[5] = "PPPP";
void setup() {
  float temp = 25.57;
  float hum = 40.15;
  float pres = 97684.39;

  Serial.begin(74880);
  // put your setup code here, to run once:
  delay(100);
  Serial.println("before");
  printThem();
  dtostrf(temp, 4, 2, mqttTemp);
  Serial.println("converted temp");
  printThem();
  dtostrf(hum, 4, 2, mqttHum);
  Serial.println("converted hum");
  printThem();
  dtostrf(pres, 5, 0, mqttPres);
  Serial.println("converted press");
  printThem();
}
void printThem()
{
  Serial.print("mqttPres ");
  Serial.print((unsigned long) &mqttPres, DEC);
  Serial.print(": ");
  for (int i = 0; i < 5; i++) {
    Serial.print((int) mqttPres[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttHum  ");
  Serial.print((unsigned long) &mqttHum, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttHum[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttTemp ");
  Serial.print((unsigned long) &mqttTemp, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttTemp[i], DEC);
    Serial.print(' ');
  }
  Serial.println();
}

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

}

```

The above outputs the following:

```
before
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 84 84 84 84 84 0
converted temp
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted hum
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 52 48 46 49 53 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted press
mqttPres 1073644748: 57 55 54 56 52
mqttHum  1073644753: 0 48 46 49 53 0
                     ^ ======== note the leading 0
mqttTemp 1073644759: 50 53 46 53 55 0

```

The simplest fix, of course, is to declare your variables with the correct size

```
char mqttTemp[7]; // because -10.00 takes 6 characters + 1 for NULL
char mqttHum[7];  // because 100.00 takes 6 characters + 1 for NULL
char mqttPres[6]; // because 97684 takes 5 characters + 1 for NULL - if pressure can reach 100000 then use 7 here as well

```

and then use `dtostrf` **correctly**, i.e. the second argument is the total width, including `.` and a possible `-`

```
dtostrf(temp,6,2,mqttTemp);
dtostrf(hum,6,2,mqttHum);
dtostrf(pres,5,0,mqttPres);

```
> 2 votes

---
Tags: esp8266, sensors, code-review
---


# Question
Title: Error - invalid conversion from 'char' to 'const char*', Not able to connect on pubnub server using node mcu
I have node mcu with ESP8266 wifi module. When i am trying to upload an example code then its not working.

This is the Error:-

```
inline PubSubClient* PubNub::subscribe(const char* channel, int timeout)

                      ^

exit status 1
invalid conversion from 'char' to 'const char*' [-fpermissive]

```

Code:-

```
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

#include <PubNub.h>

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

char pubkey = 'pub-c-4a9cdbca-5688-4939-a852-f63cf6743980';
char subkey = 'sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094';

char pubchannel = 'demo_keyset';
char subchannel = 'demo_keyset';

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

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

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

```

Code is taken from pubnub arduino github example - https://github.com/pubnub/arduino/blob/master/examples/AdafruitFeatherM0WINC1500/AdafruitFeatherM0WINC1500.ino

# Answer
> 1 votes
problem was in the declaration of API keys and channel on the above code

Here is the right code:-

```
const char * pubkey = "publisher key from your account";
const char * subkey = "subscriber key from your account";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

```

---
Tags: wifi, nodemcu
---


title: RGB LED lights and Arduino

text:
# Question
Title: RGB LED lights and Arduino
I am doing my thesis project which is a kinetic light/sound sculpture. My first step is to learn how to work with RGB LED lights and how to choose them and what other kinds of equipment I need.

I started to learn Arduino uno and learned how to light an LED, now I need to expand it much bigger. I want to be able to control each LEDs.

I want 30 meters LED light divided to 7 channels, in which each channel have a unique function that will trigger 7 channels of sound.

I hope I could use your help and thanks in advance for your time :)

# Answer
I suggest you to use RGB Led Driver like: WS2812. You can build led strip as long as you want.

There are a lot of example/tutorial using Arduino and Strip Led composed by **WS2812** Led Driver (For example, here there is a tutorial).

NB: You pay attention that using 30 meters strip led, you need an external power supply and you can't use 5V pin of Arduino, because Arduino doesn't supply sufficient power for supply a strip led too long.
> 2 votes

---
Tags: rgb-led
---


# Question
Title: Serial.print prints but lcd.print does not
The following code reads a txt file from a SD card, finds the corresponding character and prints the next 12 characters:

```
...
      char temp;
      byte who = random(1, 13); // 1 to 12
      temp = findName(who);
      Serial.print(who);
      Serial.print("  ==> ");
      Serial.println(temp);
...

    char findName (byte number) {
      char text[12];
      byte i;
      txt = SD.open("test.txt");
      txt.seek(12 * (number - 1));
      for (i = 0; i < 11; i++) text[i] = txt.read();
      txt.close();
      return text;
    }

```

But the following, on a LCD, does not. (setCursor, etc. ommited for clarity)

```
...
char temp;
byte who = random(1, 13); // 1 to 12
temp = findName(who);
lcd.print(who);
lcd.print("  ==> ");
lcd.print(temp);
...

```

I'm certain the cause is a variable data type mismatch, but I don't know how to solve it. Any help is appreciated.

Thank you.

# Answer
> 0 votes
In the `findName()` function, you declare a char array of name `text`. Internally, `text` is a pointer to a block of memory 12 bytes in size.

When you `return text` within the `findName()` function, you are passing back the pointer to the block of memory. The return type of `char` is inconsistent with the return command. But probably more problematic is that once `findName()` ends, the memory set aside for the `text` array is marked as unused. It is no longer reserved for holding anything and may be reallocated at any time by some other function or operation.

In C/C++, array variables do not refer to the entire array, but to the first element in the array. The fact that your program works with `Serial.print()` is probably just good luck. `lcd.print()` may declare some variable or buffer which overwrites what the `findName()` function had put in those 12 bytes.

There are many approaches to take to resolve this. One way is to declare char arrays in the "highest" scope in which it will be used, and to declare it with the largest size that you could ever see in the operation of your program.

In your case, you can:

```
...
      char temp[12];
      byte who = random(1, 13); // 1 to 12
      findName(temp, who);
      Serial.print(who);
      Serial.print("  ==> ");
      Serial.println(temp);
...

    void findName (char *text, byte number) {
      byte i;
      txt = SD.open("test.txt");
      txt.seek(12 * (number - 1));
      for (i = 0; i < 11; i++) text[i] = txt.read();
      txt.close();
    }

```

What this does:

1. `temp` is now the char array
2. `findName()` takes the pointer to the char array, and the number as arguments
3. `findName()` modifies `text`, which refers to the same block of already-allocated memory as `temp`, and that block of memory does not go away at the end of `findName()`.
4. Because `findName()` is not returning a value, it's return type is `void`.

---
Tags: serial, lcd, sd-card, display, print
---


title: Measure Sofware Serial write() time

text:
# Question
Title: Measure Sofware Serial write() time
As you probably know, SoftwareSerial uses Interrupts to do some of the timing stuff of the Serial communication.

What I am trying to accomplish is to measure the time that it takes `SoftwareSerial.write()` to write/send one byte.

Obviously, I started trying with timestamps based on `millis()`, but found out that SoftwareSerial messes with the `millis()` timer and it simply doesn't count properly.

I have something like this:

```
timestamp = millis();
HC12.write(endByte); //HC12 is a SoftwareSerial object

//After sending waits for the answer
while (HC12.available() > 0) {
  byte r = HC12.read();
  if (r == (byte) 254) { //The other HC12 module sends 0xFE
    unsigned long received = millis() - timestamp;
    Serial.println(received);
  }
...

```

Any suggestion on how I could measure this?

I am trying to implement a half-duplex communication with HC12 433MHz modules and I am testing some theoretical/real timing values for the communication between two boards.

# Answer
It is very simple, and you don't need any code to work it out.

SoftwareSerial is completely synchronous (i.e., *blocking*) when writing. That means that the amount of time taken to peform the write is the time taken to send the data on the line plus a small function call overhead.

That means the time taken is:

```
1 / baud * 10 seconds

```

So at 9600 baud one bit is sent in 1/9600 of a second, and there are 10 bits (1 start, 8 data, and 1 stop bit), so it takes 1/960th of a second.

That's about 1ms per byte, plus a few extra clock cycles for calling the actual functions.

To put it in more detail, when you send a byte this happens:

1. Set the line level to the start bit level
2. Wait 1/9600th of a second
3. Set the line level to the first data bit level
4. Wait 1/9600th of a second
5. Repeat 3&4 for the rest of the data bits
6. Set the line level to the stop bit level
7. Wait 1/9600th of a second
8. Set the line level to the idle level

So you have 10 "wait 1/9600th of a second" in total, or a total time of 1/960th of a second.

The same can be said of receiving data. When the start bit arrives it triggers a *pin change* interrupt. A synchronous blocking interrupt routine then executes that does the same as above but with reading instead of writing. So that takes about 1ms to execute at 9600 baud - plus some extra to insert the incoming byte into a circular buffer, which you then read from in your sketch.

So the round-trip time of a single byte from unit A to unit B then from unit B to unit A can be estimated as:

```
1/960 + 1/960 + overheads

```

That means the minimum time will be 1/480 seconds plus whatever time is spent at the remote unit processing the byte to send data back to you, and a little bit for the function call overheads.

Incidentally, it's that last operation in the interrupt, the "adding the byte to a circular buffer" that means you can't reliably receive at 115200 baud with SoftwareSerial. That takes more time to process than the typical gap between bytes (could be zero - just the width of the stop bit...) that the next byte could have already started to arrive at the GPIO pin before the Arduino is capable of triggering the ISR again, so it misses the start bit.
> 1 votes

---
Tags: softwareserial, millis, hc-12
---


# Question
Title: How to multitask while writing on Serial
I am trying to send real-time data taken from an ADC by Arduino Uno (SPI) to Arduino IDE through a USB cable. I found that one byte takes around 70 microseconds when Serial.write() is used at a baud rate of 115200. My question is that if I send 14400 bytes (which would be the maximum limit at this baud rate), can I perform any other tasks? Does Arduino allow multitasking while the serial buffer is busy writing data?

# Answer
Until you fill the transmit buffer (64 bytes by default but can be recompiled to enlarge it if you need to), Serial.print() or Serial.write() will return immediately. The characters in the buffer will be transmitted by an interrupt service routine, so essentially, the Arduino is double-tasking for that purpose. If the buffer is full when you call Serial.print() or Serial.write() or Serial.print() fills it before having sent all of its characters, those calls block (won't return) until there is buffer-space for their remaining characters.

So yes, you can do other things while the writing happens, as long as you haven't filled the buffer. You can call Serial.availableForWrite() to find out how many characters you can send without blocking.

By the way, at 115200 baud, or 11520 bytes/second, each character should take 1/11520 seconds or 86.8 microseconds, not 70 milliseconds.
> 3 votes

---
Tags: serial
---


# Question
Title: Combining code for multiple sensors in a single program
I need to operate 3 different sensors (taken 6 sensors of each type) by Arduino Mega2560 :-

1. DHT11 (temperature-Humidity sensor)
2. MQ5 (gas sensor) and
3. Soil Moisture sensor {taken 6 of each type (total=18).}

I have managed to run each one of them separately and I don't know how to manipulate the code so they could work all together. My background in coding is basic, so it would be great help if someone can help me for combining these codes.

Here are the sketches:

**MQ5 Code:**

```
int sensor=7;
int gas_value;
void setup()
{

pinMode(sensor,INPUT);
Serial.begin(9600);

}

void loop()
{

gas_value=digitalRead(sensor);
Serial.println(gas_value);
}

```

{other digital pins to be used: D6,D5,D4,D3,D2}

**DHT11 Code:**

```
#include <dht.h>
#include <dht.h>
#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;

void setup(){

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000);//Wait 5 seconds before accessing sensor again.

  //Fastest should be once every two seconds.

}// end loop()

```

{analog pins for other sensors: A1,A2,A3,A4,A5}

**Soil\_Moisture Sensor Code:**

```
int sensor_pin = A6;
int output_value ;

void setup() {

   Serial.begin(9600);
   Serial.println("Reading From the Sensor ...");
   delay(2000);

   }

void loop() {

   output_value= analogRead(sensor_pin);
   output_value = map(output_value,550,0,0,100);
   Serial.print("Mositure : ");
   Serial.print(output_value);
   Serial.println("%");
   delay(1000);
   }

```

{Analog pins for other sensors to be used: A6,A7,A8,A9,A10}

# Answer
All things before `void setup()` put before one `setup()` function. All things in `void setup()` put to the one `void setup()` \- do not duplicate things like `#include` or `Serial.begin()`. And things from `loop()` function put to the `loop()` function. It's a good practice to don't use `delay()` in `loop()` when you are processing more things than one. Instead of `delay()` use `millis()` to get current uptime and after that compare this uptime to last uptime of check.

I modified your code, so read it and try it.

```
#include <dht.h>

#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;

int sensor=7;
int gas_value;

int sensor_pin = A6;
int output_value ;

unsigned long gas_last_time = 0;
unsigned long dht11_last_time = 0;
unsigned long analog_last_time = 0;

void setup(){
  Serial.begin(9600);
  pinMode(sensor,INPUT);
}

void loop(){
  if(millis() - gas_last_time >= 10){
    gas_last_time = millis();

    gas_value=digitalRead(sensor);
    Serial.println(gas_value);
  }

  if(millis() - dht11_last_time >= 5000){
    dht11_last_time = millis();

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");
  }

  if(millis() - analog_last_time >= 1000){
    analog_last_time = millis();

    output_value= analogRead(sensor_pin);
    output_value = map(output_value,550,0,0,100);
    Serial.print("Mositure : ");
    Serial.print(output_value);
    Serial.println("%");
  }
}

```
> 0 votes

# Answer
In general:

All `#define`s and `#include`s get put from all separate sketches, at the top.

Globals and function definitions (except for `setup()` and `loop()`) get mixed together below the `#define`s and `#include`s.

All code in the separate `setup()`s get put in the combined `setup()`.

All code in the separate `loop()`s get put in the combined `loop()`.

You have to be aware that any `loop()` from the separate programs that include a `delay()` will likely have to be refactored to use the same kind of scheduled execution method as the Blink Without Delay example from Arduino. `delay()` stops the whole program while it twiddles thumbs, which means your other sensors aren't being read or managed during that time.
> 2 votes

---
Tags: arduino-mega, programming, sensors, temperature-sensor
---


# Question
Title: Method to iterate over the bits in a byte sent over serial
In my current project which integrates Arduino/avr IC with Raspberry-Pi, and each communicating via serial, I'm looking to send a byte of data to the Arduino from the RPi, which then would be iterated over, bit by bit.

Each bit represents a setting. If a bit is 0, then the Arduino would turn that respective device off, if a bit is 1, then Arduino would turn that respective device on. For example, a byte such as: 01100110, would mean the Arduino would have to turn four devices off, and four devices on.

I'm looking for information on how to take a byte over serial, and iterate over that byte bit by bit, and have the Arduino make decisions based on the value of each bit.

Excuse my post for lacking much technical detail, I'm refraining from using terms that are still very vague to me.

Regards.

# Answer
In all the examples below, `value` is the value of the byte

LSB -\> MSB - so 00001111 would turn ON the first 4 devices and turn OFF the last 4

```
for(int i = 0, mask = 1; i < 8; i++, mask = mask << 1)
{
    if (value & mask)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

```

Alternatively, you can do the following, but `value` will be altered

```
for(int i = 0; i < 8; i++, value = value >> 1)
{
    if (value & 1)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

```

Working the other way around in each byte:
MSB -\> LSB - so 00001111 would turn OFF the first 4 devices and turn ON the last 4

```
for(int i = 0, mask = 128; i < 8; i++, mask = mask >> 1)
{
    if (value & mask)
    {
        // bit "i" is on
    }
    else
    {
        // bit "i" is off
    }
}

```

Alternatively, you can do the following, but `value` will be altered

```
for(int i = 0; i < 8; i++, value = value << 1)
{
    if (value & 128)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

```
> 2 votes

---
Tags: arduino-uno, serial, raspberrypi, serial-data
---


# Question
Title: AVR-GCC can't call function located on fixed address
I wrote the following code:

```
#include <avr/io.h>

__attribute__((noinline, section(".app_start"))) void app_start() //app_start section starts at 0xFA0
{
    //register_packet_dispatch(packet_received);
    PORTB = 0xFF;
}

__attribute__ ((noinline)) void call_app()
{
    asm ("call 0xFA0\nret");
    //app_start();
}

int main()
{
    DDRB = 0xFF;
    //call_app();
    app_start();
    while(1){}
}

```

What I compiled with:

```
avr-gcc -Wl,--section-start=.reg_dispatch=0xdac -Wl,--section-start=.app_start=0xFA0 -mmcu=atmega328p -Os -o ubb.o ub_bootloader.cpp -DF_CPU=16000000

```

Which tries to simulate a host application that tries to call a relocated client application, begins from the 4000 address (0xFA0). If it would work, it's light up the LED wired to the arduino's 13. pin. But why `app_start` won't be called?

I've also inspected the output assemlby:

```
avr-objcopy -j .text -j .data -O ihex ubb.o ubb.hex

00000fa0 <_Z9app_startv>:
 fa0:   8f ef           ldi r24, 0xFF   ; 255
 fa2:   85 b9           out 0x05, r24   ; 5
 fa4:   08 95           ret

00000080 <main>:
  80:   8f ef           ldi r24, 0xFF   ; 255
  82:   84 b9           out 0x04, r24   ; 4
  84:   0e 94 d0 07     call    0xfa0   ; 0xfa0 <_Z9app_startv>
  88:   ff cf           rjmp    .-2         ; 0x88 <main+0x8>

```

Everything seems correct, why it isn't working at all? Of course, if i remove the "noinline" attribute, it works. But that's a mirage, the compiler inlines the content of the function, but when I build this into an application, the code after the 0xFA0 address will be rewritten by the host application.

# Answer
I've tried this code with arduino and it worked (i taught, of course, i can't add the "-Wl,--section-start=.app\_start=0xFA0" flag to the compilation process so the function not gonna be moved to other section) So i set the arudino IDE to show every command from the compilation to the end of the upload process.

The problem lies in the usage of avr-objdump, whose i found somewhere and used witouth overview the CLI switches.

I've also made a mistake when i wrote the question. To disassemble the object file, the right command is:

```
avr-objdump -S --disassemble  ubb.o > ubb.asm

```

THe command i've used to create hex file:

```
avr-objcopy -j .text -j .data -O ihex ubb.o ubb.hex

```

The working one (extracted from arduino):

```
avr-objcopy -O ihex -R .eeprom ubb.o ubb.hex

```

-j means keep only the given section(s)

while

-R means, remove only the given section(s)
> 3 votes

---
Tags: bootloader, avr, flash, avr-toolchain, avr-gcc
---


# Question
Title: Trouble with reading Bitmaps from SD-Card
I'm having problems with reading a bitmap file with the SD library. I wrote a small header that reads uncompressed 24-bit bitmap files. It works fine when I try it on Windows 10 MingW with fread() instead of SD.read(). On my UNO it only reads the correct offset address, the other parts are garbage.

For a pure red 1x1 px bitmap I get the following expected output on Windows with MingW:

```
Fname: ..\rot.bmp
Offset: 00000036
W * H: 1 * 1
Bit# 24
Cmp: 0
ArraySize: 1
---------------------------
RGB: ff0000

```

Arduino outputs:

```
Fname: rot.bmp
Offset: 00000036
W * H: 0 * 2304
Bit# 58
Cmp: 0
ArraySize: 8
---------------------------
Error while reading BMP file

```

bmp.hpp

```
#ifndef BMP_HEADER
#define BMP_HEADER

#if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
#include <SD.h>
#include<stdint.h>
#define BYTE uint8_t
#define WORD uint16_t
#define DWORD uint32_t
#define LONG int32_t
#else
#include<stdlib.h>
#include<windows.h>
#endif // defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
#pragma pack(2)
typedef struct
{
  BYTE B;
  BYTE G;
  BYTE R;
} pixel;

typedef struct
{
  WORD bfType;
  DWORD bfSize;
  DWORD bfReserved;
  DWORD bfOffset; //offset to byte array
} bfheader;

typedef struct
{
  DWORD biSize; //size of this header
  LONG biWidth; //image width
  LONG biHeight;//image height
  WORD biPlanes;
  WORD biBitCount; //color depth in bit per pixel
  DWORD biCompression; //0 for none(RGB mode)
  DWORD biSizeImage; //size of image in byte; may be 0 if biCompression is RGB
  LONG biXPelsPerMeter;
  LONG biYPelsPerMeter;
  DWORD biClrUsed; //palete stuff
  DWORD biClrImportant; //more palete stuff
} biheader;

//returns BGR array of bitmap
//header and biheader are assumed to be allocated upon execution
//returns null if unsuccessful
inline pixel* readBMP(const char* filename, bfheader* header, biheader* infoheader)
{
    #if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    SDLib::File f = SD.open(filename);
    if(!f) return NULL;
    f.read((uint8_t *)header, sizeof(bfheader)); // read the 14-byte file header
    f.read((uint8_t *)infoheader, sizeof(biheader)); //read the 40-byte info header
    #else
    FILE* f = fopen(filename, "rb");
    if(f == NULL) return NULL;
    fread(header, sizeof(bfheader), 1, f);
    fread(infoheader, sizeof(biheader), 1, f);
    #endif //defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
  if(infoheader->biCompression != 0 || infoheader->biBitCount != 24) //if the file is not RGB encoded or if its not 24bit
  {
    #if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    f.close();
    #else
    fclose(f);
    #endif // defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    return NULL;
  }
  int size = (int) infoheader->biSizeImage/sizeof(pixel); //get byte size of pixel array
  pixel* data = (pixel*) malloc(sizeof(pixel)*size); // allocate
  #if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)
    f.seek(header->bfOffset); //set file cursor to starting address of RGB array
    f.read((uint8_t *)data, sizeof(uint8_t)*size); // read the rest of the data at once
    f.close();
  #else
    fseek(f, header->bfOffset, SEEK_SET);
    fread(data, sizeof(pixel), size, f);
    fclose(f);
  #endif //__arm__
  return data;
}
#endif //BMP_HEADER

```

readbmp\_test.ino

```
#include<arduino.h>
#include <SPI.h>
#include "bmp.hpp"

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");
}

void loop()
{
  char debug[160];
  char rgbdata[8];
  const char* const files[] = {"rot.bmp", "gruen.bmp", "blau.bmp"};
  int files_len = 3;
  bfheader header;
  biheader infoheader;
  pixel* image;
  for(int i=0; i<files_len; i++)
  {
    image = readBMP(files[i], &header, &infoheader);
    Serial.println("----------------------------");
    sprintf(debug,  "Fname: %s\n"
                "Offset: %08lx\n"
                "W * H: %ld * %ld\n"
                "Bit# %u\n"
                "Cmp: %lu\n"
                "ArraySize: %lu\n"
                "---------------------------\n",
                  files[i],
                  header.bfOffset,
                  infoheader.biWidth, infoheader.biHeight,
                  infoheader.biBitCount,
                  infoheader.biCompression,
                  infoheader.biSizeImage/sizeof(pixel));
    Serial.print(debug);
    if(image != NULL)
    {

      for(unsigned j=0; j<infoheader.biSizeImage/sizeof(pixel); j++)
      {
        sprintf(rgbdata, "%02x %02x %02x", image[j].R, image[j].G, image[j].B);
        Serial.println(rgbdata);
      }
    }else{
        sprintf(debug, "Error while reading BMP file\n");
        Serial.print(debug);
    }
    free(image);
  }
}

```

main.cpp //MingW Windows Test

```
#if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA)  //arduino compiler wants to run this main?
#else
#include<stdio.h>
#include "bmp.hpp"

int main(const int argc, const char** argv)
{
    if(argc < 2) return -1;

    bfheader header;
    biheader infoheader;
    for(int i=1; i<argc; i++)
    {
        pixel* image = readBMP(argv[i], &header, &infoheader);
        if(image != NULL)
        {
            printf("Fname: %s\n"
                    "Offset: %08x\n"
                    "W * H: %d * %d\n"
                    "Bit# %d\n"
                    "Cmp: %d\n"
                    "ArraySize: %d\n"
                    "---------------------------\n",
                    argv[i],
                    header.bfOffset,
                    infoheader.biWidth, infoheader.biHeight,
                    infoheader.biBitCount,
                    infoheader.biCompression,
                    infoheader.biSizeImage/sizeof(pixel));
            for(int j=0; j<infoheader.biSizeImage/sizeof(pixel); j++)
            {
                printf("RGB: %02x%02x%02x\n", image[j].R, image[j].G, image[j].B);
            }
        }else{
                printf("Error while reading BMP file\n");
                return 1;
        }
        free(image);
    }
    return 0;
}
#endif

```

I'm really stuck on this, I actually rewrote it a couple times already. I would really appreciate some help.

# Answer
`f.read((uint8_t *)infoheader, sizeof(infoheader));`

should be

`f.read((uint8_t *)infoheader, sizeof(biheader));`

the size of the variable (pointer) is only 2. you want to read 40 bytes of `biheader` struct

and

`f.read((uint8_t *)data, sizeof(uint8_t)*size)`

should be

`f.read((uint8_t *)data, sizeof(pixel)*size)`

---

The next problem is %d and %x in sprintf. %d and %x read two bytes on Arduino, not 4, not 1. Print the values without sprintf as `Serial.println(number)`
> 1 votes

---
Tags: arduino-uno, sd-card, sd
---


# Question
Title: Do you need an ESC to run this brushless DC motor with Arduino Uno?
This is the motor:

https://www.aliexpress.com/item/Wholesale-JGA25-2418-8-5-1977-rpm-Electric-Motors-Brushless-Motor-High-Torque-Speed-Controlled-DC/32360228129.html

I'm hooking it up to the arduino as described and giving the PWM outputpin analogWrite functions, but it's not working.

# Answer
No. It has an ESC built in.

You just provide power and a PWM signal, and optionally a direction signal.

To test:

1. Connect red to +12V.
2. Connect black to 12V GND and to Arduino GND
3. Connect white to D5
4. `analogWrite(5, 128)`;
> 0 votes

---
Tags: arduino-uno, arduino-ide, motor, pwm, electronics
---


title: Sending Data from ESP8266 to PHP

text:
# Question
Title: Sending Data from ESP8266 to PHP
I want to display the RFID tag value to a html file.

I am using ESP8266 ESP-01 module, EM-18 Reader Module, Arduino Uno and Xampp for hosting PHP.

Right now, I am getting a value of "255" in Arduino whenever I scan a RFID tag. But I am supposed to get the 12-digit alphanumeric RFID tag value.

I have attached the Arduino and also the output screen of the Serial Monitor.

I have my college submission next week so it's urgent. Any help would be appreciated.

```
#include "SoftwareSerial.h"
String ssid ="Home";
String password="****";
SoftwareSerial esp(2, 3);// RX, TX
String data;
String server = "192.168.0.182"; // www.example.com
String uri = "/testget.php";// our example is /esppost.php
int DHpin = 0;//sensor pin
byte dat [12];
String tag;

void setup() {
  pinMode (DHpin, OUTPUT);
  esp.begin(9600);
  Serial.begin(9600);
  reset();
  connectWifi();
}

//reset the esp8266 module

void reset() {
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") )
    Serial.println("Module Reset");
}

//connect to your wifi network

void connectWifi() {
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);
  /*
  if(esp.find("OK")) {
    Serial.println("Connected!");
  }
  else {
    connectWifi();
    Serial.println("Cannot connect to wifi"); }*/
}

byte read_data () {
  byte data;
  for (int i = 0; i < 13; i ++) {
    if (digitalRead (DHpin) == LOW) {
      while (digitalRead (DHpin) == LOW); // wait for 50us
        delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'
      if (digitalRead (DHpin) == HIGH)
        data |= (1 << (12-i)); // high front and low in the post
      while (digitalRead (DHpin) == HIGH);
// data '1 ', wait for the next one receiver
    }
  }
  return data;
}

void start_test () {
  digitalWrite (DHpin, LOW); // bus down, send start signal
  delay (30); // delay greater than 18ms, so DHT11 start signal can be detected
  digitalWrite (DHpin, HIGH);
  delayMicroseconds (40); // Wait for DHT11 response
  pinMode (DHpin, INPUT);
  while (digitalRead (DHpin) == HIGH);
    delayMicroseconds (80);
  // DHT11 response, pulled the bus 80us
  if (digitalRead (DHpin) == LOW);
    delayMicroseconds (80);
  // DHT11 80us after the bus pulled to start sending data
  for (int i = 0; i < 13; i ++)
    // receive tag value data, the parity bit is not considered
    dat[i] = read_data ();
  pinMode (DHpin, OUTPUT);
  digitalWrite (DHpin, HIGH);
  // send data once after releasing the bus, wait for the host to open the next Start signal
}

void loop () {
  start_test ();
  // convert the bit data to string form
  tag= String(dat[12]);
  data = "tag=" + tag;// data sent must be under this form //name1=value1&name2=value2.
  Serial.println(data);
  httppost();
  delay(1000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  String postRequest =
  "POST " + uri + " HTTP/1.0\r\n" +
  "Host: " + server + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Content-Length: " + data.length() + "\r\n" +
  "Content-Type: application/x-www-form-urlencoded\r\n" +
  "\r\n" + data;
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.
  esp.print(sendCmd);
  esp.println(postRequest.length() );
  delay(500);
  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
    if( esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String tmpResp = esp.readString();
        Serial.println(tmpResp);
      }
      // close the connection
    esp.println("AT+CIPCLOSE");
    }
  }
}

```

Output :

# Answer
> 1 votes
I got it working using the code below:

```
#include "SoftwareSerial.h"
String ssid ="Home";

String password="%Qwerty@123%";
char input[12];
int count = 0;
SoftwareSerial esp(2, 3);// RX, TX

String data;

String server = "192.168.0.182"; // www.example.com

String uri = "/testget.php";// our example is /esppost.php

int DHpin = 0;//sensor pin

byte dat [12];

String temp;

void setup() {

pinMode (DHpin, OUTPUT);

esp.begin(9600);

Serial.begin(9600);

reset();

connectWifi();

}

//reset the esp8266 module

void reset() {

esp.println("AT+RST");

delay(1000);

if(esp.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network

void connectWifi() {

String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";

esp.println(cmd);

delay(4000);
}

byte read_data () {

byte data;

for (int i = 0; i < 8; i ++) {

if (digitalRead (DHpin) == LOW) {

while (digitalRead (DHpin) == LOW); // wait for 50us

delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'

if (digitalRead (DHpin) == HIGH){

data |= (1 << (7-i)); // high front and low in the post
 }
while (digitalRead (DHpin) == HIGH);

// data '1 ', wait for the next one receiver

}

} return data; }

void start_test () {

digitalWrite (DHpin, LOW); // bus down, send start signal

delay (30); // delay greater than 18ms, so DHT11 start signal can be detected

digitalWrite (DHpin, HIGH);

delayMicroseconds (40); // Wait for DHT11 response

pinMode (DHpin, INPUT);

while (digitalRead (DHpin) == HIGH);

delayMicroseconds (80);

// DHT11 response, pulled the bus 80us

if (digitalRead (DHpin) == LOW);

delayMicroseconds (80);
while(count<12){
input[count] = Serial.read(); // Read 1 Byte of data and store it in the input[] variable
      count++;          // increment counter
      delay(5);}
// DHT11 80us after the bus pulled to start sending data

//for (int i = 0; i < 4; i ++)

// receive temperature and humidity data, the parity bit is not considered
/*for(int x=0;x<12;x++)
for(int i=0;i<12;i++)
//dat[i] = read_data ();
dat[x]=input[i];*/

pinMode (DHpin, OUTPUT);

digitalWrite (DHpin, HIGH);

// send data once after releasing the bus, wait for the host to open the next Start signal

}

void loop () {

start_test ();

    count = 0;      // Reset the counter to zero
    temp = "";
    // convert the bit data to string form
for(int i=0;i<13;i++)
temp += input[i];
Serial.println(temp);
//Serial.println(temp);

data = "tag=" + temp;// data sent must be under this form //name1=value1&name2=value2.

httppost();

delay(200);

}

void httppost () {

esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

if( esp.find("OK")) {

Serial.println("TCP connection ready");

} delay(100);

String postRequest =

"POST " + uri + " HTTP/1.0\r\n" +

"Host: " + server + "\r\n" +

"Accept: *" + "/" + "*\r\n" +

"Content-Length: " + data.length() + "\r\n" +

"Content-Type: application/x-www-form-urlencoded\r\n" +

"\r\n" + data;

String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

esp.print(sendCmd);

esp.println(postRequest.length() );

delay(500);

if(esp.find(">")) { Serial.println("Sending.."); esp.print(postRequest);

if( esp.find("SEND OK")) { Serial.println("Packet sent");

//while (esp.available()) {

//String tmpResp = esp.readString();

//Serial.println(tmpResp);

//}

// close the connection

esp.println("AT+CIPCLOSE");

}

}}

```

# Answer
> 0 votes
You can follow this awesome tutorial if you want to connect your RFID RC522 module to PHP. Source Code and a step by step tutorial are provided. You only need NodeMcu and RC522 RFID module. https://devcraze.com/tutorials/connecting-rfid-scanner-to-php-using-nodemcu-wifi-module/

---
Tags: arduino-uno, programming, esp8266, sensors, rfid
---


# Question
Title: Can I power a Wemos D1 R2 via the VIN and GND pins?
Can I power a Wemos D1 R2 via the VIN and GND pins? If so, at what voltage?

# Answer
> 2 votes
Wemos D1 R2 has on-board regulator with input from power jack and Vin pin. The regulator is for 9 to 24 V.

---
Tags: arduino-uno, power, voltage
---


# Question
Title: My software serial code won't work at > 4800bps
I've put together a simple software serial (send-only) implementation for use on my attiny8\[45\] microcontrollers. I realize that there are more efficient USI-based implementations out there; this was mostly an educational exercise. The code uses TIMER0 in CTC mode to time the sending of bits on an available output pin.

It works fine from 300bps up to 4800bps, but anything faster than that just results in garbage.

The complete code is at the bottom of this answer. The following settings all work correctly:

1. 4800bps

```
#define BPS 4800
#define SCALE_FLAG 1
#define SCALE_VAL 1

```
2. 2400bps

```
#define BPS 2400
#define SCALE_FLAG 2
#define SCALE_VAL 8

```
3. 1200bps

```
#define BPS 1200
#define SCALE_FLAG 2
#define SCALE_VAL 8

```
4. 300bps

```
#define BPS 300
#define SCALE_FLAG 3
#define SCALE_VAL 64

```

While this fails:

1. 9600bps

```
#define BPS 9600
#define SCALE_FLAG 1
#define SCALE_VAL 1

```

Because everything other than 9600bps works I'm tempted to think that my code is correct, and yet I expect that I should be able to achieve 9600bps with these microcontrollers.

Are there any obvious bugs in this code? I think that's the most likely explanation, but after poking at this for a couple of days I'm not seeing it.

---

```
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include <string.h>

#define BPS 9600
#define SCALE_FLAG 1  // This is the value that goes in the TCCR0B register
#define SCALE_VAL 1   // This is the divisor selected by SCALE_FLAG

#define TXPORT PORTB
#define TXDDR DDRB
#define TXPIN PORTB0

#define TICKS_PER_BIT (F_CPU/BPS/SCALE_VAL)
#define mS_PER_BIT (1000000/BPS/1000)
#define uS_PER_BIT ((1000000 / BPS) - (1000 * mS_PER_BIT))

typedef struct SERIAL_PORT {
    uint8_t data;
    uint8_t index;
    uint8_t busy;
} SERIAL_PORT;

void millis_init();
uint32_t millis();

void serial_init();
void serial_putchar(char c);
void serial_print(char *s);
void serial_println(char *s);
void delay(uint32_t m);

volatile SERIAL_PORT port;
volatile uint32_t _millis,
         _micros = 1000;

int main() {
    millis_init();
    serial_init();
    while (1) {
        serial_println("hello world");
        delay(500);
    }
}

void delay(uint32_t m) {
    uint32_t t_start = millis();
    while (millis() - t_start < m);
}

void millis_init() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        _millis = 0;
    }
}

uint32_t millis() {
    uint32_t x;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      x = _millis;
    }
    return x;
}

void serial_init() {
    DDRB |= 1<<TXPIN;       // Set TXPIN as an output
    TXPORT |= 1<<TXPIN;     // Set TXPIN high (serial idle)
    TCCR0A = 1<<WGM01;      // Select CTC mode
    TCCR0B = SCALE_FLAG;    // Set clock scaler
    OCR0A = TICKS_PER_BIT;  // Set CTC target value
    TIMSK0 |= 1<<OCIE0A;    // Enable compare match interrupt
    sei();
}

void serial_putchar(char c) {
    while (port.busy);
    port.data = c;
    port.index = 0;
    port.busy = 1;
}

void serial_print(char *s) {
    while (*s) serial_putchar(*s++);
}

void serial_println(char *s) {
    serial_print(s);
    serial_putchar('\r');
    serial_putchar('\n');
}

ISR(TIM0_COMPA_vect) {
    if (port.busy) {
        switch(port.index) {
            case 0:
                // send start bit
                TXPORT &= ~(1<<TXPIN);
                break;
            case 9:
                // send stop bit
                TXPORT |= (1<<TXPIN);
                port.busy = 0;
                break;
            default:
                // send data bit
                if (port.data & 1) {
                    TXPORT |= 1<<TXPIN;
                } else {
                    TXPORT &= ~(1<<TXPIN);
                }
                port.data >>= 1;
                break;
        }
        port.index++;
    }

    _millis += mS_PER_BIT;

    if (uS_PER_BIT > _micros) {
        _millis++;
        _micros = 1000;
    } else {
        _micros -= uS_PER_BIT;
    }
}

```

# Answer
> 1 votes
At 1MHz and 9600 baud, you have a total of 104 clock cycles available to run your interrupt routine in. A quick count up of the assembly instructions generated comes to more than that (around 126 at first glance), so you can't fit it into the time.

As a result, your baud rate will actually be lower than 9600, and the chip will be completely starved of clock cycles for doing anything in your main loop.

---
Tags: serial, attiny, avr-toolchain
---


title: Find vehicle movement by IMU and GPS

text:
# Question
Title: Find vehicle movement by IMU and GPS
I'm using `MPU9250` which has both accelerometer and gyroscope in a vehicle. What I want is to just know that if the vehicle is currently moving or not. I searched and find out that I can't get velocity easily so I skipped that but I was wondering how can I found movement with an IMU.

Edit: As @Duncan said, it seems that it cannot be examined with only IMU. I also have a GPS sensor in my device and having the speed value from GPS but it is not very accurate. For example, if the vehicle is stopped for 5 minutes I get variable speeds between 0 to 10.0 kmph and on the other hand getting the location as lat/long has about 20 meters error. So I can't really rely on it. I was wondering can I combine both GPS and IMU to find out if it is really moving or not? One solution that I came was relying on GPS speed but for spikes just check the accelerometer variations and if it is beyond a threshold, it means that it actually moved.

# Answer
You noted that your goal is to determine whether or not a vehicle is in motion. Because you are trying an IMU, I assume the device that needs to know this is on-board the vehicle.

There are many complicated ways to know this, such as using the acceleration data from the IMU to perform Inertial Dead Reckoning, this has the problem of temporal drift. A GPS has the issue of needing it's speed data to be filtered a bit to get rid of high-speed spikes.

But -- if you just need to know if the vehicle is moving or not, and if the vehicle has wheels, you can use an light detector, such as an IR emitter and IR receiver pair, along with a slitted disc attached to the wheel, and simply count when the last time the receiver was activated -- if beyond some threshold of time, then you assume the wheel is not turning, and thus that the vehicle is not moving. Or perhaps just use a light sensor and paint white and dark patterns on the wheel.

Or put a magnet on the wheel and place a hall effect sensor (magnet sensor) near where the magnet will pass. Count the pulses from the hall effect sensor.

If the vehicle is not a wheel-based vehicle, then you may have to rely on GPS or some other method, however.
> 1 votes

---
Tags: accelerometer
---


title: Building mocoLUFA under OSX & Linux

text:
# Question
Title: Building mocoLUFA under OSX & Linux
I am attempting to build mocoLUFA under OS X el Capitan 10.11.6.

\[Editor: mocoLUFA (MIDI firmware for Arduino Uno)\]

I am using the specified LUFA version (LUFA101122) and I have tried building with both brew avr-gcc and also Crosspack-AVR.

The problem I am facing isn't with the build or the install. It's just that as soon as I install the hex file, I get no midi messages at all.

What does work - the OSX machine recognises the MIDI device and the MIDI device appears in DAW's, however MIDI Monitor registers no messages at all.

I have tried downloading a custom-built mocoLUFA and I am able to install this and it works fine. I see midi messages coming across from my sketch.

Crosspack-AVR installs avr-gcc 4.8.1.

My question is - what is the correct build environment in order to achieve a working mocoLUFA under OSX? I have tried both mocoLUFA and dualMoco and I get the same result with each.

My purpose for this is to modify mocoLUFA so that it can support sending MTC over USB. At present, it appears that mocoLUFA does not support System Common messages.

UPDATE: Built fresh Ubuntu VM. Installed avr-gcc, avr-libc, LUFA-100807 and mocoulfa. Same result. hex builds fine, no response from the atmega16u2. TX light flashing, sketch on the 2560 running, but no midi messages down the usb cable.

# Answer
> 1 votes
This is Franco, from Yaeltex, the guys who put up that site for custom MocoLUFA compiling.

Our site works on an Ubuntu server, and the build environment can be seen at the bottom of the site, which is as follows:

1. Ubuntu Server Setup
    * avr-gcc: avr-gcc (GCC) 4.9.2
    * avrdude: Version 6.3, compiled on Mar 15 2016 at 21:26:45
    * LUFA: 100807
    * dualMocoLUFA: custom Yaeltex based on 2013/09/22

On the other hand, I use Windows 10 to build locally in my computer, and I have a similar setup with sligthly older versions of avr-gcc and avrdude:

2. Windows 10 Server Setup
    * avr-gcc: avr-gcc (GCC) 4.3.3
    * avrdude: Version 5.10, compiled on Mar 15 2016 at 21:26:45
    * LUFA: 100807
    * dualMocoLUFA: custom Yaeltex based on 2013/09/22

Here is a link to the fork we made to mocoLUFA, it has minor changes, that were very useful to us and our hardware.

Regarding your problem, I am really lost on the cause of it, but we can start with some questions to get closer to a solution.

* What kind of MIDI messages are you trying to send/receive?
* Can you share the code you are using?
* Are you using Arduino MIDI Library (Last version is v4.3.1)?
* If not, are you sure you are using 31.250 bps as baud rate?
* Do you have something else connected to TX or RX lines in your circuit?

Let's start with these. Cheers!

# Answer
> 0 votes
I see that you are reading the MIDI messages from your iPad. If so, it is to be noted that LUFA reports 500mA for power requirements. So you could try self powering your USB-HUB.

Source: http://morecatlab.akiba.coocan.jp/morecat\_lab/MocoLUFA.html

---
Tags: arduino-mega, midi, avr-gcc
---


# Question
Title: Why does my LED turn off automatically after about 18 seconds on its own?
I am using the Arduino Due and I am programming it with Atmel Studio 6.2. I have had a HUGE learning curve using this IDE and the Atmel ASF. Nothing is straightforward as it is in the Arduino IDE. Nonetheless, I want to toggle an LED on and off with a simple interrupt on a pull-up configured tactile button. This is my code:

```
#include <asf.h>
#include "pio.h"

// Define the LED pins
#define BLUE_LED2 PIO_PC28 // Arduino Due pin 3
#define BLUE_LED3 PIO_PC26 // Arduino Due pin 4
#define BLUE_LED4 PIO_PC25 // Arduino Due pin 5
#define BLUE_LED5 PIO_PC24 // Arduino Due pin 6
#define BLUE_LED6 PIO_PC23 // Arduino Due pin 7

// Define the button pins
#define BUTTON_1 PIO_PC22
#define BUTTON_2 PIO_PC21

// Define function prototype for button interrupt
void button_press_handler(uint32_t, uint32_t);
void toggle_LED(uint32_t);

int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init();

    // Initialize input/out
    ioport_init();
    pmc_enable_periph_clk(ID_PIOC);
    pmc_enable_periph_clk(ID_PIOB);

    // Set LED pins as outputs and set there default values (off)
    pio_set_output(PIOC, BLUE_LED2, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED3, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED4, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED5, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED6, LOW, DISABLE, ENABLE);

    // Set button pins as pull-up inputs
    pio_set_input(PIOC, BUTTON_1, PIO_PULLUP);
    pio_set_input(PIOC, BUTTON_2, PIO_PULLUP);

    // Configure button input pin interrupt mode and handler (Falling Edge)
    pio_handler_set(PIOC, ID_PIOC, BUTTON_1,  PIO_IT_RISE_EDGE, button_press_handler);
    pio_handler_set(PIOC, ID_PIOC, BUTTON_2,  PIO_IT_RISE_EDGE, button_press_handler);

    // Enable the interrupts
    pio_enable_interrupt(PIOC, BUTTON_1);
    pio_enable_interrupt(PIOC, BUTTON_2);
    NVIC_EnableIRQ(PIOC_IRQn);

    while(1){
         // Doing stuff in here...
    }
}

```

Then this is my interrupt routine:

```
// Interrupt handler for button press
void button_press_handler(uint32_t a, uint32_t b)
{
    // Turn the LED's on or off
    toggle_LED(BLUE_LED2);
    toggle_LED(BLUE_LED3);
    toggle_LED(BLUE_LED4);
    toggle_LED(BLUE_LED5);
    toggle_LED(BLUE_LED6);
}

// Function to toggle LED on/off
void toggle_LED(uint32_t LED){

    if (pio_get(PIOC, PIO_TYPE_PIO_OUTPUT_0, LED))
    pio_clear(PIOC, LED);
    else
    pio_set(PIOC, LED);
}

```

Things work normal and as expected up until about 18 seconds in. After 18 seconds, the LED turns off if it is on. I tested this by setting LED 2 HIGH by default and removing the interrupt all together:

```
pio_set_output(PIOC, BLUE_LED2, HIGH, DISABLE, ENABLE);

```

In this case, the LED will stay on forever, but about every 18 seconds, the LED will flash off then back on once quickly. Why is this happening?

# Answer
> 2 votes
Again, figured this out. I simply forgot to put in `board_init();` Also, since `board_init()` already calls `ioport_init()`, I had to disable that.

Now I have this:

```
int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init(); // Initialize the System Clock
    board_init();  // Initialize the board

```

....

# Answer
> 1 votes
The symptoms you describe are consistent with your program crashing after 18 seconds. I expect you will find something in this that is the problem:

```
while(1){
     // Doing stuff in here...
}

```

To debug this, add something to the startup that is unique or clearly identifiable:

* a print "reset" to a serial port if you have one
* in your case, blink the led's in sequence 2,3,4,5,6

Once you confirm that your program is resetting, strip out everything in the

```
// Doing stuff in here...

```

With the program stripped down, it should keep the LED's lit.

If the LED's still do not stay lit, but you see your reset indicator, consider power. Microcontrollers will reset when the voltage droops too low. The LED's might be consuming enough power to reduce the voltage below the trip point. Connect a voltmeter to the supply voltage to see if it is stable.

The time delay can be associated with the power supply heating at higher current. The LM2734 chip on the Due has a thermal shutdown, same as most voltage regulators. If your hardware draws enough current to overheat, the chip will shutoff, cool down and turn back on.

# Answer
> 0 votes
This may be because the ATSAM3X8E chip has a watchdog: from the datasheet section 15.1,

> The Watchdog Timer can be used to prevent system lock-up if the software becomes trapped in a deadlock. It features a 12-bit down counter that allows a watchdog period of up to 16 seconds (slow clock at 32.768 kHz). It can generate a general reset or a processor reset only. In addition, it can be stopped while the processor is in debug mode or idle mode.

`board_init()` almost certainly disables the watchdog.

---
Tags: arduino-due, c, atmel-studio
---


# Question
Title: How to parse multi line serial data with an unknown number of lines?
Here's the example data I've read in H-Term:

```
\r\n
\r\n
NO:0015\r\n
G:   5.97kg\r\n
T:   0.00kg\r\n
N:   5.97kg\r\n
\r\n
\r\n

```

How to save the number including "kg" to each variable (NO, G, T, N)?

# Answer
This is an overly broad question which borders "write me the code" - this isn't a coding service - and if anything belongs on StackOverflow since it regards processing. That being said, this question would be flagging as overly broad there too.

I'm providing an answer because I believe it may help others here as it speaks to some fundamental programming concepts. This is not a perfect solution by any means, for example it doesn't take program size into account. See the end of the post for a sketch.

There are two main problems you face:

1. Model the input data
2. Process the data

Modeling the input data means structuring your expected input in a meaningful way. Looking at the input data provided, I see this format

* 0-N chars indicate some metadata delimited by a colon (:)
* 0-N white space
* 0-N digits with optional decimal point (0015,5.97)
* 0-N unit designation (kg)
* data is delimited with a CRLF (\r\n)

Now think of each line as a **packet** of information. In that sense, let's create some data structures that describe the data of the packet.

```
// Types
typedef enum {
  NoType,
  NO,
  G,
  T,
  N,
} Type;

// Units
typedef enum {
  NoUnit,
  uKg, // kilogram
  uG,  // gram
} Unit;

// Values - unions are handy to model variants.
typedef union {
  char str[5];
  float dval;
} Value;

```

Given the basics above, let's model a Packet:

```
// the data model for a CRLF delimited packet
typedef struct {
  Type type;
  Value value;
  Unit unit;
  byte valid;
  // metadata
  byte expectUnit; // 1 if a Value has a Unit; 0 otherwise.

} Packet;

```

OK, so that's a basic model of the input data. How to process? Always break down big problems to the smaller, manageable units to provide a solution.

Now there's a huge number of possibilities to parse/interpret your data packets. I am providing a bare bones, brute force approach that you may learn from, and hopefully improve upon. For example I am not providing much in the way of array overruns which can crash a program.

Here's the main processing function, which takes a string of input data (a line) and produces a Packet. In all I am only going to provide for the Type 'G' and leave the rest to you.

```
// readPacket processes the input string pszBuffer and fills pPacket accordingly.
//
// pszBuffer should be a string of characters delimited by \r\n.
// pPacket is a pointer to a Packet which is filled by this function.
//
// returns 1 if packet is valid, 0 otherwise.
byte readPacket(Packet* pPacket, const char* pszBuffer) {
  byte isvalid = 0;
  if (pszBuffer && pPacket) {
    char tmp[10];
    char* psz = (char*)pszBuffer;
    char* pszTmp = 0;
    byte len = 0;
    // initialize packet
    pPacket->type = Type::NoType;
    pPacket->unit = Unit::NoUnit;
    pPacket->valid = 0;
    pPacket->expectUnit = 0;
    // get the Type
    psz = processType(pPacket, psz);
    if (psz) {
      // skip any space characters now.
      psz = trimLeadingSpaces(psz);
      psz = processValue(pPacket, psz);
      // if Type handled, check units and finish.
      if (psz) {
        if (pPacket->expectUnit)
          pPacket->valid = processUnit(pPacket, psz);
        else
          pPacket->valid = 1;
      }

    } // Type not found

    isvalid = pPacket->valid;
  }
  return isvalid;
}

```

OK that's not a lot. The logic is

* Get the packet Type
* IFF a packet Type was found, get the packet Value
* IFF a value was found, get the Unit if required

It's important to breakdown these steps in smaller, manageable functions. First, the code for getting the packet Type.

```
// processType
// Sets pPacket->type to the type found in psz.  Type is delimited by a colon (:)
// Returns 0 (null) if a known Type wasn't found.
// Otherwise a ptr to the data past colon delimiter.
//
char* processType(Packet* pPacket, const char* psz) {
  // find the colon (:) delimiter and return what it leads to.
  byte len = 0;

  char* ptr = strchr((char*)psz, ':');
  char* pResult = 0;
  if (ptr) {
    // found the colon.
    char buffer[4];
    byte len = (ptr - psz) / sizeof(char); // pointer math to find length.
    strncpy(buffer, psz, len);
    // null term buff
    buffer[len] = 0;
    // assume succcess; default will rest to fail.
    pResult = (char*)psz + len + 1; // +1 to skip colon character.
    switch (buffer[0]) {
    case 'G':
      pPacket->type = Type::G;
      pPacket->expectUnit = 1; // unit should be given.
      break;
    default:
      pPacket->type = Type::NoType;
      pResult = 0; // fail, didn't find a known type.
    }
  }

  return pResult;
}

```

So processType sets up the packet Type and adds information about whether to look for Unit information later.

If processType() found a valid Type, the next step is to get the value based in that type with the function processValue

```
// Sets pPacket->value according to the packet Type.
// Returns null (0) if type not supported or value not found,
// otherwise a pointer to the remaining characters following the value handled.
char* processValue(Packet* pPacket, const char* psz) {
  char* ptr = 0;
  // value is construed by Type
  switch (pPacket->type) {
  case Type::G:
    ptr = processFloat(pPacket, psz);
    break;
    //
    // add your additonal Type implementations...
    //
  default:
    // invalid, set psz to null.
    ptr = 0;
  }
  return ptr;
}

```

Great. Now, let's look at a way to get the value for a float:

```
// Sets pPacket->value.dval
// Returns 0 (null) if a value wasn't found.
// Otherwise a ptr past the last character of the decimal value.
char* processFloat(Packet* pPacket, const char* psz) {
  const char *float_chars = ".0123456789";
  char* ptr = (char*)psz;
  if (ptr) {
    // scan ptr until we don't find a match.
    byte index = 0;
    while (strchr(float_chars, (char)ptr[index]))
      index++;

    if (index) {
      //  get the float using a temporary buffer.
      //  dangerous! assuming this will not overrun!
      char buf[10];
      strncpy(buf, ptr, index);
      // null term buff
      buf[index] = 0;
      pPacket->value.dval = atof(buf);
      // advance ptr past the decimal characters for return valie.
      ptr += index;
    }
    else ptr = 0; // fail
  }
  return ptr;
}

```

Finally if all went well, the code should look for the Unit if expected (based on the Type)

```
// Sets pPacket->unit to the unit given in psz.
// Returns 0 if no unit was found, non-zero otherwise.
byte processUnit(Packet* pPacket, const char* psz) {
  pPacket->unit =  Unit::NoUnit;
  if (psz) {
    switch ((char)*psz) {
    case 'k':
      pPacket->unit = Unit::uKg;
      break;
    case 'g':
      pPacket->unit = Unit::uG;
      break;
    default:
      break; // unit initialized to NoUnit.
    }
  }
  return pPacket->unit != Unit::NoUnit;
}

```

Here's a GIST of an arduino sketch using the code above.

Good luck, hope this helps. In the future, pose questions regarding processing on StackOverflow.
> 2 votes

---
Tags: serial, string, data-type, serial-data
---


title: NEED Help With Servo motor

text:
# Question
Title: NEED Help With Servo motor
I have just bought a MG90s tower pro servo for my school project and there is a problem. As soon as I connect my servo to the cnc shield or directly arduino, the whole arduino board turns off. I believe the motor is aking very high power. I even tried to power the motor with a 5v 2amps adapter, but still it turns off.I checked the resistance between the input wires and the wires to DC motor which was very high. As soon as I connected motor to external supply, there was a huge voltage drop. The voltage became almost negligible. DC motor was working fine alone. The servo hasn't even rotated for 1 degree. Please give me a quick solution as I am in a hurry for school deadline is coming. Should I buy a new servo or am I doing something wrong? Please be quick. Thank you. Circuit diagram is below...\]

The code is below -

```
#include <Servo.h>

Servo name_servo;

int servo_position = 0;

void setup() {

name_servo.attach (9);

}

void loop() {

  for (servo_position = 0; servo_position <=180; servo_position +=1){

    name_servo.write(servo_position);
    delay(10);
  }

  for (servo_position=180; servo_position >= 0; servo_position -=1){

    name_servo.write(servo_position);
    delay(10);
  }
}

```

# Answer
> The servo hasn't even rotated for 1 degree.

This is fine, until you apply a control signal nothing much should happen.

> As soon as I connected motor to external supply, there was a huge voltage drop. The voltage became almost negligible. DC motor was working fine alone.

This is a problem; it sounds like your servo is shorted, busted, kaput, no good.
> 1 votes

# Answer
Your conclusion is correct. The servo motor is asking a lot of current.

You need a power supply that is more than 2amps. Connect the grounds (the servo black wire to the Arduino GND). Don't let the current for the servo motor go through the Arduino board. Use wires for the servo motor that can handle high currents. Don't let the power for the servo motor go via a breadboard, because the small metal contacts of a breadboard are not for high currents.

Can you get a smaller servo motor?

Could there be something wrong with the 2 A power supply? Is it a certified and good quality power supply?

Tower Pro does not tell what the stall current of the MG90S is: www.towerpro.com.tw/product/mg90s-3/
> 0 votes

# Answer
I found different sources, that state stall currents for this servo between 0.2A and 0.8A, so a 2A power source should be enough for one of these.

From your wiring diagram (which looks good) I guess, that the Arduino is provided with power by other means (maybe USB). If not, please try it that way. You can easily use a USB power bank or a externally driven USB hub, if you don't want to risk your PCs USB ports with a currently unknown error.

Your code is also ok (it's basically the sweep example code of the servo library).

So there are only 2 possible culprits left:

1. The servo: It might be damaged. I have seen some forum entries, that there are many cheap versions of this servo, which don't meet most quality standards. Depending on where you bought it, it might also been DOA (Dead On Arrival: broken, when it reached you). You should try to connect it with a capable power source (without any connection to an Arduino) and measure the current draw. If the current is too high (or the voltage again dips), disconnect it directly and throw it away.
2. The power source: You didn't write, what power source you used exactly. It might be the case, that it is broken, or that it does not provide the specified amount of current. Some power sources can break on a short (or on drawing too much current). You might have created a short while experimenting and broke it. Then you need a new power source.

Test the servo first, with a fresh power source.
> 0 votes

---
Tags: arduino-uno, motor, servo, shields, arduino-motor-shield
---


# Question
Title: Large(ish) strings failing to send over WiFi101 using WiFiServer
I've based a sketch off the vanilla WiFi101 server examples.

If I define a const char array like this:

```
const char HTML_index[] = "<html><head></head><body>test</body></html>";

```

The server works well. However if I increase the char\[\] size to about 1,300 bytes the server fails to send a response. The device (Feather M0 WiFi) doesn't lock up, I can continue to make HTTP requests and the serial console functions correctly, just no HTTP response. The device and laptop (client) are both on the same WiFi AP so nothing weird there.

First I thought this was a memory issues, but as I'm using newer architecture and IDE using `const` *should* ensure the string is in FLASH.

So I then read some threads about buffer limits per response using other libraries: https://github.com/esp8266/Arduino/issues/3205

But again not sure how applicable this is to an ARM based system/ WiFi101 library.

Is there a limiting buffer size etc when sending HTTP data in my setup? Do I need to split the string up into smaller pieces and send multiple responses? How could I go about debugging this situation?

Edit: This is the example sketch my code is based off: https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi

Edit2: ok I think I know what's going on but can't test right now, will post an answer when I do. I found this thread https://github.com/arduino-libraries/WiFi101/issues/163 which talks about SOCKET\_BUFFER\_UDP\_SIZE. So I looked through the WiFi101 src and found this:

```
#ifdef LIMITED_RAM_DEVICE
#define SOCKET_BUFFER_SIZE 64
#else
#define SOCKET_BUFFER_SIZE 1472
#endif

```

https://github.com/arduino-libraries/WiFi101/blob/master/src/utility/WiFiSocket.cpp

It's likely that my string was actually over 1472 bytes so this makes sense.

Edit3: Found more references:

https://github.com/arduino-libraries/ArduinoHttpClient/issues/14

https://github.com/arduino-libraries/WiFi101/pull/116

So I take it the 1500 in WINC1500 could mean the buffer size. Either way looks like there's a hardware buffer limit and responses larger than ~1400 bytes need to be chunked.

# Answer
As per my notes the WINC1500 has a limit of 1500 bytes per transmission. But some of this is always taken up by TCP overhead so the payload buffer must be smaller, that's why you see numbers like 1460.

From: http://ww1.microchip.com/downloads/en/appnotes/atmel-42739-tcp-client-and-server-operation-using-atwinc1500\_at14596\_applicationnote.pdf

> **2.2.2 TCP Packet Size**
>
> A packet is sized as per the lowest MTU (Maximum Transmission Unit) on the path, which is typically 1500 bytes (for Ethernet) of data including TCP (20 bytes) and IP headers (20 bytes). The packet size is defined in main.h as :

```
#define MAIN_WIFI_M2M_BUFFER_SIZE 1460

```

> The application then defines a socket buffer of this size in main.c as:

```
static uint8_t gau8SocketTestBuffer[MAIN_WIFI_M2M_BUFFER_SIZE];

```

This means that HTTP responses over ~1400 bytes need to be chunked which means split up into multiple calls.

FYI chunked Transfer-Encoding is superseded in HTTP/2: http://undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.html

Info on HTTP chunked encoding: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding

```
Transfer-Encoding: chunked

```

> Data is sent in a series of chunks. The Content-Length header is omitted in this case and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format, followed by '\r\n' and then the chunk itself, followed by another '\r\n'. The terminating chunk is a regular chunk, with the exception that its length is zero. It is followed by the trailer, which consists of a (possibly empty) sequence of entity header fields.

https://www.httpwatch.com/httpgallery/chunked/

https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88

> **Transfer-Encoding**
>
> The use of Transfer-Encoding: chunked is what allows streaming within a single request or response. This means that the data is transmitted in a chunked manner, and does not impact the representation of the content.
>
> Officially an HTTP client is meant to send a request with a TE header field that specifies what kinds of transfer encodings the client is willing to accept. This is not always sent, however most servers assume that clients can process chunked encodings.
>
> The chunked transfer encoding makes better use of persistent TCP connections, which HTTP 1.1 assumes to be true by default.
>
> Chunked data is represented in this manner:

```
4\r\n
Wiki\r\n
5\r\n
pedia\r\n
e\r\n
 in\r\n\r\nchunks.\r\n
0\r\n
\r\n

```

> Each chunk starts with its byte length expressed as a hexadecimal number followed by optional parameters (chunk extension) and a terminating CRLF sequence, followed by the chunk data. The final chunk is terminated by a CRLF sequence.
>
> Chunk extensions can be used to indicate a message digest or an estimated progress. They are just custom metadata that your layer 7 receiver needs to parse. There's no standardised format for it. Because of this, it's probably better to just add your metadata (if any) into the chunk itself for your layer 7.5 application to parse.
>
> For your application to send out chunked data, you must first send out the Transfer-Encoding header, and then you must flush content in chunks according to the chunk format. If you don't have an appropriate HTTP server that handles this, then you need to implement the syntax generator yourself. Sometimes you can use a library to provide an abstract interface.

Possible fix on Arduino platforms is to use StreamLib library or roll-your-own chunking system.

**Update:** I hacked together a sketch and confirmed this works. Next issue was the buffer must be null terminated, BUT this is stripped out before transmitted over TCP so the HTTP chunk size is the buffer size -1.
> 1 votes

---
Tags: string, web-server, arduino-zero
---


title: let Arduino limit it's own input power

text:
# Question
Title: let Arduino limit it's own input power
My current project will be sitting next to a 12VDC power line. It seems a waste no to tap it to power into the Arduino board too. Now I read everywhere that with 12V input quite a lot power gets dissipated by the voltage regulator. Wouldn't it then a wise move to use the board 's own PWM capabilities to throttle the input voltage?

Nother point is whether it is sensible at all when the board is using little current (in this case less than 5mA over the pins for 0.1 sec every few seconds, plus the board in deep sleep mode).

# Answer
> 1 votes
How did you measure that it's going to be 5mA? Because if that's really the case, the regulator dropping 7V (I'm assuming it's a regular 5V arduino) will need to dissipate ~35mW of heat which is not much and it should not cause a lot of problems for your board.

Another option would be using a step-down power supply module, there are tons of available dc-dc converters, mostly based on LM2596 (search for *LM2596 DC-DC module*) which will handle your 12 power rail with ease.

# Answer
> 0 votes
There are some models of clone boards that have a DC-DC switching regulator instead of linear regulators to do just that. The extra cost for the regulator chip, inductor, diode, etc. are probably not worthwhile in the majority of applications tho.

---
Tags: power, pwm
---