title: Wiring BMP280 to Arduino Uno

text:
# Question
Title: Wiring BMP280 to Arduino Uno
I bought a BMP280 and it looks like this:

How can I connect BMP280 to Arduino Uno? I tried the following examples on the web, but they didn't work. I used this library, connecting the PINS in this way:

```
VCC  ->  3.3V
GND  ->  GND
SCL  -> 13
SDA  -> 12
SDO  -> 11

```

But the sensor did not initialize.

# Answer
Eventually as reported here, it worked using this pinout:

```
VCC --> 3.3V
GND --> GND
SCK --> A5
SDI --> A4

```

And this code:

```
#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int hum_raw,temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;
 int8_t  dig_H1;
 int16_t dig_H2;
 int8_t  dig_H3;
 int16_t dig_H4;
 int16_t dig_H5;
 int8_t  dig_H6;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t osrs_h = 1;             //Humidity oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
    uint8_t ctrl_hum_reg  = osrs_h;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF2,ctrl_hum_reg);
    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0,hum_act=0.0;
    signed long int temp_cal;
    unsigned long int press_cal,hum_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    hum_cal = calibration_H(hum_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    hum_act = (double)hum_cal / 1024.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.print(press_act);
    Serial.print(" hPa  HUM : ");
    Serial.print(hum_act);
    Serial.println(" %");

    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];
    dig_H1 = data[24];
    dig_H2 = (data[26]<< 8) | data[25];
    dig_H3 = data[27];
    dig_H4 = (data[28]<< 4) | (0x0F & data[29]);
    dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F); // Fix 2014/04/06
    dig_H6 = data[31];                                   // Fix 2014/04/06
}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
    hum_raw  = (data[6] << 8) | data[7];
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

unsigned long int calibration_H(signed long int adc_H)
{
    signed long int v_x1;

    v_x1 = (t_fine - ((signed long int)76800));
    v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) +
              ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) *
              (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) *
              ((signed long int) dig_H2) + 8192) >> 14));
   v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4));
   v_x1 = (v_x1 < 0 ? 0 : v_x1);
   v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
   return (unsigned long int)(v_x1 >> 12);
}

```

Actually, BMP280 doesn't monitor relative humidity so you can delete the part related to the humidity control.

```
#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0;
    signed long int temp_cal;
    unsigned long int press_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.println(press_act);
    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];

}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

```
> 1 votes

# Answer
The BMP280 is a sensor that can be used at 3.3V, but not at 5V. The datasheet tells that the interface pins may be maximum 3.6V (when the sensor is powered with 3.3V). That means you may not connect the sensor to an Arduino Uno. Not to the SPI interface and not to the I2C interface. The sensor might already be damaged. This is not a joke. When sensor is still working, the results might be noisy or the values could drift too much.

The easiest solution is a level shifter module for I2C. Another option is to add two extra pullup resistors of 10k from SDA to 3.3V and from SCL to 3.3V and connect the SDA and SCL directly to the Arduino Uno. It will not be reliable, but with some luck it will work. You need some luck, because it will not be okay according to the datasheet of the ATmega328P.

You could also buy a 3.3V Arduino board (Arduino Due, Arduino Zero, Arduino M0, and so on), or buy a BMP280 module that is compatible with 3.3V and 5V signals: Adafruit BMP280
> 0 votes

---
Tags: arduino-uno, sensors
---


title: Void value not ignored

text:
# Question
Title: Void value not ignored
Why does this throw the error: "void value not ignored as it ought to be

returning = printTemperature(returnLine);"

```
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
     return 0;
  } else {
    return tempC;
  }
}

void loop(){

   delay(2000);
   feeding = printTemperature(feedLine);
   returning = printTemperature(returnLine);
    mySql;
    feeding = 0;
    returning = 0;
}

```

Both 'feeding' and 'returning' are declared as a float too.

# Answer
> 2 votes
printTemperature() is declared void (i.e., nothing returned) but it contains a return statement, and you've attempted to assign the (void) value. You probably meant to declare the function as 'float'.

# Answer
> 1 votes
First of all: In C/C++ world void means "empty" as in "no value".

As the method is declared void it is saying that it does not return a value. But the code sets the value and also assigns the return value to a variable. Logically that does not make sense.

In the old days a void method returned an int (I'm not sure whether that is still the case) but it has never been a good idea to make a value returning method a void returning method. So technically in the old days it made sense but it still was "not a good idea"

Nowadays compilers will return an error when you return a value in a void method. This can be turned off by using the -fpermissive compiler directive. This directive might be useful in some template cases. I advice not to use it.

---
Tags: arduino-uno
---


# Question
Title: Arduino to read from RS232 converter to TTL serial module (updated)
Here's the system I want to work on:

1. The weight controller device detects weight which can transfer data via RS232 serial connection
2. I used RS232 converter to TTL serial module to connect the weight controller device to Arduino
3. The TTL connections were made to respective pins of Arduino UNO Board (GND-GND, VCC-5V, RX-0, TX-1)

**The serial print from serial connection should produce 17 character length string : ST,GS 1.58,kg**

## Why am I getting strange results at times?

```
// Read Serial (RS232) data from Weight Controller Device via RS232 to TTL Converter Module

// Ignore the include statement, the editor does not allow pasting certain characters

include SoftwareSerial.h

int RX_PIN = 2;
int TX_PIN = 3;
int BAUD_IDE = 9600;
int BAUD_WEIGHT_SENSOR = 9600;

// serial port from weight controller
SoftwareSerial mySerial = SoftwareSerial(RX_PIN, TX_PIN);

void setup() {
  mySerial.begin(BAUD_WEIGHT_SENSOR);
  Serial.begin(BAUD_IDE);
}

void loop() {
  while (mySerial.available()) {
    int inChar = mySerial.read();
    if (inChar != '\n') {
      serialData += (char)inChar;
    }
    else {
      int dataSize = serialData.length();
      Serial.print(serialData);
      Serial.print(" length:  ");
      Serial.print(dataSize);
      Serial.print("\n");
      delay(3000);
      serialData = "";
    }
  }
  serialData = "";

}

// this one works perfectly but i want to store as string to
process
// information and use for other functions
/*void loop() {
if (mySerial.available()){
  Serial.print((char)mySerial.read());

```

# Answer
You need to disconnect the Arduino\`s RX and TX pins from any device before trying to upload a sketch via USB, because the Serial data is directly wired from the USB chip to these pins. It's as if you're trying to flash the thing behind your RS232 adapter.
> 2 votes

# Answer
You are attempting to talk to your peripheral via a second serial UART implemented in software on arbitrary pins, which should leave the hardware UART free for uploading and debug or other runtime communication between the Arduino and a PC.

However, the "arbitrary pins" you choose to use to connect the peripheral are *the same* pins as used by the hardware UART.

**Move your peripheral to two other pins**, for example

```
int RX_PIN = 2;
int TX_PIN = 3;

```

and move the connections accordingly

Also consider if you really want `Serial.println()` which will add a line break after every character in the output, and will also print the received characters as their numeric ASCII codes, one per line, rather than printing the characters themselves. You probably want `Serial.write()`.
> 1 votes

---
Tags: arduino-uno, serial, softwareserial, uploading, rs232
---


title: Problem Atmel Studio 7 with uploading

text:
# Question
Title: Problem Atmel Studio 7 with uploading
I have a problem with the interworking between Atmel Studio 7 and Arduino IDE 1.6.10.

I recently upgraded from IDE 1.0 to 1.6.10 and I can no longer upload my code to the Arduino. Everything works including compiling and it does recognise my COM3 port. Atmel Studio is configured for no external programmer.

When I compile with the Arduino IDE it *does* upload the code. My question is what goes wrong here, what do I need to do solve it. Thanks for your help

This the message I have in the end:

```
Compiling 'GridMonintor_V1R1' for 'Arduino Nano w/ ATmega328' Binary sketch size: 12,268 bytes (used 40% of a 30,720 byte maximum) (22.20 secs)

Minimum Memory Usage: 774 bytes (38% of a 2048 byte maximum) Uploading to I/O board using 'COM3'

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

```

# Answer
> 1 votes
> ...Specify a programmer using the -c option and try again

For Arduino, the programmer switch must be `-c arduino`. The full arguments for `avrdude`, in the Atmel Studio 7 External Tools window, are:

```
-c arduino -p m328p -P COM3 -b 57600 -D -V -U flash:w:"$(TargetDir)$(TargetName).hex":a

```

See avrdude options.

# Answer
> 0 votes
you might want to try the following command: -C “C:\Program Files\Arduino\hardware\tools\avr\etc\avrdude.conf” -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:$(TargetDir)$(TargetName).hex:i

where i is used at the end for intel. the one provided above by @flanker uses a

see this detailed tutorial How to program Arduino using ATMEL Studio 7

# Answer
> 0 votes
Switch on vMicro\>Uploader\>verbose then try the upload and post the output as a .txt file in a new thread in the visualmicro.com forum.

http://www.visualmicro.com/forums

Because you are using the Visual Micro plugin the forum is the best place to see help.

We will also check that you have configured the new arduino location against the arduino 1.6.x option in Visual Micro and not the Arduino 1.0. option as you had it originally. In fact you can have both IDE versions configured in Visual Micro at the same time and switch between them using the tool bar.

Thanks

---
Tags: arduino-ide, uploading, atmel-studio
---


# Question
Title: Square wave based on falling edge of alternative pulse of upcoming RPM square wave
In my recent project, I have RPM Square wave from vehicle. Now, based on that I want square wave based on falling edge but only alternative pulse of RPM square wave.

I think below image clear more properly.

Upper yellowish square wave which I need. And below pinkish square wave is RPM square wave.

I made a code for that and it's working fine but when RPM is stable. But when RPM change rapidly then it's not working fine.

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

const int kPinInj = 12;

volatile uint32_t kInjTime = 0;

void setup()
{
  Serial.begin(250000);

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

  pinMode(kPinInj, OUTPUT);
}

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

  Serial.println(RPM);

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

void countRPM()
{
  RPMpulses++;

  if(RPMpulses % 2 == 0)           // Skip alternative pulse
  {
    kInjTime = millis();
    digitalWrite(kPinInj, HIGH);
  }
}

int getRPM()
{
  Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
  RPMpulses = 0;
  Final_RPM = min(99999, Final_RPM);
}

```

After SUGGESTION, updating my codes. But it output waveform has some problem. In white circle, you can see that problem.

# Answer
Rather than saying

```
if(RPMpulses % 2 == 0)           // Skip alternative pulse
  {
    kInjTime = millis();
    digitalWrite(kPinInj, HIGH);
  }

```

and later setting `kPinInj` in the main loop, you could act as follows:

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

```

This would ensure that your trace 1 toggles properly. If you want a shorter up-time on that trace, you could treat `CHANGE` interrupts rather than `FALLING`, and maintain `RPMpulses` as a number twice as big as now, ie use 120000 instead of 60000 in the RPM calculation, and could say:

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

```

Note, the floating point arithmetic in `getRPM()` is slow. At a 750 ms refresh interval, that may not matter much. But you probably can get good enough results rather more quickly using just integer arithmetic, if you parenthesize the expression somewhat as follows:

```
Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval;

```

That is, do any remainderless divisions early; multiply all the remaining numerator terms together into a large number; then divide by the comparatively small `refreshInterval`, ending up with numerous significant digits without the use of floating point arithmetic, which takes many milliseconds on typical Arduino systems.

*Edit 2:* If your modified code still says `RPMpulses = 0;` within `getRPM()`, you may get a glitch at the end or beginning of each refresh interval. You may instead need to say `RPMpulses = 1;`, or `RPMpulses &= 1;`, or some such. Also, to avoid an extra count when the latter expression is 1 instead of 0, say `RPM0 = RPMpulses &= 1;` and use `(RPMpulses-RPM0)` instead of `RPMpulses` in calculating `Final_RPM`.
> 1 votes

# Answer
There are some things you shouldn't be doing within an interrupt service routine (ISR) like `countRPM()`:

1. Don't call the `millis()` function. It depends on other interrupts which will be disabled during the execution of your ISR.
2. Don't call `digitalWrite` or any other functions
3. Don't use execution cycles hungry operators like `%` (modulo). To obtain modulo 2, just use a bit mask for the LSB.

What you should actually be doing within the ISR is just setting/resetting a flag or variable. Then, do all your stuff in the `loop()` function according the value of the flag or variable.
> 1 votes

---
Tags: arduino-uno, programming
---


title: DS18B20 - Temperature a bit off?

text:
# Question
Title: DS18B20 - Temperature a bit off?
I'm trying to measure the temperature using a DS18B20 sensor. I'm using the DallasTemperature and OneWire Libraries. The sensor is connect in Pin 10 with a 4k7 resistor between VDD and DQ (actually I'm using 4x 1k and 2x 330 ohms) as so:

Here's the code I'm using:

```
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 10

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

float celsius;

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

  sensors.setResolution(12);

  sensors.begin();
}

void loop(void) {
  sensors.requestTemperatures();
  celsius = sensors.getTempCByIndex(0);

  Serial.println(celsius);
}

```

The sensor is outputing values close to the actual temperature (measure with a mercury thermometer), but a bit off.

Example:

```
Sensor Temperaute: 34.44°C
Thermometer Temperature: ~32°C

```

Why is that? And how can I fix it?

# Answer
> 1 votes
When the wires to the DS18B20 are short, you can use a 10k resistor as well.

The DS18B20 is accurate. If you have connected it wrong and it became very hot, then it might be damaged. But normally it is always accurate.

Many report that the DS18B20 returns a high temperature, and the cause is often something nearby that makes the DS18B20 warmer. For example an Arduino board (with a hot voltage regulator) or a computer screen or a certain air flow of warm air or even very dim sunlight. A normal thermometer does not do that, but the DS18B20 is highly influenced by warm things nearby.

Some temperature sensors have a problem with self-heating. You could add a delay of 5 seconds in the loop function, to see if that makes a difference.

To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water).

The picture uses pin 2 and the sketch uses pin 10. I assume that is a mistake.

---
Tags: temperature-sensor, ds18b20
---


title: Serial LCD has like a "rolling shutter"

text:
# Question
Title: Serial LCD has like a "rolling shutter"
I've attached my LCD Display (AV1624YRB-SJ) to my Arduino Nano on the following pins:

```
#define LCD_RS 7
#define LCD_ENABLE 8
#define LCD_D4 9
#define LCD_D5 10
#define LCD_D6 11
#define LCD_D7 12
#define LCD_CONTRAST 6 //PWM Wave with capacitor for contrast

```

and im initializing it this way:

```
LiquidCrystal lcd(LCD_RS, LCD_ENABLE, LCD_D4, LCD_D5, LCD_D6, LCD_D7);

byte arrow[8] = {
    B00000, B00100, B00010, B11111, B00010, B00100, B00000,
};

void setup() {
  pinMode(LCD_CONTRAST, OUTPUT);
  pinMode(LCD_D4, OUTPUT);
  pinMode(LCD_D5, OUTPUT);
  pinMode(LCD_D6, OUTPUT);
  pinMode(LCD_D7, OUTPUT);
  analogWrite(LCD_CONTRAST, STARTCONTRAST); // Set LCD Contrast

  lcd.begin(16, 2);
  lcd.createChar(CHAR_ARROW, arrow);
  lcd.setCursor(3, 0);
  lcd.print("Welcome To");
  lcd.setCursor(1, 1);
  lcd.print("My Test");
  delay(2000);
}

```

The Problem is, that there is nothing to see on the display. If i crank up the contrast slightly you can see something like a rolling shutter effect.

http://i.imgur.com/FOIEwVj.gif

The display worked just fine 3 days ago. Where could be a mistake. I don't remember changing something, but i tried rewiring.

# Answer
As I noted in a comment to the question Arduino LCD is displaying gibberish, sometimes, a PWM's sharp-cornered waveform might introduce a lot of noise into the LCD. If you have to use PWM, you probably should put a good low-pass filter between PWM and LCD pin 3.

Check whether using a fixed voltage (from a voltage divider or pot) fixes the problem. That fixed the problem in the case of the linked question.

If you need programmable control of contrast, and can't get PWM to work without heroic measures involving op-amp based filters, you could use a digital pot or a DAC.
> 1 votes

---
Tags: arduino-nano, lcd
---


# Question
Title: Motor running during Motor Shield R3 reset
I have a problem with the Arduino Motor Shield R3 on an Arduino Uno. I Have a DC Motor on the A Channel and the Shield is connected to an external power source. When I reset the Arduino card the motor starts running by default until the pins are initialized.

This is really problematic for me because the motor is on a rail delimited by 2 switches, when a switch is reached the motor stops. When the motor moves during reset the value of the switches are not read yet, which causes the motor to go beyond the switch and be blocked afterwards.

When I reset the card I read the value of the 3 digital pins used to drive the motor :

* pin 12 : Direction (DirA), HIGH motor foward, LOW motor running backward
* pin 3 : Power (PwmA), HIGH motor running, LOW motor not running
* pin 9 : Brake (BrakeA), HIGH brake is on, motor can't run, LOW brake is off, motor can run

Before reseting I put the 3 pins at HIGH, At reset, pin 12 == HIGH, pin 9 == LOW, pin 3 == HIGH which means that the brake is disengaged but the Power is still here, so the motor starts running again until the pinMode function is reached. During that reset time of approximately 2 seconds, the motor has the time to go beyond the switches which causes the system to break.

**Is this normal ? Is there a way to force the pin 3 to be at LOW when the Arduino resets ?** I put my code at the bottom.

**Naïve solution** : is to put PwmA at LOW when a switch is reached, so I'm sure it will stay that way until the next reset. But if the arduino is reseted while the motor is running I still have the problem.

```
int closeSwitch = A3;
int openSwitch = A2;
int DirA = 12;
int PwmA = 3;
int BrakeA = 9;

int OpeningDirection = LOW;
int ClosingDirection = HIGH;

bool motorRunning = false;
bool motorOpening = false;
bool openSwitchReached = false;
bool closeSwitchReached = false;

void setup() {

  Serial.begin(9600);

  sendToPC("Init\n"); //This is just to read the init state of the pins
  Serial.print(digitalRead(DirA));
  Serial.print(digitalRead(BrakeA));
  Serial.print(digitalRead(PwmA));

  pinMode(openSwitch, INPUT);//is High when Hublot opened
  pinMode(closeSwitch, INPUT); //is HIGH when hublot closed
  pinMode(DirA, OUTPUT); //Initiates Motor Channel A pin
  pinMode(BrakeA, OUTPUT); //Initiates Brake Channel A pin
  pinMode(PwmA, OUTPUT); //Initiates Brake Channel A pin

  sendToPC("\nAfter\nA:"); //After init all is LOW
  Serial.print(digitalRead(DirA));
  Serial.print(digitalRead(BrakeA));
  Serial.print(digitalRead(PwmA));

  //Stopping the motor
  setMotorSpeed(0);
  if (digitalRead(BrakeA) == LOW) {
    brakeMotor();
  }

  //Is the first switch on
  openSwitchReached = (digitalRead(openSwitch) == HIGH);
  //Second switch state
  closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

  handleSerialInput(-3); //Send ping return
  handleSerialInput(-2); //Send status
}

void sendToPC(const char * str) {
  Serial.write(str);
  delay(215); //Delay to avoid answers being read as one
}

void setMotorSpeed(int speed) {
  if (speed > 0)
    digitalWrite(BrakeA, LOW);   //Disengage the Brake for Channel A
  digitalWrite(PwmA, HIGH);   //Spins the motor on Channel A at full speed
}

void setMotorDirection(int direction) {
  digitalWrite(DirA, direction); //Establishes direction of Channel A
}

void brakeMotor() {
  digitalWrite(BrakeA, HIGH);
  //digitalWrite(PwmA, LOW); -> this is my naïve solution
}

void handleSerialInput(int input) {
  Serial.print(input);
  if (input == 1 && !openSwitchReached) { //open
    brakeMotor(); // stop motor
    delay(100);
    setMotorDirection(OpeningDirection);
    setMotorSpeed(255); // set motor max speed
    motorRunning = true;
    motorOpening = true;
    sendToPC("HublotOpening");
  }
  else if (input == 2 && !closeSwitchReached) { //close
    brakeMotor(); // stop motor
    delay(100);
    setMotorDirection(ClosingDirection);
    setMotorSpeed(255); // set motor max speed
    motorRunning = true;
    motorOpening = false;
    sendToPC("HublotClosing");
  }
  else if (input == -2) { //get status
    if (openSwitchReached)
      sendToPC("HublotOpened");
    else if (closeSwitchReached)
      sendToPC("HublotClosed");
    else if (motorRunning && motorOpening)
      sendToPC("HublotOpening");
    else if (motorRunning && !motorOpening)
      sendToPC("HublotClosing");
    else if (!motorRunning)
      sendToPC("HublotNotMoving");
  }
  else if (input == -3) //Ping
    sendToPC("ArduinoHublot");
  else if (input == 0) { //Stop
    brakeMotor(); // set motor max speed
    motorRunning = false;
  }
  else {
    sendToPC("WTF");
    Serial.print(input);
  }
}

void loop() {

  openSwitchReached = (digitalRead(openSwitch) == HIGH);
  closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

  if (openSwitchReached && motorRunning && motorOpening) {
    sendToPC("HublotOpened");
    brakeMotor();
    motorRunning = false;
    delay(200);
  }
  else if (closeSwitchReached && motorRunning && !motorOpening) {
    sendToPC("HublotClosed");
    brakeMotor();
    motorRunning = false;
  }

  if (Serial.available()) {
    int read = (Serial.readStringUntil(':')).toInt();
    handleSerialInput(read);
  }

}

```

# Answer
> 1 votes
Add pulldown resistors (10KΩ) to any pins you want to force to be low at reset.

(Quite frankly I'm amazed they don't exist on all inputs to the board by default - it seems a bit of a fatal omission).

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


# Question
Title: How do I make specific tones with a piezo buzzer?
I am using a piezo buzzer and fiddling around with it a little bit. I currently have different tones with delays in between and I have to do a lot of trial and error for the piezo buzzer to play sounds like I want it to. Is there a better way to do this? because at this rate I will be stuck for a while.

I am trying to get the piezo buzzer to make the sound of an alarm. Any suggestion on how I can get it to sound exactly like an alarm or is trial and error the only way?

# Answer
> 2 votes
It's very hard to know from your question what you are having trouble with. I have a piano and I can hit the keys, but it takes me a long time to hit them in the right order and with the right timings to create a new symphony.

Anyway, if creating the sounds is the problem, have you looked at the Tone library?

Different alarms have different sounds. I once heard an alarm which sounded like the start of Fuer Elise, so probably the notes were `E` and `D#`. That would make their frequencies about 330Hz and 311Hz:

```
void loop()
{
    tone(pin, 330, 250);
    delay(300);
    tone(pin, 311, 250);
    delay(300);
}

```

The sound you linked to sounds to me like it starts on a C, and slides up gradually one octave. One octave higher is double the frequency, so this code should do that:

```
void loop()
{
    const int startFreq = 523;  // C5 is 523Hz

    // Start at the given freqency, and increase gradually by
    // one octave (double the frequency)
    for (int freq=startFreq ; freq<= (startFreq*2) ; ++freq)
    {
        tone(pin, freq, 10);
        delay(3);
    }
}

```

---
Tags: arduino-uno, c++, piezo, buzzer
---


# Question
Title: How to use a 4-pin ultrasonic sensor as a 3-pin ping sensor?
```
const int pingPin = A0;

void loop() {
  long duration, inches, cm;
  pinMode(pingpin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}

```

How to change this code for a 4-pin ultrasonic sensor?

# Answer
The four pin `Echo)))` module is basically the same as three pin ones, except for triggering is done by another pin. So you don't have to care about setting pin to the output mode and switching it back to the input mode after the trigger pulse. You can read about it for example here.

```
const int8_t pingPin = A0;
const int8_t trigPin = A1;

void setup()
{
  pinMode(pingPin, INPUT);
  pinMode(trigPin, OUTPUT);
}

void loop()
{
  // pulse on trigger pin:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // 10us is minimum trigger pulse duration
  digitalWrite(trigPin, LOW);

  // measure HIGH pulse duration:
  long duration = pulseIn(pingPin, HIGH);

  // and rest of the code:
  long   inches = microsecondsToInches(duration);
  long       cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}

```
> 1 votes

---
Tags: arduino-pro-mini
---


# Question
Title: Why can't I use an optocoupler to drive an AC circuit using the arduino digital pins?
So, when I searched for ways to drive AC circuits from Arduino, everyone suggested relays with a transistor switching circuit to channel an external 5V. I was wondering what would happen if I used an optocoupler like 4n35 to drive an AC circuit. Will the phototransistor inside the chip burn out?

# Answer
> 2 votes
Use it with Triac. I use MOC3020 + BT138 + 330 and 510 Ohm resistors. It works good as relay and in dimmer scheme. Scheme is here http://cyber-place.ru/attachment.php?attachmentid=1030&d=1370462030

# Answer
> 1 votes
No. A 4N35 will switch 150mA at 30V DC. See http://elinux.org/RPi\_GPIO\_Interface\_Circuits for more detail. If you are proposing to switch 110/240V AC there are safety issues. You should look at available commercial modules.

# Answer
> 1 votes
Normally Opto couplers like a 4N35 were not designed to drive an application load. Typically they are used to trigger another device such as a SCR or Triac. There is a vidio I would recommend you watch, it gives some information and the comments are good. Give this a try:

https://www.youtube.com/watch?v=FVef6f2\_Si8

Gil

# Answer
> 1 votes
SSR's typically have a arduino friendly 3v + dc input, and can switch 10+ amps of up to 330vac.

---
Tags: arduino-uno, relay
---


title: Running Multiple Languages on Arduino

text:
# Question
Title: Running Multiple Languages on Arduino
This is mostly a conceptual question. Is it possible to have two scripts running on an Arduino, where one is a Julia script, and one is a Python script or something like that?

# Answer
> 0 votes
Basically no, because you can't run either Julia *or* Python, let alone both together.

Bear in mind also what an Arduino is (what most of them are, anyway): a low (computational) power microprocessor with a tiny amount of RAM. No operating system, no multi-tasking. Not in the same league as, for example, a Raspberry Pi.

---
Tags: python
---


# Question
Title: Trying to understand interaction of interrupts, noInterrupts and delays
I'm having trouble understanding how to activate interrupts so that they operate only when they should. With this code, I seem to get erratic performance when I either attach or unattached interrupts, or when I try using noInterrupts. What I am trying to accomplish is to deactivate the alarm function from running until a slight delay is initiated upon hitting an incorrect key. That would allow leaving the premises without triggering the interrupt. Does noInterrupt only affect the function in which it is placed??

```
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int PIR_SensorPin = 2;
int LED_OutPin = 11; //green
int Alarm_OutPin = 12; //red
int alarm_count = 0;
volatile boolean trigsensor = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;
int timeout = 10000;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (LED_OutPin, HIGH);
  }
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
  Serial.println ("System Ready");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop()
{
  readKeypad(); // Serial.println ("at keypad");
  if (trigsensor == true) {
    alarm ();
  }
}

///////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  alarm();
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("trigsensor="); Serial.println (trigsensor);
  Serial.println ("at Alarm");
  if (away == true && trigsensor == true) {
    noInterrupts();////////////////////////////////
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW); delay (500);
      digitalWrite (LED_OutPin, HIGH); // delay (1000);
      //   digitalWrite (LED_OutPin, LOW); delay (1000);// End by turning off light
      Serial.println (alarm_count);
    }
  }
  trigsensor = false;
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    tone(10, 900, 100);
    Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  digitalWrite (LED_OutPin, HIGH);
  digitalWrite (LED_OutPin, LOW);
  trigsensor = false;
  away = false;
  readKeypad();
}

///////////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  noInterrupts();
  Serial.println ("@ incorrect PIN ");
  //detachInterrupt(0); Serial.println ("interrupt off 1");
  trigsensor = false;
  away = true;
  digitalWrite (LED_OutPin, HIGH);
  delay(timeout);
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); Serial.println ("interrupt on 2");
  alarm(); Serial.println ("here");
}

```

# Answer
> 1 votes
Well, yes, I think attaching and detaching interrupts isn't really something that you should do to often. It also won't really make your code very much more readable.

You may have a look at programming (embedded systems) in general. A technique I like to do is making a (non-blocking) state machine. In this way you don't even need interrupts (you can actually have interrupts if you want, though).

Also, it may be worth noting that making your code more readable and understandable is likely going to improve your "idea of what is going on" and thus improve it's reliability. This is commonly done by designing and applying "scope" to your code. You've done well on the keypad functions, giving them a sane name and reasoning. You could've put them in a class, but that's not where the errors are at.

Basically, your alarm has a few states:

* Armed
* Unarmed
* Alarm!
* Just activated

From these, you can form a state diagram. Usually, "events" lead to the state of your system being changed. For example:

simulate this circuit – Schematic created using CircuitLab

(Sorry for "abusing" the schematic editor (: ) As you can see, events can be user interaction/sensors/timing, basically anything.

By designing your code in a state diagram, you get an idea of what you want your machine to do, at what moment. And what other states it can go to from there (and when/how).

Your code will become something along the lines of:

setup

```
enum STATE{
  armed,
  unarmed,
  justActivated,
  alarm
};

STATE systemState = unarmed;
long timeGettingArmed;

```

loop

```
switch(systemState){
   case armed:
   if(breakinSensor.check() == HIGH){
      systemState = alarm;
   }else if(keyPad.check() == deactivated){
      systemState = unarmed;
   }
   break;
   case unarmed:
   if(armButton.check() == HIGH){
      timeGettingArmed = millis(); // Or you could just do a delay here.
      systemState = justActivated;
   }
   break;
   case justActivated:
   if(timeGettingArmed + waitTime < millis()){
     systemState = armed;
   }
   break;
   case alarm:
   if(keyPad.check() == deactivated){
     systemState = unarmed;
   }else{
     beep();
   }
   break;
}

```

Ofcourse you'll have to highly adapt this code to suit your needs, I doubt it will even compile. But it can also be a part of designing your program, try just writing it out in words (or explaining it to someone), before you program it.

\*You could make use of the interrupts by checking in the interrupt if the state is "armed" and then setting the state to "alarm". This way you avoid the interrupt messing up any of your logic and having to disable it.

The cool thing of this "non-blocking" (if you don't use delays) state machine is that you can actually add more statemachines to it, and it will seem like the processor does everything at the same time. This is because it skips rather fast through the "i/o checks".

---
Tags: arduino-uno
---


# Question
Title: Calculate the time since arduino started working for a year
I want Calculate the time since arduino started working for a period of one year using arduino uno and when the period is over flip a light on

# Answer
Simplest solution would be to use `millis()`, but you will need to somehow take care of the periodic rollover. Creating a lower frequency software timer, as explained by Jot, is one solution. Another option is to extend `millis()` to 64 bits:

```
uint64_t millis64()
{
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

```

You must call this function at least once every 49.7 days, otherwise it will loose time. I would just call it on every loop iteration, like this:

```
const uint64_t ONE_YEAR = 365.25 * 86.4e6;  // Julian year

void loop()
{
    if (millis64() >= ONE_YEAR) {
        // do some stuff...
    }
}

```

Besides the issue of a possible power failure, there is another caveat: the Arduino Uno is clocked off a ceramic resonator. These are not very accurate, and are typically specified to be within 0.5% of their nominal frequency. This means that your “year” can be off by as much as 1.8 days. RTCs are clocked off a quartz crystal and are then far more accurate. Ultimate accuracy could be achieved with a GPS receiver.
> 1 votes

# Answer
The function millis counts up to about 50 days. However, you can make a software timer with millis of, for example, 1Hz. With a unsigned long that counts the seconds, it is easy to count a year.

It will not be reliable. When the power is off, it starts again. A RTC (Real Time Clock) with its own battery is better.

Are you a good software engineer ? How can you be sure that it will work ?
> 1 votes

# Answer
I would use a network card to talk to an NTP server. In setup(), fetch the time and save it to EEPROM if there's not one already saved. You can then ping the NTP server every day or every boot, comparing the saved date and responding as appropriate. This strategy avoids MCU timer slew, power-out milis() resets, and extra hardware (other than networking, which more and more projects have already anyway).
> 1 votes

---
Tags: arduino-uno, timers, time
---


# Question
Title: What design patterns can I use to handle user input and display updating?
I've used enough products with embedded microcontrollers and unresponsive UIs to know that it can make or break a product. Even a slight delay or lag between the button presses and the display updating, or button presses being ignored or double counted, can be extremely frustrating.

What design patterns can be used to deal with user input (from buttons) and updating displays without causing these issues?

I currently use the following kind of pattern (this is simplified down to the bare minimum):

```
#include <Bounce.h>

#define GREEN_LED       6 // Pin for green LED

#define BUTTON_PIN      15 // Pin for button - uses external pull down so active high

#define DISPLAY_REFRESH_INT 100 // How many MS between display updates

Bounce button = Bounce(BUTTON_PIN, 5);

// To signal between the button read and the display update
bool ledState = false;

// Used to keep track of last display update
long displayUpdate = 0;

void setup()
{
    pinMode(GREEN_LED, OUTPUT);
    pinMode(BUTTON_PIN, INPUT);
}

void loop()
{
    // Read the button status
    if (button.update())
    {
        if (button.risingEdge())
        {
            ledState = !ledState;
        }
    }

    // Update the display periodically
    if (millis() - displayUpdate > DISPLAY_REFRESH_INT)
    {
        displayUpdate = millis();

        digitalWrite(GREEN_LED, ledState);
    }

}

```

What other options are there? Is it ever worth using pin change interrupts to read buttons (if we are not considering battery life!).

# Answer
The answer depends on exactly how the sketch is meant to respond to the user interaction.

**External interrupts**
If the interaction depends on responding very accurately to the rising or falling edge of an input event (as in your example), then an external interrupt may be the way to go, if possible.

This is particularly important if the input event might be shorter that the duration of a call to `loop()`. If that happens, consecutive attempts to poll the input could completely miss the state change. It's quite rare for a user input event to be that short though, unless `loop()` is quite slow to execute.

External hardware to get help that though, e.g. by having an input which latches until it is read and reset by the microcontroller.

**Improving polling frequency**
External interrupts often aren't possible (e.g. because the chip only supports a limited number), or they are simply overkill/unnecessary for a given application.

In those cases, it may still be possible to improve the timing precision when using polling. One option is to split up all the different parts of the main loop into separate functions. On each successive iteration of `loop()`, it will call the next function, and then wrap round to the first. In between each of those functions, it can poll the button. Here's a simple example:

```
unsigned int g_section = 0;

void setup() { }

void pollButton()
{
    //...
}

void runSection0()
{
    //...
}

void runSection1()
{
    //...
}

void runSection2()
{
    //...
}

void loop()
{
    // Poll the button on every pass:
    pollButton();

    // Execute the next section of the main code:
    switch (g_section)
    {
    case 0: runSection0(); break;
    case 1: runSection1(); break;
    case 2: runSection2(); break;
    }

    // On the next iteration, run the next section:
    if (++g_section > 2) g_section = 0;
}

```

One important issue with this approach is that it's very difficult to make each of those `runSectionX()` functions take the same execution time. That can result in the button being polled inconsistently from one iteration to the next. If it's fast enough though, then it shouldn't be too big of a problem.

**Display update**
Updating a display is unfortunately often quite slow, compared to many other operations. That means you need to be quite careful where you do it. Inside an Interrupt Service Routine often wouldn't be appropriate, as that could introduce other timing issues in your sketch.

Realistically, you'd have to do it in the main loop. If you absolutely have to run it quickly though, then it can be included in the faster polling example I've given above -- i.e. update the display on every iteration, the same as polling. You have to be careful to avoid partial updates though.
> 6 votes

# Answer
For program control, I made something of a menu handling framework for one of my projects and shared the source on Github. *Note that this is for chipKIT but the menu handling code is generic.* After building my 3rd or 4th huge if-else-if and switch structure, I decided there had to be a better way. *Credit for the source of the static menu structures.*

I just use the main loop to check the button.

I'm wanting to say the first step is to get a TFT. If you try it, you'll never go back... I particularly love the Adafruit 1.8" TFT with joystick. Arduinos are slow enough that I cannot recall caring to debounce user input.
> 2 votes

# Answer
You could interrupt instead of polling if you can de-bounce the buttons in hardware. Otherwise you'll be take many more interrupts than there were button presses and still have to de-bounce them in software.

But to the primary question, a collection of state machines can be very useful, at least for the ui, and give you most of the benefits of multi-tasking without needed a m/t kernel. can be in RAM limited devices, unfortunately, because

The technique could be especially useful on these small devices but for the severe limits on RAM, making it something of a challenge to divide your state-machine data between flash and RAM, to fit.
> 1 votes

# Answer
As Chris K i've also implemented a static menu library with a wide variety of output options like Serial,LCD,TFT, etc.. I've started it to help in a friends project and I'm also sharing it open source for people that with similar problems, hope you can find it useful.

https://github.com/neu-rah/ArduinoMenu
> 0 votes

---
Tags: button, ui, display
---


title: door protector arduino program

text:
# Question
Title: door protector arduino program
Please check the arduino program given below and help me to find out error. The program is for following hardware. GSM 800 module Arduino Uno board Limit switch(2)

We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.

We run this program & it run but it sends the massage repeatedly after some time. Please help me to find out error..

***my ARDUINO code is***

```
const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;
bool i = true;
bool j = true;
bool k = true;
bool l = true;
int buttonState1 = 0;
int buttonState2 = 0;
void setup() {

  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void loop() {
  buttonState1 = digitalRead(Main);
  if (buttonState1 == HIGH && i == true ) {
    digitalWrite(Main_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Main Door is closed");
    Serial.write(0x1A);
    delay(5000);
    i = false;
    j = true;
  }
  else
  { if (buttonState1 == LOW && j == true )

    { digitalWrite(Main_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91---------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Main Door is open");
      Serial.write(0x1A);
      delay(5000);
      i = true;
      j = false;
    }
  }

  buttonState2 = digitalRead(Store);
  if (buttonState2 == HIGH && k == true) {

    digitalWrite(Store_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(5000);
    k = false;
    l = true;
  }
  else
  { if (buttonState2 == LOW && l == true)
    {
      digitalWrite(Store_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91------------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Store room is Open");
      Serial.write(0x1A);
      delay(5000);
      k = true;
      l = false;
    }
  }
}

```

# Answer
> 1 votes
I can't see any obvious flaws in the code other than the excessive use of delay. However you could make your code a lot cleaner which makes it easier to spot the errors.
The version below has the duplicate lines moved into a function and instead of using the poorly named i,j,k & l to track two states it uses two variables to do the same job. Finally things that don't need to be global have been moved to being local.

```
const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;

void setup() {
  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void sendMessage(char *text) {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print(text);
    Serial.write(0x1A);
    delay(5000);
}

void loop() {
  static int oldState1 = -1;
  static int oldState2 = -1;

  int buttonState1 = digitalRead(Main);
  if (buttonState1 != oldState1) {
    digitalWrite(Main_led, buttonState1);
    if (buttonState1 == HIGH)
      sendMessage("Main Door is closed");
    else
      sendMessage("Main Door is open");
    oldState1 = buttonState1;
  }

  int buttonState2 = digitalRead(Store);
  if (buttonState2 != oldState2) {
    digitalWrite(Store_led, buttonState2 );
    if (buttonState2 == HIGH)
      sendMessage("Store room is closed");
    else
      sendMessage("Store room is open");
    oldState2 = buttonState2;
  }
}

```

---
Tags: programming, gsm
---


title: How to select arduino 101 in ubuntu?

text:
# Question
Title: How to select arduino 101 in ubuntu?
How to I select arduino 101? I have ubuntu.

# Answer
In that ancient version of the IDE? You don't.

You download and install the latest version of the IDE from the Arduino website, then use the Boards Manager to install the packages that include the Ardiuno 101.
> 1 votes

# Answer
The default serial port it shows up in for me is *ttyACM0*

You can set this as your default port, so when you open the IDE with `sudo arduino`

```
~ $ vim ~/.arduino/preferences.txt

```

change the value for `serial.port`

```
serial.port=ttyACM0

```
> 1 votes

---
Tags: arduino-ide, ubuntu, 101
---


# Question
Title: Enter timing value via keypad for bldc motor spin
I am trying to key in the timing for how long the bldc motor needs to spin via keypad. I hope you can help me with this. I'm using delay() to set the timing of bldc motor spin. How do I key in a series of numbers in seconds, and then put it in the delay()?

The idea for this code is to enter the speed and timing via keypad. After entering the speed and timing, button '#' is used to move the bldc motor according to the speed and timing entered. My question is how do I make my code to compile where speed is keyed in first, timing second then button '#' to run the motor?

Here is my code so far...

```
#include "Keypad.h"
#include "LiquidCrystal.h"
#include "Servo.h"

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

Servo myservo;

const byte ROWS = 4; //four rows
const byte COLS = 3; //four columns
char keys[ROWS][COLS] =
 {{'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
  };
byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5,4,3}; //connect to the column pinouts of the keypad
int count=0;

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

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

  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("S:");
  lcd.setCursor (0,1);
  lcd.print ("T:");

  myservo.attach(11);
}

void loop()
{
    static char buffer[4], spintime[4];
    static byte i = 0, a = 0;
    char key = keypad.getKey();

    // i < 3: prevent buffer overflow
    if  ('0' <= key && key <= '9')   // this is for speed entry
    {
        buffer[i] = key;
        ++i;
        buffer[i] =0;  // null-terminate buffer
        lcd.setCursor (2,0);
        lcd.print(buffer);
    }

     if  ('0' <= key && key <= '9') // this is for timing entry
     {
        spintime[a] = key;
        ++a;
        spintime[a] =0;  // null-terminate buffer
        lcd.setCursor (2,1);
        lcd.print(spintime);
    }
    else if (key == '#')            // this is to run the motor after speed and timing are entered
    {
        int value = atoi(buffer);
        myservo.write(value);       //speed of motor
        int timing = atoi(spintime);
        delay (timing*1000);        // keep the motor spin for ( timing entered) second
        myservo.write(0);
        i = 0;
    }
}

```

# Answer
As I understand it, you want to enter the speed, then the time, then '#'.

Let's imagine you want a speed of 22 and a time of 3. The device will see `2`, `2`, `3`, `#`. How will it know whether you're asking for a speed of 22 and a time of 3, or a speed of 2 and a time of 23? Simple answer: it cannot know. So we need to find a way to tell it.

My suggestion: we'll enter speed followed by `*`, and time followed by `#`. (There are other possible solutions to this.)

We also need to decide the longest number the user can enter, and what happens if they enter a longer one, or if they don't enter one at all? Let's say the longest number is 3 digits, and if they enter a longer one, we will ignore the extra digits. So if they enter `123456789#`, we will register `123#`. (Again, there are other solutions.)

There's some stuff in your code about an LCD, but you don't mention it in the question, so I have ignored it.

Lastly, I am assuming your code to drive the motor and read keys is correct.

Here's some `loop` code which I hope will do the above. It will read numbers until it finds either a `*` or a `#`, convert the number to an integer, and store it as either `time` or `speed`. When it has *both* speed and time, it will spin the motor and reset the values.

```
void loop()
{
    // Where we will store the number as we type it.
    // This buffer is large enough for a 3-digit number, pull a null terminator
    char buffer[4];

    // The speed of the motor
    static int speed = 0;

    // The time to spin for
    static int time = 0;

    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i<3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key || '*' == key)
        {
            // Null terminate
            buffer[i] = 0;

            // Convert to an integer
            int value = atoi(buffer);

            // Set the appropriate value
            if ('#' == key) time = value;
            if ('*' == key) speed = value;
            break;
        }
    }

    // If we have both speed and time...
    if (speed > 0 && time > 0)
    {
        // ...spin the motor at the required speed
        myservo.write(speed);
        // ...and for the required time
        delay(time*1000);
        // ...then stop it
        myservo.write(0);

        // Reset the values for next time
        time = 0;
        speed = 0;
    }
}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to compile a sketch using arduino-builder?
How do you compile a sketch with a custom library path using arduino-builder? The docs are a little light.

I have my source code organized like this:

```
lib
    SomeLib
        somelib.h
        somelib.cpp
src
    otherfile.h
    main.ino

```

I've installed Arduino 1.8.1 into /usr/share/arduino.

I'm trying to compile this for an Arduino Uno from my project root directory with:

```
arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -libraries lib -fqbn arduino:avr:uno -build-path .build src/main.ino

```

But it returns this error:

```
fork/exec {runtime.tools.ctags.path}/ctags: no such file or directory

```

What's causing this error?

# Answer
You need to specify the path to the `tools-builder` folder, which is where `ctags` is. Try this:

```
arduino-builder \
  -compile \
  -hardware /usr/share/arduino/hardware \
  -tools /usr/share/arduino/hardware/tools \
  -tools /usr/share/arduino/tools-builder \
  -libraries lib \
  -fqbn arduino:avr:uno \
  -build-path .build \
  src/main.ino

```
> 4 votes

---
Tags: arduino-builder
---


# Question
Title: Initially my Arduino executes a series of PWM signals simultaneously, but after some iterations it adds around a second between PWM executions
I am using 2 adafruit PWM servo shield in order to generate 25 PWM signals. In particular I am using this shield: https://www.adafruit.com/products/1411

A python script sends the commands to the Arduino (Mega 2560) through pyserial. The commands are like "A0 P1 S500\n". Each argument separated by a space. The first chooses the shield, the second one the pin, and the third one the speed.

The code running in the Arduino is as follows:

```
#include <Adafruit_PWMServoDriver.h>

#define BUFFER_SIZE 200

// Init both adafruit boards
Adafruit_PWMServoDriver pwm0 = Adafruit_PWMServoDriver(0x40);
Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x41);

int read_command(char *buffer)
{

    static int pos = 0;
    int rpos;

    if (Serial.available() > 0) {
        Serial.println(Serial.available());
        char readch = Serial.read();

        switch (readch) {

            case '\n':
                rpos = pos;
                pos = 0; // Reset position index ready for next time
                Serial.println(buffer);
                return rpos;

            default:

                if (pos < BUFFER_SIZE -1) {
                    buffer[pos++] = readch;
                    buffer[pos] = '\0';
                } else {
                    Serial.println("666"); //buffer overflow
                }
        }
    }
    // no end line or char found, return -1
    return -1;

}

void parse_command(char* command)
{

    char* parameter;
    parameter = strtok(command, " ");
    long shield, pin, speed;

    while (parameter != NULL) {

        switch(parameter[0]) {

            case 'A':
                shield = strtol(parameter+1, NULL, 10);
                break;

            case 'P':
                pin = strtol(parameter+1, NULL, 10);
                break;

            case 'S':
                speed = strtol(parameter+1, NULL, 10);
                break;

        }
        parameter = strtok(NULL, " ");
    }

    for (int x=0; x < BUFFER_SIZE; x++)
        command[x] = '\0';

  if (shield == 0)
    pwm0.setPWM(pin, 0, speed);

  if (shield == 1)
    pwm1.setPWM(pin, 0, speed);

}

void setup()
{

  Serial.begin(9600);
  Serial.flush();

  pwm0.begin();
  pwm0.setPWMFreq(100);  //Max is 1600, Kevin was using 1000
  pwm1.begin();
  pwm1.setPWMFreq(100);

}

void loop()
{

  static char buffer[BUFFER_SIZE];

  if (read_command(buffer) > 0)
    parse_command(buffer);

}

```

As said, I am sending the commands from a Python script, where for example I have a function called "activate all", that will send 25 commands like "A0 P1 S500\n" (obviously with different values after the A and the P) to the serial port. I also have a function called "disable all", which is very similar to the previous command, but setting the S to 0 so like "A0 P1 S0\n".

So, as I start the serial communication, if I execute from Python "activate\_all", I can how all the PWM signals are generated at the same time. I know it is actually 1 by 1, but it is fast enough to seem simultaneously to the human eye. If I then send a disable\_all, I can see how all the PWM signals are set to 0 at the same time.

This works as expected for a while, but after some point, when I send an activate\_all, it will indeed activate all of them, but it activates each PWM signal one by one, with a delay of around 1 second between activations (so you can clearly see them going one by one), and a very similar effect when disabling them all. From this point on, which seems slightly different each time, every time I want to activate more than one pwm signal at the same time, it will add this 1s delay between activations.

The only way I have to fix this is to send from the python a "flush()". which seems to be fix it. Doing flushes from the Arduino code, like when for example serial.available is 0, doesnt seem to fix it.

I don't know what exactly I am doing wrong. I guess the way I am handling the communication buffer is wrong, but I haven't seen where my mistake is.

A very similar code to the one pasted here was used in another project, in that case it was interfaced with Labview, and in that case everything seem fine.

In case you wonder about the code running in the Python script, it is like this:

```
import serial, time, json

class BZBoard:

    def __init__(self, port):

        self.ser = serial.Serial(port, 9600, timeout=120)
        time.sleep(2) # serial docs recommend a wait just after connection
        self.ser.flush(); self.ser.flushInput(); self.ser.flushOutput();

        self.motors = {
            just naming the pins
            }

    def __del__(self):

        self.disable_all()
        self.ser.close()
        del self.ser

    def close(self):

        self.disable_all()
        self.ser.close()
        del self.ser

    def activate_motor(self, motor_code, speed=300):
        ''' code as in A1 or C2 as marked in the actual board. See the dict motors'''

        shield, pin = self.motors[motor_code]
        command = "A%d P%d S%d\n" % ( shield, pin, speed )
        self.ser.write(command.encode())

    def activate_all(self, speed=300):

        for key in self.motors.keys():
            self.activate_motor(key, speed)

    def disable_motor(self, motor_code):

        shield, pin = self.motors[motor_code]
        command = "A%d P%d S0\n" % ( shield, pin )
        self.ser.write(command.encode())

    def disable_all(self):

        for key in self.motors.keys():
            self.disable_motor(key)

if __name__ == "__main__":

    board = BZBoard("/dev/ttyACM0")

```

So the user will do for example a lopp that repeats itself 20 times, where it will activate\_all, wait 1 second, disable\_all, wait 1 second. The first 10 iterations or so, everything will be fine and the PWM are generated all of them at the same time (with respect to the human eye), but after that, the PWM signals are generated 1 by 1, with a delay of 1s or so between them.

# Answer
> 1 votes
There seems to be reason to think about filled buffers causing stalls and timeouts, but comments regarding 5-second sleeps between trials seem to rule that out. To debug what's actually happening, you might blink an LED each time you receive a character, and another LED each time you call your `parse_command()` routine; and if you have an oscilloscope, look at the serial transmissions back and forth to see whether delay is due to something at the Arduino end vs at the host end.

That said, I think it would make sense to simplify the protocol by getting rid of your input buffer and just processing input as it comes. For example, you could use the following letters as post-fix actions.

```
A  Select shield 1
B  Select shield 2
P  Set pin number, eg 11P selects pin 11
S  Set speed, eg 472S sets speed to 472
N  Send current speed to current pin, then increment pin number

```

For example, the command sequence for “disable\_all” could look like:

```
0S0PANNNNNNNNNNNN 0PBNNNNNNNNNNNNN

```

This is easy to parse on the fly; declare `int val=0` and any other needed variables before `loop()`, then within `loop()` say:

```
  char inc;   // For incoming character
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        board = 0;
        break;
      case 'B':
        board = 1;
        break;
      case 'P':
        pin = val;
        break;
      case 'S':
        speed = val;
        break;
      case 'N':
        if (PinNumberIsOk(board, pin))
          pwm[board].setPWM(pin, 0, speed);
        ++pin;
        break;
      default :
        ; // handle blanks, returns, whatever
      }
      val = 0;  // Set val to zero on any non-digit
    }

```

As another example, the sequence `4PA 11SN13SN17SN` would send speeds 11, 13, and 17, respectively, to motors 4, 5, 6 on the first shield.

---
Tags: serial, pwm, adafruit, python
---


# Question
Title: Receiving SMS by Arduino GSM Shield and control the LED with the content of this SMS?
I am using Arduino GSM Shield receiving SMS from an Android app. And the content of this SMS will control a LED. If the content of this SMS is not "off", the LED will be on and the content will be printed in the serial monitor. But if it is "off", the LED will be off immediately. Besides, the LED will keep being on until the "off" message coming. For now, I used the code from the example of the software. But I cannot use the content of this SMS to control the status of LED. With the code below, the LED could not be turned on and the content could not be displayed on the monitor. I think it was because the sketch failed to get the whole content of this SMS. Could anybody tell me how to solve this problem? Thanks.

```
#include <GSM.h>
GSM gsmAccess;
GSM_SMS sms;
char senderNumber[20];
int led=13;
void setup()
{
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  digitalWrite(led,LOW);
  while (!Serial) {
    ;
  }
  Serial.println("SMS Messages Receiver");
  boolean notConnected = true;
  while(notConnected)
    {
      if(gsmAccess.begin("6442")==GSM_READY)
        notConnected = false;
      else
        {
          Serial.println("Not connected");
          delay(1000);
        }
    }
  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop()
{
  char c;
  int val=0;
  val=digitalRead(led);
  if (val==HIGH){
    digitalWrite(led,HIGH);
  }
  if (sms.available()){
    Serial.println("Message received from:");
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);

    if(sms.peek()=='#')
      {
        Serial.println("Discarded SMS");
        sms.flush();
      }
    while(c=sms.read())
      if(c='off'){
        digitalWrite(led,LOW);
      }else{
        digitalWrite(led,HIGH);
        Serial.print(c);
      }
    Serial.println("\nEND OF MESSAGE");
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }
  delay(1000);
}

```

# Answer
First of all, you have a typo: You need the double-equals operator in

```
if (c == 'off') {

```

But more importantly, you can't use a `char` variable to hold or compare more than one character at a time. I don't know the details of the Arduino GSM library, but if `sms.read()` returns a string, then you'll need a string variable or an array of `char` to hold the result.
> 4 votes

# Answer
`sms.read()` function returns only a single byte of the SMS string. You can store the whole data in a character array and process it later like following:

```
char c, message[140];
int i=0;
while (c = sms.read()) {
    message[i++] = c;
}
if (strstr (message, "off")) {    //If SMS contains off anywhere
    digitalWrite(led,LOW);
} else {
    digitalWrite(led,HIGH);
    Serial.print(message);
}

```

And I believe the following portion in your code is not required as it is doing nothing:

```
val=digitalRead(led);
if (val==HIGH){
    digitalWrite(led,HIGH);
}

```
> 1 votes

---
Tags: led, gsm
---


# Question
Title: How to connect ESP8266 12e directly to Arduino Uno (without shields)
I have an ESP8266 12E module and I'm trying to connect it to arduino, without any shields or whatsoever. I've looked everywhere but all I can find is about ESP-01 or with a NodeMCU. I'd like to do the bridge manually, but I don't know which pins I should ground and which pins I should power.

This is my current setup:

And the following sketch:

```
#include <SoftwareSerial.h>

//RX pin 2, TX pin 3
SoftwareSerial esp8266(2, 3);

#define DEBUG true

void setup() {
  Serial.begin(9600);
  esp8266.begin(115200);
  sendData("AT\r\n", 2000, DEBUG);
  delay(1000);
  Serial.println("Firmware version:");
  delay(3000);
  sendData("AT+GMR\r\n", 2000, DEBUG);
  Serial.println("** End **");
}

void loop() {}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }
  if (debug)
  {
    Serial.print(response);
  }
  return response;
}

```

When run, I get the following output:

```
Firmware version:
** End **

```

On the module, the led flashes when I power it up, but after that it remains off. I've already tested the voltage regulator with ReadAnalogVoltage, and the output was 3.33v, so it is working.

# Answer
Make sure to specify as SoftwareSerial's Rx pin, the pin# connected to the ESP's Tx pin. They have to be crossed. (I just fumbled that myself, a couple of hours ago ):

It is the ESP's Rx pin that needs the voltage divider.

Also pullup the ESP's reset pin.

Update:

ESP-01 and ESP-12 modules use the same ESP8266 chip. The differences are in the number of pins brought out from the chip and made available on the board. Other differences include the firmware interpreters installed on them before shipment: "NodeMCU" is one. ESP-01 is usually shipped with the AT+ command interpreter unless it specified otherwise; I would expect the same for the others. Bottom line is they are connected pretty much alike. Interacting with them serially from an Arduino (or other device) then depends on the installed firmware, including whether you've installed your own. So far, I've used all of mine as WiFi modules using the AT+ interpreter they came with.

> How can I pullup the reset pin? Also do I need to pullup it just for initial setup (changing baud rate and such) or should it be pulled up at all times?

I use a 10K-Ohm resistor to +3.3v as a pullup. You need it pulled up anytime you are not trying to force a hardware reset; grounding it resets the chip. I have never used a reset button on my ESPs. I just leave them pulled up. If you want one, it should short the reset pin to ground.

Update 2 (wiring):

You've powered the ESP with 3v but your pullups are taken to the Arduino's 3.3v supply. Most chips have a slim tolerance for signal levels above their supply voltage. I'd suggest driving the entire ESP from your 3v battery - power & both pullups.

I don't know the ESP-12E's pinouts to check them; I'm sure you have, and you might want to label the diagram so someone else can look over it too.

Then there's whatever "chicken dance" is needed on the reset and the GPIO line that needs to get toggled to start an upload. I don't know that sequence, but I think you need a grounding buttons on on each one to be able to sequence them.
> 2 votes

# Answer
Oh boy, lot of things can be the problem here.

First of all: a voltage divider using 10k-10k has an output of 2.5V when the source is 5V. The ESPs run on 3.3V, so this effectively could mean the commands are completely scrambled when they arrive at the ESP.

The other way around and you're putting 3.3V comms into a 5V device. This isn't a problem per say, but it could definitely lead to problems. I suggest you use a bi-directional logic level converter which will transform a 5V command to the 3.3V ESP level, and back.

Your wiring between the Arduino and the ESP seems al right, but make sure TX~RX and RX~TX are connected, not TX~TX and RX~RX, but as I said above: use a bi-directional logic level converter.
> 1 votes

# Answer
From your code, I understand that you're setting the baud rate of the software serial pins as 115200. Software serial doesn't support speeds this high. You could set the baud rate of ESP8266 down to 9600 by using a USB to TTL converter and the AT command interface. Then you should try repeating this process using a baud rate of 9600 for the software serial. Or if you happen to have an Arduino Mega which comes with 4 serial ports, you can use the hardware serial pins which supports high speeds.
> 1 votes

---
Tags: esp8266
---


title: Arduino + DS18B20 array

text:
# Question
Title: Arduino + DS18B20 array
I want to connect 24 DS18B20 sensors to arduino by onewire library in the same digital pin .

Can anyone post an example code ?

Thanks

# Answer
> 2 votes
Use the OneWire and the DallasTemperature libraries. They are both in the Arduino IDE in the Library Manager.

The DallasTemperature library has the example "Multiple". You need to make an array of DeviceAddress.

To tell them apart, you have to label each temperature sensor with its device address (a unique identifier inside each DS18B20). Therefor you have to connect them one-by-one and write down the device address.

Start with one sensor, and if that works, try to make arrays.

For 24 temperature sensors, you need a lot of wires. That could make it less reliable. You can use two or three or more pins as well. Then you have to create more than one "OneWire" bus in the sketch.

There are many examples for multiple DS18B20 sensors. For example this one is with an array: Arduino forum: "multiple temp sensors ds18b20".

---
Tags: arduino-ide, ds18b20
---


# Question
Title: Arduino randomly does incorrect addition
I've been trying to make an accelerometer calibration tool for my Arduino Nano and MPU6050, but the arduino seems to randomly do incorrect addition. If you look at the output of the console, it works fine for the first 4 iterations, then on the fifth, decides that -31904+-7964 is equal to 25668. It is supposed to be -39868. It does this every time I run it, usually between the 3rd to 6th iteration, but with different numbers.

```
bool calix = true; //X calibrated or not
      while(calix)
      {
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("PrevAvgX: "); Serial.println(axo/i);
        Serial.print("Axo: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        axo = (float)ax + (float)axo;
        i += 1;
        Serial.print("Axo2: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        float cax = axo/i; //Current Average (x)
        Serial.print("AverageX: "); Serial.println(cax);
        delay(100);
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("NewX: "); Serial.println(ax);
        float offsettocurrent = ax-(axo/i);
        Serial.print("AverageX-RawX: "); Serial.println(offsettocurrent);
        if(offsettocurrent>5 or offsettocurrent<-5)
        {
          Serial.println("Offset not accurate enough. Continuing.");
        }
        else
        {
          Serial.println("Offset accurate enough. Finishing calibration");
          break;
        }
        delay(100);
      }

```

Serial console output:

```
Initializing I2C devices...
Testing device connections...
Connected to MPU6050
Attempting full calibration
PrevAvgX: -1
Axo: 0
RawX: -8048
Axo2: -8048
RawX: -8048
AverageX: -8048.00
NewX: -8028
AverageX-RawX: 20.00
Offset not accurate enough. Continuing.
PrevAvgX: -8048
Axo: -8048
RawX: -7940
Axo2: -15988
RawX: -7940
AverageX: -7994.00
NewX: -7964
AverageX-RawX: 30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7994
Axo: -15988
RawX: -7972
Axo2: -23960
RawX: -7972
AverageX: -7986.00
NewX: -8016
AverageX-RawX: -30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7986
Axo: -23960
RawX: -7944
Axo2: -31904
RawX: -7944
AverageX: -7976.00
NewX: -8016
AverageX-RawX: -40.00
Offset not accurate enough. Continuing.
PrevAvgX: -7976
Axo: -31904
RawX: -7964
Axo2: 25668
RawX: -7964
AverageX: 5133.00
NewX: -7944
AverageX-RawX: -13077.00
Offset not accurate enough. Continuing.

```

# Answer
`int` only goes from `-32768` to `32768`, and rolls-over, as you've seen. Use a `long` data type instead and you can go MUCH further from zero. Use `double` instead of `float` likewise, when you need more room. Be aware however that larger types use more RAM, and in the case of `double`, execute a bit slower as well.
> 2 votes

---
Tags: arduino-nano, mpu6050, mathematics
---


# Question
Title: Arduino Nano memory issue. SD card and LCD screen together
When i am uploading my code to `arduino nano`, i am getting message about high dynamic memory usage (87%):

```
Sketch uses 17,628 bytes (57%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,751 bytes (85%) of dynamic memory, leaving 297 bytes for local variables. Maximum is 2,048 bytes.
Low memory available, stability problems may occur.

```

But despite this, its uploading to my `arduino nano` and everything works fine without action method's code. How to use code (code to work with LCD) wich is located in `action()` method. If i use hidden code, im getting message `error opening test.txt` (not enough memory). But if code which is controls LCD screen is annotated then `SD` card works fine.

If i use this code, i'm getting problem with SD card. But i can still use LCD and SD on same arduino board separately without any problems, but if i try to combine it, im getting some problems with SD card reading.

```
void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

```

All code:

```
#include <Wire.h>
#include <Adafruit_SSD1306.h>

#include <SPI.h>
#include <SD.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

int count_iterations = 0;

#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

File myFile;

void setup() {

  /// SD START
  // Open serial communications and wait for port to open:
  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!");
    return;
  }
  Serial.println("initialization done.");
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
  //// SD END
}

void loop() {
  sensorValue = analogRead(analogInPin);
  if (sensorValue < 1000) {
    action();
  }
}

void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

```

# Answer
Your code is using in the neighborhood of 150 bytes for text-strings in RAM, much of which can be moved to PROGMEM quite easily. For example, replace

```
Serial.print("Initializing SD card...");

```

by

```
Serial.print(F("Initializing SD card..."));

```

Changes like that to `Serial.print()` arguments should free up about 140 bytes of RAM. To free up another 8 bytes, instead of `SD.open("test.txt" ...)`, write `SD.open(FileName ...)` with `FileName` previously declared via `char *FileName = "test.txt";` so that the text `test.txt` appears in RAM once instead of twice.

In short, if 150 bytes will make the difference, that much memory reduction is easy.

---

I briefly examined the source code behind the `Adafruit_SSD1306.h` and `SD.h` headers, to see if they use some large arrays in RAM, such as 512 bytes of sector data, or some hundreds of bytes for frame buffers.

Ordinarily, such arrays are difficult to get rid of without a rewrite from scratch or without major loss of functionality. For most one-off projects, the effort involved isn't worthwhile: one can instead use an Arduino Mega2560 system, which has 8 KB of RAM, vs the Arduino Nano's 2KB RAM; or can use an Arduino Due with 96KB RAM; or a Teensy, with 8, 16, or 64KB RAM.

However, if you plan a production run and are trying to hold down costs by using Nanos, consider the following approach: Carefully arrange the processing so that you are done with SD buffers before needing a display frame buffer; and revise the libraries so the SD buffer and frame buffer overlap. That is, place the smaller buffer within the same region of memory holding the larger buffer. If processing can't be neatly separated, blank the display while using the shared buffer area for accessing SD data.

\[Note, I edited this answer and expanded discussion of buffers in the libraries.\]
> 1 votes

---
Tags: arduino-nano, memory-usage, memory
---


# Question
Title: In line following robot do this code work perfectly as iam unclear about the right and left moving programing lines
```
    #define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
#define LM1 4       // left motor
#define LM2 5       // left motor
#define RM1 6       // right motor
#define RM2 7       // right motor

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && !(digitalRead(RS)))     // stop
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }
}

```

i got this code from a site.My doubt is if the left sensor is not reading means it has value of zero hence it is on black line and the right sensor is on white line.Then it should move to left side itself.BUt the program says it should moves to right.Iam a beginner.Please help me to clear my doubt

# Answer
> 1 votes
This depends on how the sensors are arranged. However, assuming they are setup like eyes on our heads, then the code would be correct.

If the left sensor does not see the line, but the right sensor does, then that means the line is on the right side of the robot, and thus turning to the right would bring the line back into view of the left sensor.

---
Tags: arduino-uno
---


# Question
Title: Problem in getting the output (language: Processing and Arduino IDE)
I am working on a small project with Processing and Arduino, in which, depending upon the value of a photoresistor, it displays whether it is day/night/evening.

I read the value from the photoresistor and write the value to the serial port. Then in Processing I read the value from the serial port and display depending on the value.

But I get a very flickery output, and there is always a -1 imprinted on the screen as shown in the video.

Please help me out.

link to the video

**Code for Arduino:**

```
int ldr1 = A0;
int x,y;

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

void loop() {
  x = analogRead(ldr1);
  Serial.write(x);
  delay(100);
}

```

**Code for Processing:**

```
import processing.serial.*;
Serial port;
int x,y;

void setup() {
  size(640, 320);
  port = new Serial(this, "COM3", 9600);
}

void draw() {
  background(0);
  x = port.read();
  text(x,100,100);
  if(x < 400 && x > 200) {
    textSize(32);
    fill(0,0,255);
    text("it is evening",200,200);
  }
  if(x < 200 && x > 20) {
    textSize(32);
    fill(0,255,0);
    text("it is night",200,200);
  }
  if(x > 400 && x < 900) {
    textSize(32);
    fill(255,0,0);
    text("it is morning",200,200);
  }
}

```

# Answer
If you read the documentation for Serial::read() at https://processing.org/reference/libraries/serial/Serial\_read\_.html

it says:
*"Returns a number **between 0 and 255** for the next byte that's waiting in the buffer. **Returns -1 if there is no byte,** although this should be avoided by first cheacking available() to see if data is available."*

Either before calling "Draw" function, or inside "Draw", you should first check:

```
if(port.available()){
  //do your checking for X value and set text as you are doing before

}

```

IMPORTANT - you are only ever sending the lower byte (values 0-255) from Arduino when you do Serial.write(x). That is only 1 byte. The "int" return from an analogue read is 10 bits, and needs 2 bytes to store the information from 0-1023.

You should use the Arduino function Map() to scale it down from 0-1023 to 0-255. It looks like your application should be okay with this, in terms of resolution.

```
  int val = analogRead(ldr1);
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val); //now you will not lose information

```

On the Processing side, you would then look at values from 0-255 to determine daylight/times of day.
> 1 votes

---
Tags: processing-lang
---