title: Change values of timer using I2C

text:
# Question
Title: Change values of timer using I2C
I'd like to alter the "LED\_T\_ON" values using an I2C enabled device (i.e. RPi)

Code for Arduino Mega slave:

```
//slave

#include <Wire.h>

#define SLAVE_ADDRESS 0x08

const int PWR_LED = 43;
int LED_TinH_ON = 18;
int LED_T_ON = 5000;
int LED_T_OFF = 5000;

String inString = "";    // string to hold input
byte LastMasterCommand = 0;
int Mval;

char user_input;

class Relay {
  int relayPin;
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int relayState;                 // pumpState used to set the PUMP
  unsigned long previousMillis;   // will store last time PUMP was updated

  // Constructor - creates a Timer and initializes the member variables and state
  public:
  Relay(int pin, long on, long off)
  {
    relayPin = pin;
    pinMode(relayPin, OUTPUT);

    OnTime = on;
    OffTime = off;

    relayState = LOW;
    previousMillis = 0;  //ORIGINALLY 0
  }

  void Update()
  {
    // check to see if it's time to change the state of the TIMER
    unsigned long currentMillis = millis();

    if((relayState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      relayState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(relayPin, relayState);  // Update the actual LED
    }
    else if ((relayState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      relayState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(relayPin, relayState);   // Update the actual RELAY
    }
  }
};

Relay relay3(PWR_LED, LED_T_OFF, LED_T_ON);

void setup() {
 // initialize serial communication with computer:
  Serial.begin(9600);

  Wire.begin(SLAVE_ADDRESS);

  Wire.onReceive(receiveData);
  Wire.onRequest(slavesRespond);

  pinMode(PWR_LED, OUTPUT);
}

void loop() {
  delay(1000);

  Serial.print("LED_T_ON=");
  Serial.println(LED_T_ON);
  Serial.print("LED_T_OFF=");
  Serial.println(LED_T_OFF);
  Serial.println();

  relay3.Update();

  switch (Mval) {
    case 1 ... 25:
      LED_TinH_ON = Mval;
      Serial.print("LED time on: ");
      Serial.print(LED_TinH_ON);
      Serial.println("h");
      LED_T_ON = LED_TinH_ON*1000;//*60*60;
      LED_T_OFF = (24-LED_TinH_ON)*1000;//*60*60;
    break;
  }
}

void receiveData(int byteCount) {
  LastMasterCommand = Wire.read();
  while (Wire.available()) {
    int msg = Wire.read();

    if (isDigit(msg)) {
      inString += (char)msg;
    }
  }
  Mval = inString.toInt();
  //Serial.println(LastMasterCommand);
  inString = "";
  //Serial.println(Mval);
}

void slavesRespond() {
}

```

When I change the value on the RPi the Arduino receives and displays the correct value but the timed relays don't actually use the updated values.

Am I missing something?

# Answer
> 2 votes
Your updating `LED_T_ON` and `LED_T_OFF` but those values were already passed into the constructor and changing them will not change the object. you need to update `relay3.OnTime` and `relay3.OffTime`

---
Tags: arduino-mega, i2c
---


# Question
Title: Binary addressing and coding to control a 96 input mux matrix
I’m trying to wrap my head around using binary addresses in a mux. Failing miserably. For the circuit I have six 16 channel analog multiplexers CD74HC4067 as slaves to an eight channel multiplexor CD54HC4051 master. They are bringing in 96 sensor readings (IR receiver diodes through Op Amps) into an array that, in turn, is used to constantly update lotsa LEDs through a series of shift registers (TLC5940) using the Arduino TLC5940 Library.

I’ve included the possible wiring scheme that the code is trying to control. It probably needs work too.

Question: I’ve seen, and SEMI-understand matrixes that address 32 inputs (4 x 8 bits) but not quite understanding how I can address the six mux chips with 96 inputs. Or if I can even do it this way. Example from this forum: How to code for cascading multiplexers? Is it possible with this matrix of 96 inputs, and how? Am I barking up the wrong tree?

Code so far:

```
    #include <Tlc5940.h> //Arduino TLC5940 Library controls the individual LEDs - "Pixels"

int ledCount = 96; //change  LED "PIXEL" count in matrix...also number of IR sensor inputs

int thresh = 10; //value for usable distance reading from IR

// main structures to hold LED Pixel array on/off state, IR reciever readings
byte dsply_state[ledCount];    //pixel on-off grid, need for tlc5940
uint_16  recv_state[ledCount];           // IR Readings - FROM mux set-up

// Master IR -mux sensor pins for Arduino Pro MINI
#define  M_S0 2
#define  M_S1 4
#define  M_S2 5
// Slave IR mux sensor pins
#define  S_S0 6
#define  S_S1 7
#define  S_S2 8
#define  S_S3 12

//  ANALOG PIN :
#define  InputFromMux A0

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

    //tlc5940 Arduino library
    Tlc.init(0);

    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(S_S3, OUTPUT);
    pinMode(InputFromMux, INPUT);

}

void loop() {
    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER and SLAVES.

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

    digitalWrite(M_S2, i & 0b1000000);
    digitalWrite(M_S1, i & 0b0100000);
    digitalWrite(M_S0, i & 0b0010000);
    digitalWrite(S_S3, i & 0b0001000);
    digitalWrite(S_S2, i & 0b0000100);
    digitalWrite(S_S1, i & 0b0000010);
    digitalWrite(S_S0, i & 0b0000001);

    delay(2);

    //edited as per @Gerben. thanks so much

    //get an individual sensor reading from IR receiver/opAmp mux, store it in a variable
     int IRstate = analogRead(InputFromMux);

    //populate receiving array with a reading
     recv_state[i] = IRstate;

    //populate display array for tlc5940 to push out
     dsply_state[i] = recv_state[i];

} //end for(i...) loop

      //run through display state array to check if the stored reading is greater than a threshold number
      //if yes, then turn on the "pixel". If not, set it to zero
      //

       for (int x = 0; x < ledCount; x++)
          if (dsply_state[x] >= thresh ) {

               Tlc.set(dsply_state[x], 4000);

             //or if reading from mux is zero
          } else if (dsply_state[x] < thresh) {

              Tlc.set(dsply_state[x], 0);
              }

            //tlc5940 Arduino library - update() clocks the chips
            // move update(); outside the for(x...) loop for speed?
        Tlc.update();
        delay(10);

      } //end For(x..) Loop

}//endMainLoop

```

# Answer
> 1 votes
OK. First, how the multiplexer works. I have a page about multiplexers in which there is this example of the 74HC4051:

Depending on the "binary" input to A/B/C (shown as S0/S1/S2 on your schematic) there is a low resistance path between one of the 8 inputs and the single output. The CD74HC4067 works in a similar way, except it switches 16 inputs.

So, if you set up the binary number 2 (010) in A/B/C then the third input is selected (number 02 because it is zero-relative).

In your schematic you have 6 x CD74HC4067 which therefore can have 16 x 6 inputs (96 inputs in total). The outputs of those 6 are fed into the 54HC4051 (2 aren't used) so therefore the 54HC4051 can select which of the 6 16-input chips it is interested in right now, by setting up a number between 0 and 5 on the 8-input multiplexer.

The four binary inputs to the 6 x CD74HC4067 are all tied together as you can see on the schematic.

Thus your method would be:

* Loop from 0 to 5 on the master multiplexer (the 54HC4051). This selects which of the 6 16-input multiplexers you are interested in right now.
* For each of those, loop through 0 to 15 on S0/S1/S2/S3 so that the currently-selected CD74HC4067 routes its input through to its output.
* Read the resulting value

Those two loops will give you 96 inputs, which is what you are trying to read.

This technique takes 7 output pins to output the binary numbers (3 bits plus 4 bits). It also needs one input pin to read the result.

---

Judging by the schematic it uses SPI (serial data) to control the 6 x TLC5940 shift registers which lets it turn LEDs on and off with only two control pins (SCK and MOSI named SCLK and SOUT on your schematic).

The chips are daisy-chained together so all of those TLC5940s are controlled by those two pins.

This fairly minimalist design has therefore left some spare pins on the Arduino Pro.

---

> Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern?

I know you changed the question by the time I saw this, but the code below illustrates what I mean by the two loops:

```
const int MUX_CHIPS = 6;
const int LEDS_PER_CHIP = 16;
const int TOTAL_IR_INPUTS = MUX_CHIPS * LEDS_PER_CHIP;
// Master IR -mux sensor pins for Arduino Pro MINI
const byte  M_S0 = 2;
const byte  M_S1 = 4;
const byte  M_S2 = 5;
// Slave IR mux sensor pins
const byte  S_S0 = 6;
const byte  S_S1 = 7;
const byte  S_S2 = 8;
const byte  S_S3 = 12;
//  ANALOG PIN :
const byte INPUT_FROM_MUX = A0;

int  recv_state[TOTAL_IR_INPUTS];           // IR Readings - FROM mux set-up

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

    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(S_S3, OUTPUT);
    pinMode(INPUT_FROM_MUX, INPUT);

    // set ADC prescaler of 32
    ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
    ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
} // end of setup

void loop() {

  unsigned long start = micros ();

  // read from IR diodes

  int whichLED = 0;
  for (byte master = 0; master < MUX_CHIPS; master++)
    {
    // select appropriate slave on the master MUX
    digitalWrite(M_S2, (master & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master & 0b001) ? HIGH : LOW);

    // take each slave reading
    for (byte slave = 0; slave < LEDS_PER_CHIP; slave++)
      {
      digitalWrite(S_S3, (slave & 0b1000) ? HIGH : LOW);
      digitalWrite(S_S2, (slave & 0b0100) ? HIGH : LOW);
      digitalWrite(S_S1, (slave & 0b0010) ? HIGH : LOW);
      digitalWrite(S_S0, (slave & 0b0001) ? HIGH : LOW);

      // store this reading
      recv_state [whichLED++] = analogRead (INPUT_FROM_MUX);

      } // end of for each slave
    } // end of for each master

  // display results here ...

} // of loop

```

The exact code above took 5148 µs (around 5 ms) to execute the loop once on my Uno. If we remove the speedup of the ADC (analogRead) it takes 13252 µs (13 ms).

To allow for your exact wiring you need to ignore the low-order bit on the master MUX because you are not using input A0\_13 in which case you need to add 2 to the master value in the outer loop:

```
    // select appropriate slave on the master MUX
    byte master_plus_2 = master + 2;  // allow for not using input A0
    digitalWrite(M_S2, (master_plus_2 & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master_plus_2 & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master_plus_2 & 0b001) ? HIGH : LOW);

```

---
Tags: sensors, led, input, multiplexer
---


title: I2C Read Operation in TCA9539

text:
# Question
Title: I2C Read Operation in TCA9539
I am using this TI device TCA9539 (http://www.ti.com/lit/ds/symlink/tca9539.pdf) with the pins A1 and A0 tied to ground resulting the write address to 0x74.

I don't have any issues writing to this device address and perform the necessary functions, however when I try to read registers using Arduino read functions, getting NACK there. Is 0x75 correct read address?

For second question:

Based on the device spec for read operation:

> Reading from a slave is very similar to writing, but requires some additional steps. In order to read from a slave, the master must first instruct the slave which register it wishes to read from. This is done by the master starting off the transmission in a similar fashion as the write, by sending the address with the R/W bit equal to 0 (signifying a write), followed by the register address it wishes to read from. When the slave acknowledges this register address, the master sends a START condition again, followed by the slave address with the R/W bit set to 1 (signifying a read). This time, the slave acknowledges the read request, and the master releases the SDA bus but continues supplying the clock to the slave. During this part of the transaction, the master becomes the master-receiver, and the slave becomes the slave-transmitter. The master continues to send out the clock pulses, but releases the SDA line so that the slave can transmit data. At the end of every byte of data, the master sends an ACK to the slave, letting the slave know that it is ready for more data. When the master has received the number of bytes it is expecting, it sends a NACK, signaling to the slave to halt communications and release the bus. The master follows this up with a STOP condition."

This is the code I am trying to use,

```
Wire.begin();
Wire.beginTransmission(0x74); // start i2c transmission as write addr
Wire.write(0x01)              // the register i need to read from
Wire.beginTransmission(0x75); // start i2c transmission as read addr given

```

I believe the device I2C read and arduino library functions for read is not making sense to me. Has anyone used this device for read?

# Answer
You have misunderstood, how the `Wire` library works. It is doing all the things with the direction bit for you.

**Write Operation:**

* `Wire.beginTransmission()` takes a 7-bit address as a parameter. The direction bit is automatically and internally set to write operation.
* `Wire.write()` writes a value to the library-internal buffer, but is not doing anything on the actual I2C bus
* Finally you call `Wire.endTransmission()` to finally do the write operation on the actual I2C bus. Prior to this function call the library doesn't do anything on the bus. So you have to call it, so that the data can reach the slave device

**Read Operation:**

* For reading from a slave device there is an extra function: `Wire.requestFrom()`. It takes the (7-bit) address and the number of requested bytes as parameters and it returns the number of bytes, that were actually read from the slave device (is important if the slave is sending less data, than requested). After a call to this function, the read bytes are now lying in the library-internal buffer.
* To get the received bytes from the library-internal buffer, you have to use `Wire.read()`. Again it does not do anything on the I2C bus. It just reads from the internal buffer.

---

So for your code you need to send a command byte to the slave, that says, what registers of the slave (determinded by the lowest three bytes, as the datasheet says) you want to access next. After that you can either send more bytes (in order to write the chosen registers) or you can start a request, so that the slave will send you the current state of the selected register.

Look at this images from pages 23 and 24 of the datasheet:

These are showing exactly, what you have to send. Note that the address byte is automatically send by the `Wire` library, so you don't have to do it. I will put it in code for you:

**Write operation:**

```
Wire.begin();
Wire.beginTransmission(slave_address);
Wire.write(register_address);
Wire.write(new_register_data);
Wire.endTransmission();

```

The register address is documented in the datasheet. In this case it is the register with address 0x01 (Though this makes no sense, since this is a read-only register).

**Read operation**

```
Wire.begin();
Wire.beginTransmission(slave_address);
Wire.write(register_address);
Wire.endTransmission();
if(Wire.requestFrom(slave_address,1) > 0 ){
    byte data = Wire.read();
}

```

Here we first do a write operation to tell the slave, what register we want to access. Then we request the data in this register with `Wire.requestFrom()`. To transfer from the internal buffer to our program is done with the `Wire.read()` function (but only, if there was actually something received).

---

For the address of the slave device: This depends on how you have set the pins A0 and A1. You can find a table with the corresponding addresses at page 21 of the datasheet. Note that these are NOT including the data direction bit. When you are using the `Wire` library, you don't have to bother about it.
> 0 votes

# Answer
The arduino i2c libraries expect a 7 bit slave address, not 8 bit address + r/w bit, and will manage the read write bit internally based on if you do a write or read.

So begin transmission 0x74

Write 0x01

End transmission

Begin transmission 0x74

Read n

End transmission
> 1 votes

---
Tags: i2c
---


# Question
Title: How to connect Arduino Nano with ESP8266 and BMP180?
I have an issue with my application.

**Hardware used:**

* ESP8266 Serial Wi-Fi Wireless Transceiver Module for IOT
* Robodyn Micro USB Compatible for Arduino Nano V3.0 ATmega168 CH340G
* SENSOR: BMP180

**Connections:**

* Arduino Nano to ESP8266
* CH-PD to Vcc
* GPIO0 to GND
* Rx to Rx
* Tx to Tx
* 3.3v to 3.3v
* Reset to GND
* GND to GND

**Arduino Nano to BMP180**

* 3.3v to VIN
* GND to GND
* A5 to SCL
* A4 to SDA

Sketch used (uploaded in Generic ESP8266 Board):

```
#include <DHT.h> //  DHT.h library
#include <ESP8266WiFi.h> // ESP8266WiFi.h library
#include <SFE_BMP180.h>
#include <Wire.h>

SFE_BMP180 pressure;

const char* ssid     = "GOPI-LAPTOP";
const char* password = "kcejava123";
const char* host = "api.thingspeak.com";
const char* writeAPIKey = "CQSHDFP4EZFCDWKO";

void setup() {
  // Initialize sensor
  Serial.begin(9600);
  delay(1000);
  if (pressure.begin())
    Serial.println("BMP180 init success");
  else {
    Serial.println("BMP180 init fail\n\n");
  }
  //  Connect to WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void loop() {
  char status;
  double T, P, p0, a;
  status = pressure.startTemperature();
  if (status != 0) {
    // Wait for the measurement to complete:
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("temperature: ");
      Serial.print(T,2);
      Serial.print(" deg C, ");
      Serial.print((9.0/5.0)*T+32.0,2);
      Serial.println(" deg F");
    } else
      Serial.println("error retrieving pressure measurement\n");
  }
  status = pressure.startPressure(3);
  if (status != 0) {
    delay(status);
    status = pressure.getPressure(P, T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("absolute pressure: ");
      Serial.print(P, 2);
      Serial.print(" mb, ");
      Serial.print(P*0.0295333727, 2);
      Serial.println(" inHg");
      p0 = 1013.25; // we're at 1655 meters (Boulder, CO)
      Serial.print("relative (sea-level) pressure: ");
      Serial.print(p0, 2);
      Serial.print(" mb, ");
      Serial.print(p0*0.0295333727, 2);
      Serial.println(" inHg");
      a = pressure.altitude(P, p0);
      Serial.print("computed altitude: ");
      Serial.print(a, 0);
      Serial.print(" meters, ");
      Serial.print(a*3.28084, 0);
      Serial.println(" feet");
    }
  }
  // make TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    return;
  }
  String url = "/update?key=";
  url+=writeAPIKey;
  url+="&field1=";
  url+=String(T);
  url+="&field2=";
  url+=String(P);
  url+="\r\n";
  // Request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  Serial.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  delay(30000);
}

```

**Serial Output:**

```
BMP180 init fail

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

```

**Queries:**

• How to enable BMP180 to sense? When I configure BMP180 with Arduino (without ESP8266), I get the output in the serial terminal.

• How to send data to Thingspeak.com from BMP180 using the specified hardware?

# Answer
**Connections:**

\[...\]

* `Rx to Rx`
* `Tx to Tx`

That's not gonna fix your problem with initializing the BMP180, but you have to cross the lines, Rx to Tx and Tx to Rx, if you want to get anything on the serial terminal... Besides, your Nano is 5V, your ESP 3.3V. Connecting directly the Nano's Rx/Tx lines at 5V to the ESP's Rx/Tx 3.3V lines might not be very safe.

As for the BMP180, is it rated for 3.3V, or only 5V? If it is 5V only, it might not work on the ESP. Hence the init fail.
> 1 votes

# Answer
For I2C to work you must have pull up resistors. Normally 4.7K connected between SCL and VIN and SDA and VIN make thinks work.

You probably should use a logic level convertor to convert 3.3 to 5V (not a resistor divider, not sharp enough edges for digital signals). If I remember correctly the ESP can take 7V on its pins before you kill it (its in the chip spec) but that doesn't mean its a good idea to do it.

As mentioned above you need to cross the serial leads to make the connection. The Nano's Rx lead needs to be connected to the ESP's Tx lead and vice versa.
> 1 votes

---
Tags: esp8266, arduino-nano
---


# Question
Title: Two pots controlling 2 servos -- odd behavior
I'm trying to control 2 servos with 2 pots. I thought I could just amend the tutorial code by adding in the extra pot on a1 and extra servo on d8 (am using a Nano).

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
Servo myservo_2;

int potpin = 0;  // analog pin used to connect the potentiometer
int potpin_2 = 1;
int val;    // variable to read the value from the analog pin
int val_2;

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo_2.attach(8);
}

void loop() {
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val_2 = analogRead(potpin_2);
  val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  val_2 = map(val_2, 0, 1023, 0, 180);
  myservo.write(val);                  // sets the servo position according to the scaled value
  myservo_2.write(val_2);
  delay(15);                           // waits for the servo to get there
}

```

...but the servos only respond to one of the pots (on a0) & both move to the same position regardless of what value is on a1.

Am I missing something really obvious? Why is the value on a1 ignored & why is the value mapped from a0 sent to both d8 & d9?

I have swapped out the pot on a1 just in case it was faulty but I get the same behavior.

EDIT: Added schematic

EDIT: I swapped out the Nano for another Nano but that failed to upload the sketch. So I put the original back in & now evrything is working fine!

Darn'd if I can get my head around it, possibly a bad connection with the bread board?

Anyway all working now thanks for your suggestions.

# Answer
> 1 votes
I have no idea whats wrong with your system, but this might help you diagnose it.

```
#include <Servo.h>

static const size_t MaxServos = 2;              // The number of pots and servos attached
const int servoPins[MaxServos] = {9, 8};        // The pins that the servos are controlled through
const int potpins[MaxServos] = {A0, A1};        // analog pin used to connect the potentiometer
Servo myservo[MaxServos];                       // create servo object to control a servo

void setup ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        myservo[index].attach (servoPins[index]);
    }
}

void loop ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        readAndSet (potpins[index], myservo[index]);
    }
    delay (15);                           // waits for the servo to get there - might want to multiply a value by the number of degrees turned to give a better value.
}

// \brief   Read the specified analog pin and set the server proportionally
// \param   The analog pin that the pot is connected to.
// \param   The servo that will be moved
void readAndSet (const int& pin, Servo& servo)
{
    const int value = analogRead (pin);            // reads the value of the potentiometer (value between 0 and 1023)
    const int mappedValue = map (value, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
    servo.write (mappedValue);                  // sets the servo position according to the scaled value
}

```

I have refactored your code to eliminate the duplication. This means you will get more test coverage and you should find the bug quicker. You could add a `Serial print` statement to the `readAndSet` function to ensure that you are passing and calculating the right values, but I suspect you are.

There appears to be nothing wrong with the code, so is it possible that there is some hardware limitation? Is there a short between the lines that causes the pot on A1 to be bypassed?

---
Tags: arduino-nano, servo, potentiometer
---


title: Code output is not as expected

text:
# Question
Title: Code output is not as expected
```
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'E'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
int count = 0; char num[4];
char key;
byte rowPins[ROWS] = {A0, A1, A2, A3}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

char adhaar[4][4] = {
  {'1', '0', '8', '3'},
  {'9', '1', '6', '0'},
  {'5', '7', '6', '1'},
  {'6', '7', '9', '3'}
};

char adhaar0[4] = {'1', '0', '8', '3'};
char adhaar1[4] = {'9', '1', '6', '0'};
char adhaar2[4] = {'5', '7', '6', '1'};
char adhaar3[4] = {'6', '7', '9', '3'};
boolean check, control, adhar, tag_status;
int i = 0, j, p, q;

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
  Serial.begin(9600);
  Serial.println(" enter your adhaar ");
}

void loop() {
  getkey();
  checkkey();
}

void getkey() {
  while (i < 4) {
    char key = keypad.getKey();
    if (key) {
      num[i] = key;
      Serial.print(num[i]);
      i++;
    }
  }
}

void checkkey() {
  if (i == 4) {
    control = true;
    for (p = 0; p < 4; p++) {
      for (q = 0; q < 4; q++) {
        if (adhaar[p][q] == num[q]) {
          check = true;
          Serial.println(num[q]);
        } else {
          check = false;
          Serial.println(" not eligile");
          break;
        }
      }
      if (check == true) {
        adhar = true;
        Serial.println(" cast your vote");
      }
    }
    i = 0;
  }
}

```

My problem is once the adhaar matches with the values initialised in the array I have, it's going to "cast your vote" as expected, but after that it's again executing "not eligible" 3 times.

# Answer
First, a general remark: most of your variables are never used. You should get rid of them, as they only serve to make your code more obscure.

Then, the reason for the observed behavior is that you are comparing the entered code with 4 predefined codes. Whatever the user enters, there will be at least 3 non-matches, hence 3 times the program prints “not eligile”.

To get the behavior you expect, I would get rid all all those boolean variables that make the logic hard to follow, and instead break down the problem into smaller chunks, each implemented in its own small function. This makes it easier to write code that is easy to understand.

First, how do you tell whether two 4-character codes are the same? Like this:

```
// Do codes a and b match?
bool match(char a[4], char b[4]) {
    for (int i = 0; i < 4; i++) {
        if (a[i] != b[i])
            return false;
    }
    return true;
}

```

Then, given a code entered by the user, tell whether it matches `adhaar[0]` or `adhaar[1]` or... or none of them:

```
// Return the adhaar index matching the given key,
// or -1 if there is no match.
int matching_idx(char key[4]) {
    for (int i = 0; i < 4; i++) {
        if (match(key, adhaar[i]))
            return i;
    }
    return -1;  // no match
}

```

Now your `checkkey()` function can be rewritten as follows:

```
void checkkey() {
    if (i != 4) return;  // should never happen
    if (matching_idx(num) == -1)
        Serial.println(" not eligile");
    else
        Serial.println(" cast your vote");
    i = 0;
}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Fast PWM working with int main(void) but not with void setup()
board: Arduino Mega (ATMEGA2560)

I want to generate pulses using timer1 configured as Fast PWM, this is my code which works fine:

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

int main(void)
//void setup()
{

  DDRB |= (1 << DDB5) | (1 << DDB6); // PWM outputs

  ICR1 = 0x7FFF;  // TOP
  OCR1A = 0x3FFF; // 50% of ICR1
  OCR1B = 0x3FFF; // 50% of ICR1

  TCCR1A |= (1 << COM1A1) | (1 << COM1B1);
  TCCR1A |= (1 << WGM11);
  TCCR1B |= (1 << WGM12) | (1 << WGM13);
  TCCR1B |= (1 << CS10);

}

void loop() {

}

```

I don't understand why it doesn't work if I use `void setup()` instead of `int main(void)`. I'm working with arduino IDE 1.8.2 and always used void setup(), in this case I used int main(void) because it is used in some turorials I found like this one: https://www.youtube.com/watch?v=O\_Yqf\_cugwE

EDIT: When I say that it doesn't work, what happens is that instead of having PWM signals I just have a constant 5V output in both OC1A and OC1B pins

# Answer
> 1 votes
If you don't define your own `main()`, your program will be linked with the `main()` provided by the Arduino core library, which roughly looks like this (I am simplifying a little bit):

```
int main(void)
{
    init();      // Arduino core initialization
    setup();     // user's initialization
    for (;;)
        loop();  // user's main loop
}

```

The core's `init()` function configures Timer 1 for 8-bit phase correct PWM at 490 Hz, which means that, by the time your `setup()` runs, the timer's control registers are not in their default state anymore, and some of their bits are already set to 1. If you then update these registers using the `|=` operator, you end up with a mix of the core's configuration and your own.

This can be fixed either by zeroing these registers first or, more simply, by setting their values with the `=` operator, which has the effect or setting *every* bit of those registers to the value you want.

The following works whether you use or not the Arduino core library:

```
#ifdef NOCORE
int main(void)
#else
void setup()
#endif
{
    DDRB   = _BV(PB5) | _BV(PB6);
    TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM11);
    TCCR1B = _BV(WGM12)
           | _BV(WGM13)
           | _BV(CS10);
    ICR1   = 0x7fff;  // TOP
    OCR1A  = 0x3fff;  // 50% of ICR1
    OCR1B  = 0x3fff;  // 50% of ICR1
}

#ifndef NOCORE
void loop(){}
#endif

```

Note that:

1. The control registers are *set* (`=`) rather than just modified with `|=`
2. The mode is set before the output compare registers. This is because setting the output compare registers does not work well when the timer is in an 8-bit mode.

---
Tags: arduino-mega, pwm
---


# Question
Title: 16*2 LCD display doesn't display my result
I am working on a project to calculate line frequency meter by reciprocal counting with Arduino. I am trying to print the the result on a 16\*2 LCD but it is not displaying anything. It just gets on and stuck there. I got the project details from this website Line Frequency Meter Based On Reciprocal Counting

I modified the stock program to interface the LCD but it's not working. Here is the code I am using:

```
//To read and display the Line frequency
//using Reciprocal counting method
//clk for 'Time Counter'  is generated with 'Tone' function
//'Time counter' is the physical counter T1
// 'EVENT Counter' is a software counter
#define Fin 6      // input pin for Line freq sig
#define clk 7      // input to ' Time ' counter
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
boolean FState;   // status of the 50 Hz Signal
int countS;       // Signal count
int countC=0;     //  Clock count
int LineFreq;     // Result

void setup() {
  tone(8, 5000); // generates ref freq of 5000 Hz at Pin 8
  pinMode(Fin, INPUT); // set the Fin pin as INPUT
  pinMode(clk, INPUT); // set the clk pin as INPUT
  lcd.begin(16, 2);
}

void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Frequency of signal");
  // to avoid partial cycles, first detect the rising edge
  while(digitalRead(Fin)) {
    //wait for '0' state of the Signal
    delayMicroseconds(10);
  }
  //here '0' state
  while(!digitalRead(Fin)) {
    //wait for '1' state
    delayMicroseconds(10);
  }
  //this is the rising edge of the Fin
  //counting can start from here
  // clear the TIME Counter T1
  counterStart1();
  //count 50 of the Line freq signals
  while(countS<50) {
    while(digitalRead(Fin)) {
      //wait for '0' state
      delayMicroseconds(1);
    }
    //here '0' state
    while(!digitalRead(Fin)) {
      //wait for '1' state
      delayMicroseconds(1);
    }
    // here '1' state
    // here one cycle is just over
    //increment the event counter
    countS=countS+1;
  }
  //here 50 Signal cycles over
  // read the contents of T1 & compute frequency
  countC = getCount1();
  LineFreq = 25000000/countC;

  //send to display
  lcd.setCursor(0,1);
  lcd.print(LineFreq);
  lcd.print(" Hz");
  delay(500);
  delay(100);
  // clear counter
  countS=0;
  // repeat
}

//The following code is obtained from on-line articles in the public domain
void counterStart1() {
 // hardware counter setup,  for  the 16-bit Timer1 Timer/Counter
 TCCR1A=0; // reset timer/countern control register A
 TCCR1B=0; // reset timer/countern control register B
 TCNT1=0; // initialize the counter value to 0; this register holds the current count
  // set timer/counter1 hardware as a counter; it counts events on pin Tn (Arduino pin 5)
 TCCR1B = TCCR1B | 7; // Counter Clock source = pin Tn (Arduino pin 5) , start counting now
 // 7 in binary is 0111; OR-ing will set CS10,11,12 to 1's
return;
}

// the following code is obtained from on-line articles in the public domain
// Sub routine  to get the current count
unsigned int getCount1() {
 unsigned int count; // this variable returns the current count from the counting register
 TCCR1B = TCCR1B & ~7; // Gate Off  / Counter T1 stopped,
 // this operation clears the bits (CS10,11,12)
 count = TCNT1; // read the counting register
 TCCR1B = TCCR1B | 7; // re-start counting by resetting the bits (CS10,11,12)
 return count; // return the retrieved count to the calling function
}

```

I am getting a blank screen but the line at very first of the code "Frequency of signal" is printing accurately.

What is wrong with the code and what changes do I need?

Thanks in advance!

# Answer
Your variables are `int`, which on an Arduino is a 2-byte signed type by default, and has a range of `-32768` to `32767`.

When you execute:

```
LineFreq = 25000000/countC;

```

is the result of the math a 2-byte `int`, or a 4-byte `long`? Regardless, you are possibly assigning a 4-byte value to an `int`.

You can declare `LineFreq` to be type `long`, and also append an `L` to the end of the constant value `25000000` to force `long` math, so that you have:

```
long LineFreq;
[...]
LineFreq = 25000000L/countC;

```
> 2 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Is the C++ STL fully supported on Arduino?
I don't yet own an Arduino board to run code on, and as the title says, I'm curious if the C++ STL is fully supported on Arduino **and already part of** the Arduino IDE. The STL is probably the most efficient, fully tested, and resource-minimal (which is a slightly redundant phrase, as I already mentioned efficiency) publicly available C++ code out there, and would make life much easier to code for Arduino.

*If* the STL is not a part of Arduino IDE, then how to include specific libraries such as `<algorithm>` and `<utility>`? (I'm very tempted to ask "why isn't it included?" but that seems too broad.)

# Answer
> 10 votes
The STL is not a part of Arduino IDE.

Although efficient by desktop standards, the consensus is it doesn't fit comfortably in an Arduino's limited space. That said, here's someone who seems to have done it:

https://github.com/maniacbug/StandardCplusplus

Check out the forks, they seem more up to date

# Answer
> 3 votes
STL is efficient on the platform it was designed for, which is personal computers and similar-scale devices, where allocating a single byte in the heap consumes a 4k memory page (that's several times as much as ALL Arduino RAM), and where array indexes can be efficiently replaced by pointers (8-bit microcontrollers need at least two commands to deal with a pointer). So no, it's not efficient with Arduino.

Think of quicksort algorithm - it performs very well on large lists, but is easily beaten by a simple sort if you need to sort an array of 5 elements. Being asymptotically efficient doesn't mean being efficient in every case.

# Answer
> 3 votes
The STL is not a part of Arduino IDE.

Another answer is mentioning https://github.com/maniacbug/StandardCplusplus although this library doesn't seem to be maintained anymore.

Maybe a better idea could be to try https://github.com/mike-matera/ArduinoSTL

It's a port of uClibc++ packaged as an Arduino library.

# Answer
> 2 votes
The STL is not part of Arduino and no support for libstc++ from AVR.

My "answer" differences from Malachi at one point though, as explained in the comments.

I don't think you shouldn't, just because "most people say" that you shouldn't. There are a lot of people that even think you shouldn't use C++ at all. The problem is that C++ (and C++ standard library) are very powerful and may be ported in a non-efficient way.

---

**Why use libstdc++?**

I think, however, that if you use it with care, it can be very usefull.

Let's say we've got two buffers, a send buffer and a receive buffer. With C, you would store them in a fixed char array. In C++ you can use dynamic containers.

So in C, you'll use 2x 256 bytes of memory to save your messages. Any longer message won't fit.

In C++ you'll use only whatever bytes are needed at one point (plus some extra probably). And if you get a longer message, it will simply scale up.

If the C++ thing works for you, and just test it very very well, why not use it? On average, it will use less memory, since you don't assign all of it when it's not used. You will have a problem when your messages get too big, since your memory will overflow, often causing the microcontroller to reset. But if more buffers in your program are dynamic, one may leave some space for the other, etc. Effectively using the memory more efficient!

But, without dynamic allocation, it might be a little safer, since you've already claimed those pieces of memory, there is no way you can't use those pieces. Any message that is bigger, simply won't fit, but you can easily check on that. Another thing is that the C++ stl's you find, might not be as well optimalised for your architecture/microcontroller.

Also, creating your very own dynamic storage in C may cause even more problems than the C++ stl ;). And it's not like you have to use dynamic storage for everything, simply being able to do so is nice.

---

Current microcontrollers are also getting much more serious as the 8-bit Arduino's (328P). 20$ can get you a Teensy 3.2 which has `256K Flash Memory, 64K RAM` so, in this case, dynamic memory can be very useful (if you are certain you always have enough memory left). Also: `All STM32F41xxx products embed: Up to 192 Kbytes of system SRAM including 64 Kbytes of CCM (core coupled memory) data RAM`

By that, it can also be a very nice way to learn C++ and program in the same language as you do on the PC. But keep in mind that on an 8-bit micro, you should check if your stl-functions don't give too much overhead.

---

How use C++ standard template library for AVR?

I've followed the blog from Andy Brown and now have iterators/string/vectors working in AtmelStudio.

Though I did get some errors, the first batch of errors included:

```
Error        '_M_deallocate' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]      D:\avr-stl\include\string    173
Message        declarations in dependent base 'std::_String_alloc_base<char, std::allocator<char>, true>' are not found by unqualified lookup        D:\avr-stl\include\string    173
Message        use 'this->_M_deallocate' instead     D:\avr-stl\include\string    173

```

This error actually explains itself; you should use `this->_M_deallocate`.

After that I got `undefined reference to "operator new(unsigned int, void*)`. But I fixed it by including "pnew.cpp" right under `#include <new>` in `stl_construct.h` which is weird, but it works.

(Piece of stl\_construct.h)

```
#ifndef __SGI_STL_INTERNAL_CONSTRUCT_H
#define __SGI_STL_INTERNAL_CONSTRUCT_H

#include <new>
#include <pnew.cpp>

__STL_BEGIN_NAMESPACE

```

---
Tags: c++, stl
---


# Question
Title: SPST switch - powered from pin output, or voltage regulator
I have a SPST switch and I just want to sense whether it's on or not. I will then turn on/off a relay depending on the state of this switch.

The two options I'm considering are: create a digital out on a pin going to one side of the switch, and read the digital in on another pin off the other side of the switch. Or put 5v from my voltage regulator to the switch, and read a digital in off the other side of the switch.

Would a resistor be necessary for the digital in pin with either of these options?

# Answer
It is wasting of IO pins to use the digital output pin just to get +5V rail. But both options will work. Don't forget to use pull/up or pull/down resistor, or activate internal pull/up resistor on the sensing pin. When the switch will be open, the input pin is not connected anywhere and will act as antenna, so it might pick up some noise.
> 3 votes

# Answer
You could configure one of the digital pins as INPUT\_PULLUP and connect one end of the switch to it. The other end of the switch goes to ground. LOW = switch ON, HIGH = switch OFF.

```
const byte pinNumber = 3;

void setup(){
  pinMode(pinNumber, INPUT_PULLUP);
}

void loop(){
}

```
> 4 votes

---
Tags: switch
---


title: Why is my TMP35 giving me weird values?

text:
# Question
Title: Why is my TMP35 giving me weird values?
A TMP35/36/37 is giving very high voltage readings, which results in high temperature readings. The serial monitor looks like this:

As you can see, the sensor value is in the 900s, voltage is almost 5, and temp is in the 400s. The circuit is very simple, just a TMP connected to 5V and ground and pin A0. Here is my code:

```
const int sensorPin = A0;
const float baselineTemp = 20.0;

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

}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal / 1024.0) * 5.0;
  Serial.print(", volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5) * 100;
  Serial.println(temperature);
  delay(1000);
}

```

This is a very simple program and a very simple circuit, so I'm not sure what is going on. Maybe the problem is the sensor itself. I have also tried this sensor with multiple other circuits and programs and the same thing happens.

If anyone knows anything about this, help would be great.

# Answer
Part seems to be broken; voltage is unusually high.
> 1 votes

# Answer
I use voltage dividers a lot and have seen this before.

In each and every case where ALL my readings are high, yet they vary predictably (like on my solar panels - they go up during day and down at night), there has always been proven to be a very simple, single cause.

**Resistance in the ground lead.**

Such as if it is plugged into a breadboard hole that is not holding it well, or if I have extended it and have connections along the way.

So that would be the first thing I would look for.

---

Having said that, if the readings are very high and do NOT vary predictably, then I would look for a disconnected ground lead.

---

**If all the connections are good but it still misbehaves then I would swap it out with another one to make sure the part itself isn't the problem.**
> 1 votes

---
Tags: arduino-uno, sensors, temperature-sensor
---


# Question
Title: Is there any way to group variables like group.variable as you can in Java/Delphi
I'm writing a sketch which does some calculations on measured variables, and it's based on a similar program written in Java like c = A.Ux + B.Uz; Where A&B have various parameters Ux,Uy,Uz etc In Delphi this notation can be used either for parameters of classes or variables in a group. Looks like there's something similar in Java. It's a tidy way to organise and manipulate variables when there are lots of them and move them between methods without having huge numbers of arguments.

Is there any way to do this in the Arduino Wiring language? I don't seem to find anything online, but I'm probably phrasing the question wrong. Thanks in advance, Brian

# Answer
What you are looking for is a `struct`:

```
struct foo {
    uint8_t Ux;
    uint8_t Uy;
    uint8_t Yz;
};

```

Then:

```
struct foo A;
struct foo B;

```

And:

```
A.Ux = 3;
B.Uz = 48;

int c = A.Ux + B.Uz;

```

When calling a function you should really use either pass-as-pointer or pass-as-reference to avoid unnecessary copying:

```
// By Reference
int normal(struct foo &arg) {
    return (arg.Ux + arg.Uy + arg.Uz) / 3;
}

int avg = normal(A);

```

Or:

```
// By pointer
int normal(struct foo *arg) {
    return (arg->Ux + arg->Uy + arg->Uz) / 3;
}

int avg = normal(&A);

```

You can read more about structs here.
> 2 votes

---
Tags: variables, class, mathematics
---


# Question
Title: Getting error while uploading a sketch through Ardunio IDE
I recently used the Ardunio board and powered with the AVR pocket programmer along with the AVR ISP cable and it worked just fine and no issues were experienced. However now that i switch back to the default method of powering Ardunio board with USB, getting this error while trying to upload the sketch.

There are forums available on Arduino platform but no definitive resolution.

The board is recognized by the IDE.

# Answer
> 0 votes
Reinstall the bootloader using your ISP programmer.

Installing a sketch using ISP first wipes the chip clean, and that includes the bootloader. Without the bootloader the USB interface won't be able to communicate with the main MCU.

---
Tags: arduino-uno
---


# Question
Title: Return mean of observations for a given sample time
new to this StackExchange site. I have an experimental setup with three inputs - two from a laser distance sensor to measure planar distance and one digital input from a set of callipers.

All sensors readings fluctuate over a small range (which is acceptable for my use case). Is it possible to have the Arduino record all inputs for a given period of time and output only the mean value for each sensor?

# Answer
> 1 votes
I have this:

```
int readElSens() {
  long sum = 0;
  int n = 0;
  long start_time = millis();
  while(millis() - start_time < 400) {
    sum += analogRead(ELSENS_PIN);
    n++;
  }
  return sum / n;
}

```

---
Tags: arduino-mega
---


title: Custom function like yield

text:
# Question
Title: Custom function like yield
As far as I understand, `yield()` is used when you have long code (e.g. loop) so the background processing required by the esp8266 is not suspended for long time.

I have application where some sound should be running all the time and in the same time the program has to do other things which may includes long loops (that I call `yield()` inside them). Those long loops cause the sound to be discontinues.

What is the best idiomatic way of imitating the `yield()` function in my program so I do some thing like this:

```
for(int i=0;i<10000;++i){
    yield();
    customeYield();
    someFunction(i);
}

```

Where `customeYield()` contains the necessary instruction for playing the sound. It is exactly like this (I am using ESP8266Audio):

```
if (mp3_->isRunning()) {
    if (!mp3_->loop()) {
        mp3_->stop();
        return true;
    }
    return false;
}
return true;

```

Of course, I can just call it like I did (making it global or something). However, I was wondering if there is a standard way for such a task.

# Answer
Without any hint, what you are actually doing in your long loops, it is difficult to say, what way would be the best for your case. I don't believe, there is a standard way of doing this, but there are basically only two ways of multitasking on a microcontroller:

1. **Interrupt driven:** You can set a timer interrupt, that occurs regularly to call the `AudioGenerator::loop()` function (which fills the buffer with the next data).
2. **Non-blocking code:** If you are using non-blocking code, you can first do one thing and then do another in sequence, so fast, that both codes are executed often enough. Thats exactly what the library you use is designed for (according to the README file).

If you are using more than one of these long loops in your `loop()` function, you may consider doing things with a finite state machine (FSM), so that you don't have to always add the `AudioGenerator::loop()` function to your long loops, but only once for the normal `loop()` function.
> 3 votes

---
Tags: esp8266
---


# Question
Title: LiPo + charge/boost circuit vs pre-built "power bank" - contrasting portable power sources
Portable 5V power for my projects - I was about to get the necessary parts to wire up an OEM LiPo battery (3.7V battery, boost circuit, charging circuit) when I took a peak at pre-built "power banks". From all the sources I see the LiPo batteries alone cost more than the power bank, at much lower capacity. For reference:

* a 10400 mAh power pack (max output 3A @ 5V) is 26$ on Amazon
* a 10000 mAh power pack (max output 2.1A @ 5V) is 9$ on Hobby King
* a 2500 mAh LiPo is 17$ on Amazon
* a 5000 mAh Lipo is 8$ on Hobby King

The power packs already have charging and voltage regulation circuitry! The price difference makes me think I am missing something.

Reading around I notice issues with power packs auto-shutdown at low current draws. But other than this power packs seem cost optimal and technically equivalent - at least within the output amperage range of the power banks.

Questions:

* Are there any technical differences in output voltage, lifetime, or otherwise I am missing here?
* Are there any "surprises" I'm going to face by using a power pack?
* Can you recommend a solid power pack that doesn't shut down at arduino level draws. (My app will draw 800mA @ 5V max, but during sleep, the draw of an Arduino Nano)

Thanks!

# Answer
> 3 votes
The thing to remember with power banks bought on places like eBay and Amazon is:

* **THEY LIE ABOUT THE CAPACITY**

A typical power bank you would expect to get around 3600mAh from, even though it may say 10000mAh, 50000mAh, 1,000,000,000,000mAh, etc.

The only technical difference between rolling your own circuit and a power bank is the low-current switch-off that *many* (but not all) of them have. That switch-off is fine if you are always drawing a good amount of current, but once your device goes to sleep and the current drops right down you'll find the power bank will switch off and your device will never wake up again.

However, with rolling your own system you know what you are getting. You know the capacity of your battery.

One further thing to consider: Do you *really* need 5V? The majority of electronics run from 3.3V nowadays, and the Arduino is no different. There are Arduino boards designed to run from 3.3V, and even 5V boards can be tweaked to run at 3.3V (albeit slower than normal).

So the ideal solution would be:

* A single-cell Li-Poly / Li-Ion giving nominal 3.7V
* A Li-Ion charger circuit
* A low-dropout or switching regulator with max 400mV dropout.

And no boost circuit needed. Also, no logic level shifting when communicating with 3.3V devices.

---
Tags: power, battery, lipo
---


title: interrupt pin of attiny85 unstable

text:
# Question
Title: interrupt pin of attiny85 unstable
I'm trying to learn how to program a MC, so maybe I didn't know much about a MC. I tried to test interrupt pin of ATtiny85 with this simple code

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

void setup()
{
  GIMSK = 0b00100000;
  PCMSK = 0b00000001;
  sei();
  DDRB = 0b00010000;
}

void loop()
{
  PORTB = 0b00010000;
  _delay_ms(500);
  PORTB = 0b00000000;
  _delay_ms(500);
}

ISR(PCINT0_vect)
{
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);

}

```

This is just a blink code with an interrupt to make the LED blink faster 10 times. My question is why sometimes the LED blink faster many times with the interrupt pin is not connected to anything (open)? Didn't it have internal pull up or should I use external pull up in my circuit?

Thank you

# Answer
More than an answer, these are some comments and suggestions on your program, that I hope will help you write cleaner code:

1. Since you seem to be avoiding using the Arduino core library, you may as well write your own `main()` instead of relying on the one from the core. This way you have a plain C program that can be compiled either within or outside of the Arduino framework.
2. Instead of opaque constants, like `0b00100000`, use the bit names. These names are defined in the datasheet and are provided by the avr-libc. They are normally used with the `_BV()` macro, which expands to `(1<<(x))`.
3. For those of us who do not have the full datasheet in our head, a comment or two stating what each bit does is helpful.
4. To change only one bit from a port, use the syntax `PORTB |= ...;` or `PORTB &= ...`. The compiler is smart enough to turn this into single assembly instructions, namely `sbi` and `cbi`.
5. Rather than repeating ten times the same lines, use a loop.

Applying these suggestions, your program would like like;

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

ISR(PCINT0_vect)
{
    for (int i = 0; i < 10; i++) {
        PORTB |= _BV(PB4);
        _delay_ms(100);
        PORTB &= ~_BV(PB4);
        _delay_ms(100);
    }
}

int main(void)
{
    PORTB = _BV(PB0);     // internal pullup on PB0
    GIMSK = _BV(PCIE);    // enable pin change interrupt
    PCMSK = _BV(PCINT0);  // sense pin change on PCINT0 = PB0
    DDRB  = _BV(PB4);     // pin PB4 as output
    for (;;) {
        PORTB |= _BV(PB4);
        _delay_ms(500);
        PORTB &= ~_BV(PB4);
        _delay_ms(500);
    }
}

```
> 0 votes

# Answer
The internal pullup is only activated, if you activate it in your code. To so, you have to write a `1` to the corresponding bit in the `PORTB` register, while the `DDRB` register is set for the pin to be an input.

So you the interrupt gets triggered randomly, because the pin was floating.

Since you are currently always write to the whole `PORTB`, you have to change the last bit to `1` on every `PORTB` write. Or you can write a `1` to it in `setup()` and only change the one output bit in `PORTB` by using

```
PORTB ^= 0b00010000;

```

This will toggle only your output pin.
> 1 votes

---
Tags: interrupt, attiny, pull-up, atmel
---


# Question
Title: How to configure location of preferences
I had been using Arduino 1.0.5 on my Pi, and in September last year downloaded `arduino-1.8.4-linux32.tar.xz` (which I have since updated).

I have been successfully using 1.8.5, but just noticed it seems to have been `/home/pi/.arduino15` for preferences and packages.

I probably did this inadvertently when I was briefly running both 1.8.4 and 1.0.5 (which is long gone). I have `/home/pi/.arduino` but this only contains `preferences.txt` and has not been used since September.

There seems to be no way of changing this to the normal directory; where is this configured?

# Answer
> 0 votes
Since the introduction of many enhancements in the IDE, such as the Boards Manager, and the Arduino Builder system, it was decided that this would break backwards compatibility with older versions of the IDE. In version 1.5.0 of the IDE it was therefore decided that the location of all the Arduino data files (of which there are now many, not just a `preferences.txt` file) should be moved to a new location, and `.arduino15` was chosen to reflect the current version.

Since then a *version number war* broke out between the two Arduino factions, which was then subsequently resolved, and we ended up with the 1.8.x group of versions. These, since they haven't introduced anything drastic to the underlying system since 1.5.x, haven't needed to change the location of the data files (indeed, to do so would be undesirable), so it has remained as `.arduino15`.

I don't believe it's possible to change the preferences location, since the only place would be in preferences, and it would need to load the preferences to know where to load the preferences from.

If you *really* need to access the `preferences.txt` file yourself as `~/.arduino/preferences.txt` (why would you?) then you can just delete the old `.arduino` directory and create a link to the new one:

```
$ rm -rf .arduino
$ ln -s /home/pi/.arduino15 .arduino

```

---

Update:

There is a command-line argument to the Arduino IDE that lets you set the location of the preferences.txt file (detailed here):

```
$ arduino --preferences-file /home/pi/.arduino/preferences.txt

```

However what that will do with an old preferences.txt file is anyone's guess.

---
Tags: arduino-ide, raspberrypi
---


# Question
Title: Wake Huzzah Feather ESP8266 With Reed Switch
Forgive me if this is a really dumb question but I am new to IOT and hardware in general.

I have a Huzzah Feather ESP8266 and I am trying to make a bathroom occupancy sensor. I am using a standard reed switch door sensor (example here).

Ultimately what I want this device to do is:

1. The plan is to wake the device from deep sleep when the door is closed, according to the documentation GPIO16 needs to be connected to RST to send a wake signal.
2. Once awoken check the reed switch and send a message to Azure IoT hub that says the `bathroom is occupied` if door is closed.
3. Put the device into deep sleep, waking every 30 seconds.
4. Every time the device wakes check the switch, once the door is opened I send a message to Azure that the `bathroom is not occupied` and then put into `deepSleep(0)` (i.e asleep until the door is closed again, then the process repeats)

**Right now this all works but in the opposite. I can wake the device when the door is opened, the message sends successfully to Azure.**

From my super limited understanding of this it seems like what I want to do should be possible. I imagine I am missing something very simple, but I have hit a wall here.

I dont know how to make wiring diagrams so hopefully a description of my setup will suffice:

* GPIO 16: Door sensor wire #2
* RST: GPIO 16
* GND: Door sensor wire #2

Simplified code sample:

```
void setup()
{
    initSerial(); //inits serial
    initWifi(); //initis wifi
    door_open(); //sends message
}

void door_open() {
  IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

  if (iotHubClientHandle == NULL)
  {
    Serial.print("Failed on IoTHubClient_LL_Create\r\n");
  }
  else
  {
    // Because it can poll "after 9 seconds" polls will happen
    // effectively at ~10 seconds.
    // Note that for scalabilty, the default value of minimumPollingTime
    // is 25 minutes. For more information, see:
    // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
    unsigned int minimumPollingTime = 9;

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
    {
      Serial.print("failure to set option \"MinimumPollingTime\"\r\n");
    }

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
    {
      Serial.printf("failure to set option \"TrustedCerts\"\r\n");
    }

    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, NULL) != IOTHUB_CLIENT_OK)
    {
      Serial.print("unable to IoTHubClient_SetMessageCallback\r\n");
    }

    IOTHUB_MESSAGE_HANDLE messageHandle;
    if(digitalRead(DOOR) == LOW)
    {
      messageHandle = IoTHubMessage_CreateFromString("closed");
      Serial.println("Door closed");
    }
    else
    {
      messageHandle = IoTHubMessage_CreateFromString("open");
      Serial.println("Door Open");
    }

    if (messageHandle == NULL)
    {
      Serial.print("unable to create a new IoTHubMessage\r\n");
    }
    else
    {
      MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);

      if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
      {
        Serial.print("failed to hand over the message to IoTHubClient");
      }
      else
      {
        Serial.print("IoTHubClient accepted the message for delivery\r\n");
      }
      IoTHubMessage_Destroy(messageHandle);
    }

    while (1)
    {
      IoTHubClient_LL_DoWork(iotHubClientHandle);
      ThreadAPI_Sleep(100);
    }
  }
}

```

**To clarify:** Right now my device will wake when the door sensors magnetic parts are separated. I want the device to wake when the circuit is complete (i.e the sensors are *together*).

# Answer
> 3 votes
I would get an NC or NO reed switch, the opposite of whatever you have now that's backwards. I would then get rid of all the sleep wakeup stuff and turn the unit on through the reed switch, so it has power when the door is closed, if that's more common than it being open. When closed (powered), the MCU sends a ping on boot to a server that says "hey i closed", and go to deep sleep for 10 seconds.

Once re-awaking, send out a ping that says "I'm still busy". The server needs a tiny bit of smarts, a time-out feature that sets the door state as open 12 seconds after the last ping (10s + some accounting for wifi delays).

This setup uses NO standby power, and only a tiny amount of battery-killing on-time, so it should last a lot longer than trying to sleep and externally wakeup.

For added efficiency, consider building an ESPNOW router with two more ESP8266s. Once you have that ESPNOW router up and running, you can fire off a ping in about 200ms (from a cold/warm boot) instead of 2000ms with wifi, and go back to sleep. This extends your battery life ~10x, at the cost of running two more ESPs 24/7 where power is easily available.

# Answer
> 2 votes
The RST (reset) pin of the ESP works as the reset pin of any other microcontroller. If you pull it to LOW long enough (the threshold is surely listed in the datasheet), the whole microcontroller will reset as if you had cut and reestablished the power supply. So it will not wake it from sleep, but reset it completely.

It is correct, that you can use GPIO16 connected to RST, to let the ESP reset itself from a deep sleep. This seems to be an internal hardware functionality, that is distinct from the normal IO hardware. But you cannot use the same pin for some other functionality at the same time. Your reed switch is closed, if the door is closed. So it gives a LOW level to GPIO16 and RST, holding it in reset state. In this state no code is executed, thus you never get a message, that the door is closed. When you then open the door, the switch opens too. Since the RST pin isn't pulled to LOW anymore, the ESP can boot and execute your code. The door is open, so you get the corresponding message.

So you have to use a different pin for the reed switch.

---
Tags: esp8266
---


# Question
Title: Arduino Libraries: Declaring variables as public?
How come I never see any Arduino Library expose some of it's internal variables as public in the header file? I only see functions which are declared as public, while every variable is declared private.

Background: I want to write my first Arduino library. And I thought of making some variables of this library public, so that I don't have to call a function later on when I import the library.

E.g. I want:

```
#include MyLibrary
...
MyLibrary instance();
instance.avariable = 12345;

```

instead of:

```
#include MyLibrary
...
MyLibrary instance();
instance.setVariable(12345);

```

# Answer
Classes are used to hide away the complexity of a certain task. The user of the class should not worry about how the library exactly works in the inside, but instead only worry about how it should be used. In many cases directly writing to a member variable can be not only convenient, but hurtful if a wrong value is set. If you instead use a function to set the variable, the author can add code to prevent wrong values from actually being written to the variable. Also there might be some other logic involved, that is not triggered, if you write directly to the variable. So - for the ease of use - the users might want the library to be responsible for this, not themselves.

If you write a library, you have thought about how it should be used. Hiding other ways away is a common way of leading the user through the usage. Ways of usage, that don't go along with the purpose of the library can be hided away to make the correct way clearer. A manufacturer of a saw doesn't give the user instructions how to use the wrong side of the blade, because it doesn't help you with sawing.

This does not mean, that you shouldn't make variables public at all, but only if it makes sense. For example: If you are defining a class, that just represents a point in a coordinate system without hooks to other code, it is totally OK to make the coordinates public. But if you defined the class, so that the point is directly shown on a display, you might want to change the position on the display, whenever one of the coordinates is changed. In this case you can use a set-function to trigger the display update, when a new value was given for the variable.
> 2 votes

# Answer
The Arduino ecosystem is meant mostly for beginners. This often means that people with very little knowledge will be using it and will often try random things to make stuff work. (and once they found something that works will teach it to the next guy that has the dame problem).

Disallowing things that would easily break the invariants of the library from the outset reduces the amount of support you need to give to people that inadvertently break the library by randomly changing some variable.
> 3 votes

---
Tags: c++, library, class
---


# Question
Title: Arduino: load variables with values read from SD card
I am having a bit of trouble loading values stored on an SD card and assigning them to variables within my program. I can achieve this as one big block of data, but would much prefer them to be saved to variables whilst in a loop or some other process.

My txt file has the following 6 ints & floats values, which are displayed vertically in the file:

2 0.003200 312 1 0.720000 8

Each of these values I want assigned to variables data1,....2,3,4,5,6. Unfortunately, the code I use below will never achieve this, but I am clueless as to any theory to solve this problem. Thanks in advance.

```
myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
    while (myFile.available()) {
        data = myFile.read();
    }
myFile.close();
}
else {
    Serial.println("Read Error");
}

```

# Answer
File implements Stream just like Serial. so you can use parseInt and parseFloat

```
int n = File.parseInt();
float x = File.parseFloat();
Serial.println(n);
Serial.println(x, 6);

```
> 1 votes

---
Tags: arduino-uno, c++, sd-card, data-type, float
---


title: compare two hex files

text:
# Question
Title: compare two hex files
I need to check if the code burned on the some Arduino is the same one as I have. I know how to get the hex file from the Arduino. My question is what influence the hex code? Board Type? Microprocessor type? avrdude version? anything else?

# Answer
The lines in a typical hex file include a VLI (variable length indicator). The hex files output from the IDE might have different lengths than those produced by avrdude. As a simple example:

File 1:

```
03ABC
03DEF

```

File 2:

```
06ABCDEF

```

Those files will compare differently to each other but convey the same information, split differently between lines.

To do a genuine comparison you would need to account for that.

> Board Type?

Different boards, but with the same processor, might have identical files.

> Microprocessor type?

Different processor would almost certainly have different hex files.

> avrdude version?

Probably not, however see my comments above about the VLIs.

> anything else?

As I said, the compiler may generate lines with (say) 16 bytes per line, but avrdude might read back lines with 32 bytes per line. Thus they would look different but convey the same hex codes, once you allow for that.
> 0 votes

---
Tags: sketch, avrdude
---


# Question
Title: Arduino Micro not providing regulated power
I have an arduino micro that works fine off USB. I need to power it from an external 12V power supply. When I connect the 12V supply to the adjacent VIN and GND pins, the arduino will not power up. When I measure the power at VIN, it's 12V. When I measure power at the 5V pin, it's also 12V. If I disconnect the external power and go back to USB, it powers up.

Blown regulator?

# Answer
> 1 votes
In comparing this with another Arduino Micro, it appears that the regulator is malfunctioning.

---
Tags: power, arduino-micro, voltage
---


# Question
Title: Can increasing the size of the software RX buffer cause problem in Arduino Uno
If I were to increase the of the buffer array from 64 to say 512 will this bring any long term problem in the Arduino Uno.

Changing from this:

```
#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 64 // RX buffer size
#endif

```

to this:

```
#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 512 // RX buffer size
#endif

```

This is the header file of the software serial.

# Answer
The buffer is in the UNO's limited (2K) RAM; you'd be using 1/4 of it for the input buffer. If your app is small enough and simple enough (limited call depth, specifcally), there may still be enough RAM for your app to run successfully. If you have lots of globals (remember to include libraries when you're considering RAM use), allocate much memory from the heap (with `new` or `malloc()`) or have a complex call structure such that funcA() calls funcB() calls funcC() calls ... (etc) so that many functions' stack-frames remain allocated at once - at any point in your program - your program could suffer a stack-collision: the call-stack descends low enough that it can overwrite, or get over-written by, your heap or global data.

Why do you want so large an input buffer? Will data be coming in a high rate or in large bursts, while processing of the data will be infrequent or occur at irregular times? Given the limited RAM in the UNO, running complex programs on one can require something of a balancing act in how you use resources.

Update:

> i was performing some AT commands with software serial and buffer limitation generated junk value

Other reasons why SoftwareSerial might return bad data are:

* Using too high a baud rate (9600 baud seems to be about the max);
* Code that turns the interrupts off too often or for too long;
* Other devices creating too many interupts (perhaps a built-in timer running at a high rate).

The replies to most devices' AT commands that I know of are short enough to not require a huge receive buffer. Asking for list of WiFi SSIDs from an ESP8266 could generate a large reply but most responses should not overflow a more modest buffer.
> 4 votes

# Answer
Most arduino modules have 2k ram. So think about that. Whether you need more buffer or more working space. Keep in mind that other libraries are also using the same ram.
> 0 votes

---
Tags: arduino-uno, c++, softwareserial
---


# Question
Title: Problem connecting Android app to Arduino
Sorry for doing this, I really don't know where to post beacuse this is both Android Studio code and Arduino code so I've posted to both sites.

I want to create a project of using controlling pan-tilt (2 servos combined) using the accelerometer and gyroscope data in smartphone. Creating Android app and sending the accelerometer and gryroscope data to Arduino so that the pan-tilt can determine its location.

My problem is when I connect the Android app to Arduino, no data is shown in serial monitor of Arduino and the pan-tilt is not locating the smartphone. Please help me to solve this problem.

This *MainActivity* is the class to identify the data of accelerometer and gyrscope.

MainActivity:

```
public class MainActivity extends AppCompatActivity implements SensorEventListener{

    private final String TAG = "MainActivity";//log our activity

    SensorManager sm;//define sensor manager
    Sensor accelerometer, gyrometer;//define accelerometer

    TextView xValue, yValue, zValue, xGyroValue, yGyroValue, zGyroValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        xValue = (TextView)findViewById(R.id.xValue);
        yValue = (TextView)findViewById(R.id.yValue);
        zValue = (TextView)findViewById(R.id.zValue);

        xGyroValue = (TextView)findViewById(R.id.xGyroValue);
        yGyroValue = (TextView)findViewById(R.id.yGyroValue);
        zGyroValue = (TextView)findViewById(R.id.zGyroValue);

        Log.d(TAG, "onCreate: Initializing Sensor Services");

        sm =(SensorManager) getSystemService(Context.SENSOR_SERVICE);//permission to use the sensor

        accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (accelerometer != null) {

            sm.registerListener(MainActivity.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
            Log.d(TAG, "onCreate: Registered accelerometer listerner");
        }else {

            xValue.setText("accelerometer is not supported");
            yValue.setText("accelerometer is not supported");
            zValue.setText("accelerometer is not supported");
        }
        gyrometer = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        if (gyrometer != null) {

            sm.registerListener(MainActivity.this, gyrometer, SensorManager.SENSOR_DELAY_NORMAL);
            Log.d(TAG, "onCreate: Registered gyrometer listerner");
        }else {

            xGyroValue.setText("gyrometer is not supported");
            yGyroValue.setText("gyrometer is not supported");
            zGyroValue.setText("gyrometer is not supported");
        }
    }

    public void connect(View v){

        DataSender dataSender = new DataSender();
        dataSender.execute((String) xValue.getText(), toString());
        dataSender.execute((String) yValue.getText(), toString());
        dataSender.execute((String) zValue.getText(), toString());
        dataSender.execute((String) xGyroValue.getText(), toString());
        dataSender.execute((String) yGyroValue.getText(), toString());
        dataSender.execute((String) zGyroValue.getText(), toString());

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor sensor = sensorEvent.sensor;
        if(sensor.getType() == Sensor.TYPE_ACCELEROMETER){

            Log.d(TAG, "onSensorChanged: X: " + sensorEvent.values[0] + "Y: " + sensorEvent.values[1] + "Z:" + sensorEvent.values[2]);

            xValue.setText("xValue:   " + sensorEvent.values[0]);
            yValue.setText("yValue:   " + sensorEvent.values[1]);
            zValue.setText("zValue:   " + sensorEvent.values[2]);
        }else if (sensor.getType() == Sensor.TYPE_GYROSCOPE){

            xGyroValue.setText("xGyroValue:   " + sensorEvent.values[0]);
            yGyroValue.setText("yGyroValue:   " + sensorEvent.values[1]);
            zGyroValue.setText("zGyroValue:   " + sensorEvent.values[2]);

        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

```

This DataSender is the class for sending the data to Arduino.

DataSender:

```
public class DataSender extends AsyncTask<String, Void, Void> {

    Socket s;
    DataOutputStream dos;
    PrintWriter pw;

    @Override
    protected Void doInBackground(String... voids) {

        String data = voids[0];

        try {
            s = new Socket("192.168.1.100",80);
            pw = new PrintWriter(s.getOutputStream());
            pw.write(data);
            pw.flush();
            pw.close();
            s.close();

        } catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }
}

```

This is code that are uploaded in wifi module (esp8266-01) that are connected in Arduino.

Arduino code:

```
#include <SoftwareSerial.h>
#include <Servo.h>

#define DEBUG true

SoftwareSerial esp8266(10, 11); // RX, TX

char tiltChannel=0, panChannel=1;

//These are the objects for each servo.
Servo servoTilt, servoPan;

//This is a character that will hold data from the Serial port.
char serialChar=0;

// Center servos
int tiltVal = 90;
int panVal =90;

//smaartphone value
String inText;
float value0, value1, value2;

void setup() { // Open serial communications and wait for port to open:

  servoTilt.attach(2);  //The Tilt servo is attached to pin 2.
  servoPan.attach(3);   //The Pan servo is attached to pin 3.
  servoTilt.write(90);  //Initially put the servos both
  servoPan.write(90);      //at 90 degress.

  Serial.begin(9600); //for monitoring purposes
  esp8266.begin(9600);

  //sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
  sendCommand("AT+IPR=9600\r\n", 1000, DEBUG);
  sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"EceConnect\",\"1234\"\r\n", 3000, DEBUG); //connec to
a network with name EceConnect with password 1234
  delay(1000);
  sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
  sendCommand("AT+CIPSTA=\"192.168.1.100\"\r\n", 1000, DEBUG);
  sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple
connections
  sendCommand("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port
80
  Serial.println("Server Ready");

  Serial.println("Android Sensor Type No: ");
  Serial.println("1- ACCELEROMETER  (m/s^2 - X,Y,Z)");
  Serial.println("2- GYROSCOPE (rad/s - X,Y,Z)");
  Serial.flush();

}

void loop() { // run over and over

  Serial.flush();
  int inCommand = 0;
  int sensorType = 0;
  unsigned long logCount = 0L;

  if (Serial.available() < 1) return; // if serial empty, return to loop().

    char getChar = ' ';
    if (esp8266.available()) {
      if (esp8266.find("+IPD,0,")) {
        delay(10);
        esp8266.find(":");
        delay(10);
        char letter = esp8266.read();
        Serial.print(letter); //for monitoring purposes
        //Gets the value/char from android app
      }
    }

    // parse incoming command start flag

    if (getChar != serialChar) return; // if no command start flag, return to
loop().

    // parse incoming pin# and value
    sensorType = Serial.parseInt(); // read sensor typr
    logCount = Serial.parseInt();  // read total logged sensor readings
    value0 = Serial.parseFloat();  // 1st sensor value
    value1 = Serial.parseFloat();  // 2rd sensor value if exists
    value2 = Serial.parseFloat();  // 3rd sensor value if exists

    // send smartphone readings to serial monitor/terminal
    if (DEBUG) {
      Serial.print("Sensor type: ");
      Serial.println(sensorType);
      Serial.print("Sensor log#: ");
      Serial.println(logCount);
      Serial.print("Val[0]: ");
      Serial.println(value0);
      Serial.print("Val[1]: ");
      Serial.println(value1);
      Serial.print("Val[2]: ");
      Serial.println(value2);
      Serial.println("-----------------------");
      delay(10);
    }

    // Check sensor type. If not for  Accelerometer (#1) then ignore readings
    // sensorType 1 is the Accelerometer sensor

  if (sensorType !=1) return;

  panVal = value0; // value0 = X sensor reading
  tiltVal = value1;  // value1 = Y sensor reading

  tiltVal = map(tiltVal, 10, -10, 0, 179);   // Map Accelerometer Y value to
tilt servo angle.
  servoTilt.write(tiltVal);
  delay(10);

  panVal = map(panVal, -10, 10, 0, 179);  // Map Accelerometer X value to pan
servo angle.
  servoPan.write(panVal);
  delay(10);
}

String sendCommand(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command); // send the read character to the esp8266
  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;
}

```

# Answer
In the `loop` function you have a line

```
If (Serial.available() < 1) return;

```

This prevents further code to be processed if there is nothing in the hardware serial buffer. Think about that.
> 2 votes

---
Tags: arduino-uno, accelerometer, android, gyroscope
---


title: nRF24L01 not communicating

text:
# Question
Title: nRF24L01 not communicating
I have been using two nRF24L01 to communicate with each other using a simple Arduino Uno Board. It worked for 5 days and now all of a sudden it is now working. I tried to change the modules and the Arduino boards too, but even if trying a simple example the communication between them is not happening.

I googled everything and tried every option, it is not working.

I used `printDetails()` to check the config of the modules. It shows everything is ok but I am not able to understand if the transmitter or the receiver is the problem. Please guide me to solve this problem. Also how to make sure if both are working (any debugging technique)?

I have been trying it for 9 days now, and I badly want it to work.

The code I am using is very simple code. It doesn't have any errors.

Receiver code:

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String response;
boolean done = false;

void setup() {
  delay(500);
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.openReadingPipe(0,0xF0F0F0F0AA);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&response, sizeof(response));
    done = true;
  }
  if (done) {
    Serial.println(response);
  }
  done = false;
  delay(1000);
}

```

Sender code:

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String request;

void setup() {
  delay(500);
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(0xF0F0F0F0AA);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  while (Serial.available() > 0) {
    request = Serial.readString();
    Serial.println(request);
    radio.write(&request, sizeof(request));
    delay(1000);
  }
}

```

# Answer
> 1 votes
Hello,
You need to set a channel to both NRF:

```
void setup() {
   delay(500);
   Serial.begin(9600);
   radio.begin();
   radio.setChannel(0x55); //set the channel
   radio.openWritingPipe(0xF0F0F0F0AA);
   radio.setPALevel(RF24_PA_MIN);
   radio.stopListening();
   radio.powerUp(); //Power up the radio
}

```

Change this.

```
void loop() {
    if (radio.available()) {
        radio.read(&response, sizeof(response));
        done = true;
    }
    if (done) {
        Serial.println(response);
        done = false;
    }
    //done = false;
    delay(1000);
}

```

# Answer
> 0 votes
Maybe you should check your power supply. If it worked for 5 days, then it should be ok with your boards and module. If it don't work anymore it could be broken board, broken module or power supply.

---
Tags: arduino-uno, nrf24l01+
---


title: DHT22 Hanging Up Entire Program

text:
# Question
Title: DHT22 Hanging Up Entire Program
In the process of learning and working on a larger project, I started by adding an `OLED` display (128x64, `SPI`). I wrote a simple script to update every 5 seconds and then display the number of seconds on both the `OLED` and the Serial port. This worked just fine and I even let it run for more than a day. Then I added a `DHT22`. This is where the issues started coming in. The `Arduino` `Mega` (clone) is powering both devices. I have a 10K resistor across the VCC and signal pins of the `DHT22`. The code should now update both the `OLED` and the serial port with the number of seconds and the temperature and humidity. This works, for awhile, and then the whole program freezes for some odd reason. The time before freezing is also at random intervals.

During my research it was suggested to add a 10uF capacitor across the ground and VCC. So I added a 10uF 50v cap and the results are still the same. Originally I had Serial.println(String(..... in the code, but I replaced all that to not use String(). I tried adding Serial.flush() at the end of the display code, but equal results.

Additional research also suggested waiting 30 seconds before trying to read the DHT22. I added this 30 second wait at the end of the setup function, but same results. I've tried checking for NaN, not checking for NaN and nothing has seemed to correct this issue.

I've also tried the program without the OLED. Same results. I've tried the program without the Serial output, but same results.

What is going on here and does anyone have any suggestions as to how to correct this?

Currently this whole thing is rigged up on a breadboard if that helps.

Below is the current code I'm trying:

```
#include <Arduino.h>

#include <SPI.h>
#include <Wire.h>

#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// Adafruit Libraries for the OLED display
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// Setup the OLED variables
#define OLED_MOSI   9 // D1 on the OLED
#define OLED_CLK   10 // D0 on the OLED
#define OLED_DC    11 // DC on the OLED
#define OLED_CS    12 // CS on the OLED
#define OLED_RESET 13 // RES on the OLED
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// Global variables
unsigned long currentMillis;
long previousMillis = 0;
#define interval 5000

float humidity;
float fahrenheit;

void setup(){
  // Start the serial port transmission
  Serial.begin(9600);

  // Start the OLED
  display.begin(SSD1306_SWITCHCAPVCC);

  dht.begin();

  // Clear the memory of the OLED
  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(1,0);
  display.println("Madgayrah");
  display.display();

  while(millis()<2000);

  display.setCursor(0,16);
  display.println("Arduino");
  display.display();

  while(millis()<5000);
//  while(millis()<30000);

  Serial.println("");
  display.clearDisplay();
}

void loop() {
  currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    poll_and_display(currentMillis);
  }
}

void poll_and_display(long currentMillis){
    read_dht22();

    Serial.println(previousMillis/1000);

    if(!isnan(humidity) && !isnan(fahrenheit)){
      Serial.print(fahrenheit, 1);
      Serial.print("* ");
      Serial.print(humidity, 0);
      Serial.println("%");
    }

    display.clearDisplay();

    display.setCursor(0,0);
    display.println(currentMillis/1000);
    if(!isnan(humidity) && !isnan(fahrenheit)){
      display.setCursor(0,16);
      display.print(fahrenheit, 1);
      display.print("* ");
      display.print(humidity, 0);
      display.print("%");
    }
    display.display();

    Serial.println("");

    Serial.flush();
}

void read_dht22(){
    humidity = dht.readHumidity();
    fahrenheit = dht.readTemperature(true);

//    while (isnan(humidity) || isnan(fahrenheit)) {
//      unsigned long tempEnteredMillis = millis();
//      while (millis() - tempEnteredMillis < 2500);
//
//      humidity = dht.readHumidity();
//      fahrenheit = dht.readTemperature(true);
//
//      Serial.print("Result from NaN loop = ");
//      Serial.print(fahrenheit, 1);
//      Serial.print("* ");
//      Serial.print(humidity, 0);
//      Serial.println("%");
//    }
}

```

**UPDATE:** After continuing to research on this I discovered that `Arduino` has a Watchdog Timer, or at least SHOULD have, and this SHOULD detect hang ups and restart the `Arduino`. So I tried a hardware version of the Watchdog Timer and a software version, but neither one seemed to work and/or correct the hang up/freeze issue. Below are the links I used for the software and hardware versions.

https://circuits4you.com/2018/01/24/tutorial-on-arduino-watchdog-timer-setup/

https://blog.frogslayer.com/creating-an-arduino-watchdog-timer/

I then ran across another post about a different solution that I have implemented and it seems to be working, but I want to give it some more time just to be sure. More updates to come.

# Answer
> 1 votes
Here is the solution. After searching last night I ran across this post https://forum.arduino.cc/index.php?topic=517608.new . Turns out, I was using the `Adafruit` DHT library and that seems to be what the issue was. I switched over to this https://github.com/markruys/arduino-DHT DHT library and it's been running for some 14 hours now with NO issues. Looking back through the Serial output I don't even see where it returned a NaN, not even once. I'm so excited to have this corrected and hopefully this will help out someone else stuck with this problem.

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


# Question
Title: Need help optimizing snake game code for Arduino Nano
Here's the code:

https://pastebin.com/ypWe4NZw

This is the output when I compile:

Sketch uses 13086 bytes (42%) of program storage space. Maximum is 30720 bytes. Global variables use 1456 bytes (71%) of dynamic memory, leaving 592 bytes for local variables. Maximum is 2048 bytes.

Everything runs smoothly until getNextFood(), Line 194. I try to make a LinkedList of integers from 0 to 255 (since I am using a 16x16 LED grid). However, my list only fills up to about 39, then the rest are set to zero. I suspected that I was out of memory, so I tried optimizing a few things and was able to get to 42. I changed all the ints to bytes in the getNextFood function and got up to 61, but that broke my program somehow (inf loop).

Any suggestions on how to fix this? If I can get this list to fit, the program is basically done, I have nothing else to add assuming it works as intended.

Also, why I am running out of RAM in the first place? Can someone explain which parts of the program are gobbling up those bytes during runtime (because I would expect the integer list to take up around 512 bytes leaving 80 bytes left, so why I am getting cut off around 40 integers or 80 bytes?)

Thanks.

Edit1: People have pointed out that linked lists take up a lot of space. I am using this library because the way the program is designed, I needed to make an array that could change size. I needed to be able to add and remove elements. Maybe there is a better way to do it, I don't know. I thought about making a single 16x16 array for the whole thing and using a different number for each type of piece. I don't know how I would do the snake movement in that case though, because each piece is "connected" to the one in front of it. If anyone knows of a similar library that would save space I'd be happy to try it. Also there might be a way for me to avoid using the tempSnake list.

Edit2: Per Paul's suggestion, I rewrote the code using a single 16x16 array to represent the entire game board, removing the need for LinkedList. However, it seems I am still falling short, unless there is something else wrong with my code. The program resets when I try to generate the food tiles. https://pastebin.com/ZU4hX477

# Answer
16x16 = 256

So there are 256 possible places to put a piece of snake. The max length of the snake will be 256 (fill the board completely).

So if we take an array of bytes (0-255) that is 256 bytes long we could completely map the snake.

Every step you move (unless if the snake just ate some food) you put it's head forward one step, and remove the last part.

So if we make the new head the value of "snakeLength" and do each piece of the body -1 every round. We will get this "decaying" effect.

For example:

```
[ 6][5][4] (all -1, head down) [ 5][4][3]
[ 0][0][3]                     [ 6][0][2]
[ 0][1][2]                     [ 0][0][1]

```

This probably isn't the most efficient method (especially not if you scale it up), but in this case the logic would be very easy.

If the head collides with a position that is not 0, it'll be game over. For the food/apple you could use an x/y value.

If a space is not 0, do it -1.

The upside of this is that you don't allocate memory runtime and you know exactly how many you use. This setup should also make it easier for you to avoid "copying" the whole list all the time, you can basically loop through the array and do -1 for all but those who are 0.
> 3 votes

---
Tags: arduino-nano, code-optimization
---


title: Arduino variables loaded from SD card

text:
# Question
Title: Arduino variables loaded from SD card
I am trying to load some variables from an SD card on the start up of my arduino Uno. I have been given some advice but am unable to communicate at the same hours. Using this advice, I have the following edited code, but it doesn't work and I believe that it's my implementation that is the problem. All help would be greatly appreciated.

```
myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
        while (myFile.available()) {
            myFile.read();

            km = myFile.parseInt();
            kmTemp = myFile.parseFloat();
            kmrevs = myFile.parseInt();
            miles = myFile.parseInt();
            milesTemp = myFile.parseFloat();
            milesrevs = myFile.parseInt();

            }
        myFile.close();
        }
    else {
        Serial.println("Read Error");
    }

```

# Answer
in you previous question, where I answered, you had no commas or new-lines in the example file content. the parseInt and parseFloat ignores only spaces by default.

remove the commas or read them or ignore them with parseInt parameter SKIP\_ALL

```
km = myFile.parseInt(SKIP_ALL);

```
> 1 votes

---
Tags: arduino-uno, c++, sd-card, variables, data-type
---