title: How to read and write EEPROM in ESP8266

text:
# Question
Title: How to read and write EEPROM in ESP8266
I need to know how I can write integer values in EEPROM and retain the value on power on.

```
char *Red = strstr(myTestUrl, "/R");
if (Red) {
  int RedValue  = atoi(Red + 2);
  analogWrite(12, RedValue);
  Serial.println("Red :");
  Serial.println(RedValue);
}

```

I want to write `RedValue` in EEPROM. How can it be done?

# Answer
While `EEPROM.read` and `EEPROM.write` are valid methods, it's like mopping the floor with a toothbrush. Use `EEPROM.put` and `EEPROM.get` instead.

For example:

```
#include <EEPROM.h>

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

  uint addr = 0;

  // fake data
  struct {
    uint val = 0;
    char str[20] = "";
  } data;

  // commit 512 bytes of ESP8266 flash (for "EEPROM" emulation)
  // this step actually loads the content (512 bytes) of flash into
  // a 512-byte-array cache in RAM
  EEPROM.begin(512);

  // read bytes (i.e. sizeof(data) from "EEPROM"),
  // in reality, reads from byte-array cache
  // cast bytes into structure called data
  EEPROM.get(addr,data);
  Serial.println("Old values are: "+String(data.val)+","+String(data.str));

  // fiddle with the data "read" from EEPROM
  data.val += 5;
  if ( strcmp(data.str,"hello") == 0 )
      strncpy(data.str, "jerry",20);
  else
      strncpy(data.str, "hello",20);

  // replace values in byte-array cache with modified data
  // no changes made to flash, all in local byte-array cache
  EEPROM.put(addr,data);

  // actually write the content of byte-array cache to
  // hardware flash.  flash write occurs if and only if one or more byte
  // in byte-array cache has been changed, but if so, ALL 512 bytes are
  // written to flash
  EEPROM.commit();

  // clear 'data' structure
  data.val = 0;
  strncpy(data.str,"",20);

  // reload data for EEPROM, see the change
  //   OOPS, not actually reading flash, but reading byte-array cache (in RAM),
  //   power cycle ESP8266 to really see the flash/"EEPROM" updated
  EEPROM.get(addr,data);
  Serial.println("New values are: "+String(data.val)+","+String(data.str));
}

void loop()
{
  delay(1000);
}

```

**UPDATE**: If you want to understand how the "EEPROM" is emulated in the ESP8266, you might want to reference https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM, specifically, `EEPROM.h`.

Also, `EEPROM.end` is not needed, it simply clears the local byte-array cache of the flash/EEPROM from RAM. It serves on other function.
> 36 votes

# Answer
`EEPROM.write(pos, val)` writes one byte (`val`) at the address giving by `pos`. An "int" in ESP8266 takes 4 bytes, so it's a little more complicated, because EEPROM works in bytes, not ints.

Here is a code for writing one int `val` at some position `pos` in the EEPROM:

```
void eeWriteInt(int pos, int val) {
    byte* p = (byte*) &val;
    EEPROM.write(pos, *p);
    EEPROM.write(pos + 1, *(p + 1));
    EEPROM.write(pos + 2, *(p + 2));
    EEPROM.write(pos + 3, *(p + 3));
    EEPROM.commit();
}

```

and, of course, you need to read it back:

```
int eeGetInt(int pos) {
  int val;
  byte* p = (byte*) &val;
  *p        = EEPROM.read(pos);
  *(p + 1)  = EEPROM.read(pos + 1);
  *(p + 2)  = EEPROM.read(pos + 2);
  *(p + 3)  = EEPROM.read(pos + 3);
  return val;
}

```

In Arduino you call `EEPROM.begin()`, but in ESP8266 you have to call `EEPROM.begin(n)`, where `n` is the total number of bytes you will need.

And remember that EEPROM have a short life span (by number of writes). You must minimize the number of writes!

EEPROM is permanent; you don't need to do nothing.
> 10 votes

# Answer
Method using the number of letters.

```
#include <ESP8266WiFi.h>

const char* SSID = "R360"; //MAX 32
const char* PASSWORD = "HFDYUK64323246"; //MAX 32

#include <EEPROM.h>

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

  EEPROM_ESP8266_GRABAR(SSID, 0); //Primero de 0 al 32, del 32 al 64, etc
  EEPROM_ESP8266_GRABAR(PASSWORD, 32); //SAVE

  Serial.println();
  Serial.println(EEPROM_ESP8266_LEER(0, 32));//Primero de 0 al 32, del 32 al 64, etc
  Serial.println(EEPROM_ESP8266_LEER(32, 64));

  WiFi.begin(EEPROM_ESP8266_LEER(0,32).c_str(), EEPROM_ESP8266_LEER(32,64).c_str());

}
//
void loop() {}
//
void EEPROM_ESP8266_GRABAR(String buffer, int N) {
  EEPROM.begin(512); delay(10);
  for (int L = 0; L < 32; ++L) {
    EEPROM.write(N + L, buffer[L]);
  }
  EEPROM.commit();
}
//
String EEPROM_ESP8266_LEER(int min, int max) {
  EEPROM.begin(512); delay(10); String buffer;
  for (int L = min; L < max; ++L)
    if (isAlphaNumeric(EEPROM.read(L)))
      buffer += char(EEPROM.read(L));
  return buffer;
}

```
> 2 votes

# Answer
Use `#include <EEPROM.h>`

```
EEPROM.begin(size); //Size can be anywhere between 4 and 4096 bytes.
EEPROM.write(0, RedValue);   // To store in 0th Location
EEPROM.commit();

```
> 0 votes

# Answer
I use 2 separate functions in my code on ESP8266 - one with `EEPROM.put()`, one with `EEPROM.get()`.

I had `EEPROM.begin(sizeof...);` only in `EEPROM.put()` function and `put` worked. But it took me quite a while, until I found out, that it must be used before `EEPROM.get()` as well.
> 0 votes

---
Tags: arduino-ide, esp8266, eeprom
---


# Question
Title: Arduino library creation - Calling library and Merging
I am new to creating a library in Arduino. I was able to create a library from YouTube. I want to merge two other libraries into the library I created. Can you please help me to do so?

I already created a keywords.txt file for my library but the keywords are not getting highlighted in orange in the IDE. But it identifies as keywords.

Please guide me how to properly create a keywords file and merge the libraries.

Keywords below:

```
# -----------------------------------------------------------------------------------
# Syntax coloring for IotBlueEmon library
# -----------------------------------------------------------------------------------

# Datatypes (such as objects)
CurrentSense KEYWORD1

#Methods / functions
begin   KEYWORD2
Counter1   KEYWORD2
Counter2   KEYWORD2
counter3   KEYWORD2
getCNT1   KEYWORD2
getCNT2   KEYWORD2
getCNT3   KEYWORD2

# Constants

```

# Answer
> 1 votes
If you consult the Arduino Library Specification's section on keywords.txt:

> A tab should be used to separate each name from the KEYWORD1/Keyword2/Literal1 identifier.

A true tab character is required, rather than spaces, as you have in your keywords.txt. It is common for text editors to be configured to add a given number of spaces when the tab key is pressed rather than a true tab character. That's great but in this case you will need to be sure that the tab character is used.

Note that the tab requirement will be relaxed in the Arduino IDE 1.9.0 release, which will also accept space(s) as a keywords separator but it's still best to use tabs for backwards compatibility since people will be using pre-1.9.0 IDE versions for years to come.

---
Tags: library
---


# Question
Title: Platform-independent functions for FastPWM?
I learned from answers here that `pinMode(0, OUTPUT)` is a platform-independent equivalent of `DDRB = 1<<DDB0`, on the ATTiny85.

Are there platform-independent functions for the following?

```
TCCR0A = 2<<COM0A0 | 2<<COM0B0 | 3<<WGM00;
TCCR0B = 0<<WGM02 | 1<<CS00;
TCCR1 = 0<<PWM1A | 0<<COM1A0 | 1<<CS10;
GTCCR = 1<<PWM1B | 2<<COM1B0;

```

Explanation of above code here. These calls enable FastPWM.

I checked the Arduino API reference, but not sure which are the equivalent to above. How to determine?

# Answer
> 5 votes
It is highly unlikely there would be direct 1:1 functions that implement such discrete operations. Simply because such operations are pretty unique to a single family of microcontrollers. They are too low-level for an API to even consider wanting them.

Instead, there are higher level functions which may, if the chip requires it, include those operations.

The operations you list are all related to PWM, so the higher level function that would encompass them would be `analogWrite()`.

---
Tags: pwm
---


# Question
Title: Can't fetch data from server using arduino and esp8266
I am trying to fetch some data from my website using esp8266 and Arduino, with the help of WiFiEsp library, I have got data from the website but don't know how to save that data in an array or variable and use it, now I can only see received data on the serial monitor.

```
 #include "WiFiEsp.h"

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "moto g";            // your network SSID (name)
char pass[] = "hvats555";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "himalayavats.com";

unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 10000L;

WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");

  printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial
port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
   client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /to_fetch/system_info.json HTTP/1.1"));
    client.println(F("Host: himalayavats.com"));
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

 // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

**Response from arduino(in serial monitor):-**

```
[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network
SSID: moto g
IP Address: 192.168.43.61
Signal strength (RSSI):-372 dBm

[WiFiEsp] Connecting to himalayavats.com
Connecting...
HTTP/1.1 200 OK
Date: Fri, 05 Jan 2018 10:19:46 GMT
Server: Apache
ETag: "12c077d-12-55dc4cfa4fffd"
Accept-Ranges: bytes
Content-Length: 18
Vary: User-Agent
Connection: close
Content-Type: application/json

{"power" : "high"}      // <-- i wanna fetch this

```

**NOTE:- Whenever I try to add anything in loop function for example:-**

```
int i = 0;
while(client.avilable()){
    c = client.read();
    serverResponse[i] = c; // trying to save output in an array
    i++;
}

```

**The module doesn't even fetch data from the server it keeps restarting itself. Output from arduino after adding above code in loop funtion:-**

```
[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network

[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network

[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 1.3.0
Attempting to connect to WPA SSID: moto g
[WiFiEsp] Connected to moto g
You're connected to the network

```

This repeating again and again

# Answer
> 1 votes
When Arduinos unexpectedly restarts it is usually because you have drawn too much power or have caused a segmentation error or BSOD in Windows terms. You aren't drawing to much power, so I suspect you are accessing elements of the array outside those that you should be. Check that `i` never exceeds the maximum size of serverResponse, because:

```
char serverResonse[10]
for int i - 0; i < 50; i++)
  serverResponse[i] = 42;  // This will crash on the 11th loop.

```

I can't say if the above code will cause a restart, but that's dependent on what was using the 11th byte of the array before it got stomped on.

---
Tags: arduino-uno, esp8266
---


title: What is wrong with my state machines?

text:
# Question
Title: What is wrong with my state machines?
My goal is to make an automatic gate and garage door, and it has a servo as the lock mechanism on the gate, and alarm systems that notify when the gate or garage door is open too long, more than the interval (in my case 10 seconds) through a buzzer.

It also uses:

* Bluetooth to send a command (which is `readChar`) to open/close the gate and open/close the garage.
* 4 limit switches (2 switched located at both end of gate and garage to stop its movement).

I want that the gate and garage doors can be opened/closed at the same time, so there are 2 state machines. And the alarm system (if it is activated) will stop when the gate reaches limit switch 1, and the garage reaches limit switch 3.

However with my current code (compiled), I get:

* The first state machine (stateGate) can open and close the gate, but the buzzer does not buzz when it exceeds the limit.
* The second state machine (stateGarage) did not do anything/did not operate.

Can someone point out/correct what is the mistake? Because I can't seem to find what is wrong. Thank you in advance!

Here is my current full code:

```
#include <Servo.h>

Servo Servokey;

// Motor for Gate (MotorA)
const byte IN1 = 9;
const byte IN2 = 8;
const byte EnableMotorA = 6;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 3;
const byte EnableMotorB = 5;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

int StateGate;
int StateGarage;
boolean gateClosed = false;
boolean garageClosed = false;

unsigned long GateMillis; //will hold the timer for Gate
unsigned long GarageMillis; // will hold the timer for Garage
unsigned long interval = 10000;

void setup() {
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(EnableMotorA, OUTPUT);

  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(EnableMotorB, OUTPUT);

  pinMode(LimitSwitch1, INPUT);
  pinMode(LimitSwitch2, INPUT);
  pinMode(LimitSwitch3, INPUT);
  pinMode(LimitSwitch4, INPUT);

  Servokey.attach(11); // lock mechanism for Gate
  Servokey.write(70);

  unsigned long GateMillis = 0; //will hold the timer for Gate
  unsigned long GarageMillis = 0;

  Serial.begin(9600);
}

void loop() {
  byte readChar = 0;
  if (Serial.available() > 0)
    readChar = Serial.read();
  stateGate(readChar);
  stateGarage(readChar);
}

void stateGate(byte readChar) {
  static enum { StateGate_Idle, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Close, StateGate_Alarm} StateGate;
  switch (StateGate) {
    case StateGate_Idle:
      { // If we received a valid command, start the operation
        if (readChar > 0) {
          switch (readChar) {
            case 'A':
              StateGate = StateGate_Opening;
              break;
            case 'B':
              StateGate = StateGate_Closing;
              break;
            default:
              // Here you can notify that there was a bad command
              break;
          }
        }
      }
      break;
    case StateGate_Opening:
      Servokey.write(140);
      delay(50);
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      analogWrite(EnableMotorA, 250);
      StateGate = StateGate_Open;
      break;
    case StateGate_Open:
      if (digitalRead(LimitSwitch2)) {
        digitalWrite(IN1, LOW);
        digitalWrite(IN2, LOW);
        analogWrite(EnableMotorA, 0);
        GateMillis = millis();
        gateClosed = false;
        StateGate = StateGate_Idle;
      }
      break;
    case StateGate_Closing:
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      analogWrite(EnableMotorA, 250);
      StateGate = StateGate_Close;
      break;
    case StateGate_Close:
      if (digitalRead(LimitSwitch1)) {
        digitalWrite(IN1, LOW);
        digitalWrite(IN2, LOW);
        analogWrite(EnableMotorA, 0);
        Servokey.write(70);
        delay(50);
        gateClosed = true;
        StateGate = StateGate_Idle;
      }
      break;
    case StateGate_Alarm:
      if ((millis() - GateMillis) > interval && gateClosed == false) {
        tone(piezoPin, 5000);
        StateGate = StateGate_Idle;
      } else if (gateClosed == true) {
        StateGate = StateGate_Idle;
      }
      break;
    default:
      StateGate = StateGate_Idle;
      break;
  }
}

void stateGarage(byte readChar) {
  static enum { StateGarage_Idle, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Close, StateGarage_Alarm} StateGarage;
  switch (StateGarage) {
    case StateGarage_Idle:
      { // If we received a valid command, start the operation
        if (readChar > 0) {
          switch (readChar) {
            case 'C':
              StateGarage = StateGarage_Opening;
              break;
            case 'D':
              StateGarage = StateGarage_Closing;
              break;
            default:
              // Here you can notify that there was a bad command
              break;
          }
        }
      }
      break;
    case StateGarage_Opening:
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      analogWrite(EnableMotorA, 250);
      StateGarage = StateGarage_Open;
      break;
    case StateGarage_Open:
      if (digitalRead(LimitSwitch4)) {
        digitalWrite(IN3, LOW);
        digitalWrite(IN4, LOW);
        analogWrite(EnableMotorA, 0);
        GarageMillis = millis();
        garageClosed = false;
        StateGarage = StateGarage_Idle;
      }
      break;
    case StateGarage_Closing:
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      analogWrite(EnableMotorA, 250);
      StateGarage = StateGarage_Close;
      break;
    case StateGarage_Close:
      if (digitalRead(LimitSwitch3)) {
        digitalWrite(IN3, LOW);
        digitalWrite(IN4, LOW);
        analogWrite(EnableMotorB, 0);
        garageClosed = true;
        StateGarage = StateGarage_Idle;
      }
      break;
    case StateGarage_Alarm:
      if ((millis() - GarageMillis) > interval && garageClosed == false) {
        tone(piezoPin, 5500);
        StateGarage = StateGarage_Idle;
      } else if (garageClosed == true)
        StateGarage = StateGarage_Idle;
      break;
    default:
      StateGarage = StateGarage_Idle;
      break;
  }
}

```

I made another code like what @CodeGorilla had suggested, however it turned out that both state machines did not operate.... I think I am still missed out something

Here's the other code:

```
#include <Servo.h>

Servo Servokey;

enum StateGate { StateGate_Idle = 0, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Closed, StateGate_Alarm, StateGate_Last };
enum StateGarage { StateGarage_Idle = 0, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Closed, StateGarage_Alarm, StateGarage_Last };

struct Data1
{
  byte IN1;
  byte IN2;
  bool Enable;
  int NextState;

  Data1(byte in1, byte in2, bool enable, int nextstate)
       :IN1(in1), IN2(in2), Enable(enable), NextState(nextstate)
  {}
};

struct Data2
{
  byte IN3;
  byte IN4;
  bool Enable;
  int NextState;

  Data2(byte in3, byte in4, bool enable, int nextstate)
       :IN3(in3), IN4(in4), Enable(enable), NextState(nextstate)
  {}
};

struct MotorData1
{
  byte IN1;
  byte IN2;
  byte Enable;
  MotorData1(byte i1, byte i2, byte enable)
       : IN1(i1), IN2(i2), Enable(enable)
  {}
  void pinMode() const
  {
    :: pinMode(IN1, OUTPUT);
    :: pinMode (IN2, OUTPUT);
    :: pinMode (Enable, OUTPUT);
  }
  int Set(const Data1& data1) const
  {// Set the motors to the given state
    digitalWrite(IN1, data1.IN1);
    digitalWrite(IN2, data1.IN2);
    analogWrite(Enable, data1.Enable?250:0);
    return data1.NextState;
  }
};

struct MotorData2
{
  byte IN3;
  byte IN4;
  byte Enable;
  MotorData2(byte i3, byte i4, byte enable)
       : IN3(i3), IN4(i4), Enable(enable)
  {}
  void pinMode() const
  {
    :: pinMode(IN3, OUTPUT);
    :: pinMode (IN4, OUTPUT);
    :: pinMode (Enable, OUTPUT);
  }
  int Set(const Data2& data2) const
  {// Set the motors to the given state
    digitalWrite(IN3, data2.IN3);
    digitalWrite(IN4, data2.IN4);
    analogWrite(Enable, data2.Enable?250:0);
    return data2.NextState;
  }
};
// Define the motors
const MotorData1 MotorsA(9, 8, 6);
const MotorData2 MotorsB(4, 3, 5);

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

StateGate CurrentGateState = StateGate_Idle;
StateGarage CurrentGarageState = StateGarage_Idle;
boolean gateClosed = false;
boolean garageClosed = false;

unsigned long GateMillis(0); //will hold the timer for Gate
unsigned long GarageMillis(0); // will hold the timer for Garage
unsigned long interval = 10000;

void setup() {
    MotorsA.pinMode();
    MotorsB.pinMode();

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Servokey.attach(11); // lock mechanism for Gate
    Servokey.write(70);

    Serial.begin(9600);
}

void loop()
{
    byte readChar = 0;
    if (Serial.available() > 0)
        readChar = Serial.read();
    stateGate(readChar);
    stateGarage(readChar);
}

void stateGate(byte readChar)
{// Define the state machine
    static const Data1 stateData1[StateGate_Last] =
    {
          Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Idle
        , Data1(LOW, HIGH, true, StateGate_Open)  // StateGate_Opening
        , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Open
        , Data1(HIGH, LOW, false, StateGate_Closed)  // StateGate_Closing
        , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Closed
        , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Alarm
    };
switch (CurrentGateState)
    {
        case StateGate_Idle:
        { // If we received a valid command, start the operation
            if (readChar > 0) {
                switch (readChar) {
                case 'A':
                    if (CurrentGateState != StateGate_Open)
                    {  // Prevent opening the gate if its already open
                        CurrentGateState = StateGate_Opening;
                    }
                    break;
                case 'B':
                    if (CurrentGateState != StateGate_Closed)
                    {// Prevent closing the gate if its already closed.
                        CurrentGateState = StateGate_Closing;
                    }
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateGate_Opening:
        Servokey.write(140);
        delay(50);
        CurrentGateState = MotorsA.Set(stateData1[StateGate_Opening]);
        break;
    case StateGate_Open:
        if (digitalRead(LimitSwitch2))
        {
            CurrentGateState = MotorsA.Set(stateData1[StateGate_Open]);
            GateMillis = millis();
            gateClosed = false;
        }
        break;
    case StateGate_Closing:
        CurrentGateState = MotorsA.Set(stateData1[StateGate_Closing]);
        break;
    case StateGate_Closed:
        if (digitalRead(LimitSwitch1))
        {
            CurrentGateState = MotorsA.Set(stateData1[StateGate_Closed]);
            Servokey.write(70);
            delay(50);
            gateClosed = true;
        }
        break;
    case StateGate_Alarm:
        if ((millis() - GateMillis) > interval && gateClosed == false) {
            tone(piezoPin, 5000);
            CurrentGateState = StateGate_Idle;
        }
        else if (gateClosed == true) {
            CurrentGateState = StateGate_Idle;
        }
        break;
    default:
        CurrentGateState = StateGate_Idle;
        break;
    }
}

void stateGarage(byte readChar)
{// Define the state machine
    static const Data2 stateData2[StateGarage_Last] =
    {
          Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Idle
        , Data2(LOW, HIGH, true, StateGarage_Open)  // StateGate_Opening
        , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Open
        , Data2(HIGH, LOW, false, StateGarage_Closed)  // StateGate_Closing
        , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Closed
        , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Alarm
    };
switch (CurrentGarageState)
    {
        case StateGarage_Idle:
        { // If we received a valid command, start the operation
            if (readChar > 0) {
                switch (readChar) {
                case 'A':
                    if (CurrentGarageState != StateGarage_Open)
                    {  // Prevent opening the gate if its already open
                        CurrentGarageState = StateGarage_Opening;
                    }
                    break;
                case 'B':
                    if (CurrentGarageState != StateGarage_Closed)
                    {// Prevent closing the gate if its already closed.
                        CurrentGarageState = StateGarage_Closing;
                    }
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateGarage_Opening:
        CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Opening]);
        break;
    case StateGarage_Open:
        if (digitalRead(LimitSwitch2))
        {
            CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Open]);
            GarageMillis = millis();
            garageClosed = false;
        }
        break;
    case StateGarage_Closing:
        CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Closing]);
        break;
    case StateGarage_Closed:
        if (digitalRead(LimitSwitch1))
        {
            CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Closed]);
            Servokey.write(70);
            delay(50);
            garageClosed = true;
        }
        break;
    case StateGarage_Alarm:
        if ((millis() - GarageMillis) > interval && garageClosed == false) {
            tone(piezoPin, 5000);
            CurrentGarageState = StateGarage_Idle;
        }
        else if (garageClosed == true) {
            CurrentGarageState = StateGarage_Idle;
        }
        break;
    default:
        CurrentGarageState = StateGarage_Idle;
        break;
    }
}

```

# Answer
There a couple of places where you define variables which hide other variables. eg Line 27 is hidden by 48 for a little bit. More importantly line 22 is hidden by 63 and this is probably why your state machine doesn't work.

As I said in my comment you could make life easier for yourself by refactoring it. Most of the states have the same lines of code in, so by using a structure you can reduce the number of lines and hopefully the number of bugs. I had a play a roughed out this to show what I mean. (I have not compiled it, let alone run it, but it might be a starting point.

```
Servo Servokey;
// Global to prevent accidental variable declaration.
static enum StateGate { StateGate_Idle = 0, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Closed, StateGate_Alarm, StateGate_Last };
// Defines the state machines
struct Data
{
    byte IN1;
    byte IN2;
    bool Enable;
    int NextState;

    Data(byte in1, byte in2, bool enable, int nextState)
        : IN1(in1), IN2(in2), Enable(enable), NextState(nextState))
    {}
};
// Group the motor data to make things tidier
struct MotorData
{
    byte IN1;
    byte IN2;
    byte Enable;
    MotorData(byte i1, byte i2, byte enable)
        :IN1(i1), IN2(i2), Enable(enable)
    {}
    void pinMode() const  // Set the pin mode
    {
        ::pinMode(IN1, OUTPUT);  // Use the global pinMode not this function
        ::pinMode(IN2, OUTPUT);
        ::pinMode(Enable, OUTPUT);
    }
    int Set(const Data& data) const
    { // Set the motors to the given state
        digitalWrite(IN1, data.IN1);
        digitalWrite(IN2, data.IN2);
        analogWrite(Enable, data.Enable?250:0);
        return data.NextState
    }
};
// Define the motors
const MotorData MotorsA(9, 8, 6);
const MotorData MotorsB(4, 3, 5);

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

StateGate CurrentGateState = StateGate_Idle;  // It is best to initialise the variables.
int StateGarage;
boolean gateClosed = false;
boolean garageClosed = false;

unsigned long GateMillis(0); //will hold the timer for Gate
unsigned long GarageMillis(0); // will hold the timer for Garage
unsigned long interval = 10000;

void setup() {
    MotorsA.pinMode();
    MotorsB.pinMode();

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Servokey.attach(11); // lock mechanism for Gate
    Servokey.write(70);

    Serial.begin(9600);
}

void loop()
{
    byte readChar = 0;
    if (Serial.available() > 0)
        readChar = Serial.read();
    stateGate(readChar);
    stateGarage(readChar);
}

void stateGate(byte readChar)
{// Define the state machine
    static const Data stateData[StateGate_Last] =
    {
          Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Idle
        , Data(LOW, HIGH, true, StateGate_Open)  // StateGate_Opening
        , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Open
        , Data(HIGH, LOW, false, StateGate_Closed)  // StateGate_Closing
        , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Closed
        , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Alarm
    };

    switch (CurrentGateState)
    {
        case StateGate_Idle:
        { // If we received a valid command, start the operation
            if (readChar > 0) {
                switch (readChar) {
                case 'A':
                    if (CurrentGateState != StateGate_Open)
                    {  // Prevent opening the gate if its already open
                        CurrentGateState = StateGate_Opening;
                    }
                    break;
                case 'B':
                    if (CurrentGateState != StateGate_Closed)
                    {// Prevent closing the gate if its already closed.
                        CurrentGateState = StateGate_Closing;
                    }
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateGate_Opening:
        Servokey.write(140);
        delay(50);
        CurrentGateState = MotorsA.Set(stateData[StateGate_Opening]);
        break;
    case StateGate_Open:
        if (digitalRead(LimitSwitch2))
        {
            CurrentGateState = MotorsA.Set(stateData[StateGate_Open]);
            GateMillis = millis();
            gateClosed = false;
        }
        break;
    case StateGate_Closing:
        CurrentGateState = MotorsA.Set(stateData[StateGate_Closing]);
        break;
    case StateGate_Closed:
        if (digitalRead(LimitSwitch1))
        {
            CurrentGateState = MotorsA.Set(stateData[StateGate_Closed]);
            Servokey.write(70);
            delay(50);
            gateClosed = true;
        }
        break;
    case StateGate_Alarm:
        if ((millis() - GateMillis) > interval && gateClosed == false) {
            tone(piezoPin, 5000);
            CurrentGateState = StateGate_Idle;
        }
        else if (gateClosed == true) {
            CurrentGateState = StateGate_Idle;
        }
        break;
    default:
        CurrentGateState = StateGate_Idle;
        break;
    }
}

void stateGarage(byte readChar) {
    static enum { StateGarage_Idle, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Close, StateGarage_Alarm } StateGarage;
    switch (StateGarage) {
    case StateGarage_Idle:
    { // If we received a valid command, start the operation
        if (readChar > 0) {
            switch (readChar) {
            case 'C':
                StateGarage = StateGarage_Opening;
                break;
            case 'D':
                StateGarage = StateGarage_Closing;
                break;
            default:
                // Here you can notify that there was a bad command
                break;
            }
        }
    }
    break;
    case StateGarage_Opening:
        digitalWrite(IN3, LOW);
        digitalWrite(IN4, HIGH);
        analogWrite(EnableMotorA, 250);
        StateGarage = StateGarage_Open;
        break;
    case StateGarage_Open:
        if (digitalRead(LimitSwitch4)) {
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorA, 0);
            GarageMillis = millis();
            garageClosed = false;
            StateGarage = StateGarage_Idle;
        }
        break;
    case StateGarage_Closing:
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, LOW);
        analogWrite(EnableMotorA, 250);
        StateGarage = StateGarage_Close;
        break;
    case StateGarage_Close:
        if (digitalRead(LimitSwitch3)) {
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            garageClosed = true;
            StateGarage = StateGarage_Idle;
        }
        break;
    case StateGarage_Alarm:
        if ((millis() - GarageMillis) > interval && garageClosed == false) {
            tone(piezoPin, 5500);
            StateGarage = StateGarage_Idle;
        }
        else if (garageClosed == true)
            StateGarage = StateGarage_Idle;
        break;
    default:
        StateGarage = StateGarage_Idle;
        break;
    }
}

```

EDIT ----------------

This code is a complete version of the code refactored to reduce the repetitive statements and try and minimise the number of potential bugs. I have also removed one of the state functions, since apart form the lock and acting on different motors and switches they seemed to be the same.

```
#include "Servo.h"

Servo Servokey;

enum State { State_Idle = 0, State_Opening, State_Open, State_Closing, State_Closed, State_Alarm, State_Last };

struct Data
{
    byte IN1;
    byte IN2;
    bool Enable;
    State NextState;

    Data(byte in1, byte in2, bool enable, State nextstate)
        :IN1(in1), IN2(in2), Enable(enable), NextState(nextstate)
    {}
};

struct MotorData
{
    byte IN1;
    byte IN2;
    byte Enable;
    MotorData(byte i1, byte i2, byte enable)
        : IN1(i1), IN2(i2), Enable(enable)
    {}
    void pinMode() const
    {
        ::pinMode(IN1, OUTPUT);
        ::pinMode(IN2, OUTPUT);
        ::pinMode(Enable, OUTPUT);
    }
    State Set(const Data& Data) const
    {// Set the motors to the given state
        digitalWrite(IN1, Data.IN1);
        digitalWrite(IN2, Data.IN2);
        analogWrite(Enable, Data.Enable ? 250 : 0);
        return Data.NextState;
    }
};

/// Defines all the data for the gate or garage.
struct Object
{
    State           CurrentState;               // The current state of the object
    char            OpenCommand;                // The command to open the gate/garage
    char            CloseCommand;
    MotorData&      Motors;                     // A reference to the motors object
    byte            LimitSwitchA;
    byte            LimitSwitchB;
    bool            LockObject;                 // True if the object should be locked/ unlocked
    unsigned long   OpenTime;                   // The time the object was last opened.
    bool            IsClosed;                   // True when the object is closed.
    Object(char o, char c, MotorData m, byte la, byte lb, bool lock)
        : CurrentState(State_Idle)
        , OpenCommand(o)
        , CloseCommand(c)
        , Motors(m)
        , LimitSwitchA(la)
        , LimitSwitchB(lb)
        , LockObject(lock)
        , OpenTime(0)
        , IsClosed(false)
    {}
};

// Define the motors
const MotorData MotorsA(9, 8, 6);
const MotorData MotorsB(4, 3, 5);

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

Object Gate('A', 'B', MotorsA, LimitSwitch1, LimitSwitch2, true);
Object Garrage('C', 'D', MotorsB, LimitSwitch3, LimitSwitch4, false);

unsigned long interval = 10000;

/// Lock or unlock the lock.
void LockGate(bool lock=true)
{
    if (lock)
        Servokey.write(70);
    else
        Servokey.write(140);
    delay(50);
}

void setup() {
    MotorsA.pinMode();
    MotorsB.pinMode();

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Servokey.attach(11); // lock mechanism for Gate
    Servokey.write(70);

    Serial.begin(9600);
}

void loop()
{
    byte readChar = 0;
    if (Serial.available() > 0)
        readChar = Serial.read();
    StateMachine(readChar, Gate);
    StateMachine(readChar, Garrage);
}

void StateMachine(const byte readChar, Object& objectData)
{// Define the state machine
    static const Data stateData[State_Last] =
    {
        Data(LOW, LOW, false, State_Idle)  // State_Idle
        , Data(LOW, HIGH, true, State_Open)  // State_Opening
        , Data(LOW, LOW, false, State_Idle)  // State_Open
        , Data(HIGH, LOW, true, State_Closed)  // State_Closing
        , Data(LOW, LOW, false, State_Idle)  // State_Closed
        , Data(LOW, LOW, false, State_Idle)  // State_Alarm
    };
    switch (objectData.CurrentState)
    {
    case State_Idle:                // If we received a valid command, start the operation
        if (readChar > 0)
        {
            if (readChar == objectData.OpenCommand)
            {
                objectData.CurrentState = State_Opening;
            }
            else if (readChar == objectData.CloseCommand)
            {
                objectData.CurrentState = State_Closing;
            }
            else
            {
                // Here you can notify that there was a bad command
            }
        }
        break;
    case State_Opening:
        if (objectData.LockObject)
            LockGate(false);
        objectData.CurrentState = objectData.Motors.Set(stateData[State_Opening]);
        break;
    case State_Open:
        if (digitalRead(LimitSwitch2))
        {
            objectData.CurrentState = objectData.Motors.Set(stateData[State_Open]);
            objectData.OpenTime = millis();
            objectData.IsClosed = false;
        }
        break;
    case State_Closing:
        objectData.CurrentState = objectData.Motors.Set(stateData[State_Closing]);
        break;
    case State_Closed:
        if (digitalRead(LimitSwitch1))
        {
            objectData.CurrentState = objectData.Motors.Set(stateData[State_Closed]);
            if (objectData.LockObject)
                LockGate(true);
            objectData.IsClosed = true;
        }
        break;
    case State_Alarm:
        if ((millis() - objectData.OpenTime) > interval && objectData.IsClosed == false) {
            tone(piezoPin, 5000);
            objectData.CurrentState = State_Idle;
        }
        else if (objectData.IsClosed == true) {
            objectData.CurrentState = State_Idle;
        }
        break;
    default:
        objectData.CurrentState = State_Idle;
        break;
    }
}

```

As before I can't test it, without righting myself a test harness and "it doesn't work" doesn't really help me know what the fault is. One thing I did notice is the Alarm won't work. This is because nothing ever puts it into that state, maybe the check to see if the alarm has been triggered should be in the idle state and if it occurs the state machine should move into the alarm state.

What I have tried to show you is if you are doing the same things repeatedly on different data then define the data outside of the function and reduce the amount of code you write. You would never write these functions would you?

```
int Add2and2 ()
{return 2+2;}
int Add2and3 ()
{return 2+3;}
int Add2and4 ()
{return 2+4;}

```

But its often very difficult to spot that you are doing that in your own code.

If there is still something wrong, please describe what the fault is and I'll see what I can do.
> 1 votes

---
Tags: arduino-uno, motor, millis, switch, buzzer
---


# Question
Title: Reading SMS using Arduino Uno and SIM800L and print on LCD (16x2 alphanumeric) using serial connection NEED HELP
Well, I am making a device, which has to receive SMS and print the text using am LCD display. Now I have code that can receive SMS and store it into a string variable using serial connection. Here is my code:

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

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;  //LCD pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
String Arsp, Grsp;
SoftwareSerial gsm(6,7); // RX, TX

void setup() {
  Serial.begin(9600);
  Serial.println("Testing GSM SIM800L");
  gsm.begin(9600);
  gsm.println("AT"); //checking
  delay(1000);
  gsm.println("AT+CMGF=1");  //Set to Text mode
  delay(1000);
  gsm.println("AT+CNMI=1, 2, 0, 0, 0"); //Set to notification for new message, New message indication
  lcd.begin(16, 2);
}

void loop() {
  if(gsm.available()) {
    //Check if GSM Send any data
    Grsp = gsm.readString(); //Read data received from SIM800L GSM Module
    lcd.clear(); //Clear LCD Screen
    lcd.setCursor(0,0); //Set LCD cursor to First line, first row
    for(int i = 0; i<=100; i++) {
      //Print received string character by character
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(Grsp); //Print string which received from GSM (sms, sender, sms index, receive time, etc)
        lcd.print("        ");
        lcd.print(i); //Print the string index
        delay(500);
    }
  }
}

```

When my Arduino Uno is connected to PC and the Arduino serial monitor is already open, it prints correctly this text received from GSM

```
"  +CMT: "+995599093230","","18/01/05,16:29:57+16"  0.

```

In this case I sent a message with text "0". When I disconnect the USB and connect my Arduino Uno to 9V power supply and send the same message text it prints:

`" +CMTI: "ME", "+995598403536", 40)`

In this case 40 is the index of the message received. I want to get the whole string as in the first case when the USB was connected.

I using Arduino GND and 5V to power the SIM800L. What I am doing wrong? Is this due to incorrect serial connection or incorrect code error?

# Answer
> 1 votes
The PP3 battery you are trying to use is far from powerful enough to run a SIM800L. It's barely powerful enough to run an Arduino by itself for more than a couple of hours if you're lucky.

The SIM800L, as the datasheet tells us, must be powered by a supply which can provide *at least* 2A.

> The power supply range of SIM800L is from 3.4V to 4.4V. Recommended voltage is 4.0V. The transmitting burst will cause voltage drop and the power supply myst be able to provide sufficient current up to 2A.

The Arduino's on-board 5V regulator can't provide more than 800mA if you're lucky (far less if the incoming voltage is more than around 7V due to heat dissipation). Running from USB may allow peaks of up to 2A on a DCP USB socket without the Arduino's PTC fuse blowing.

A typical PP3 battery has an impedance of 1.7 ohms. That means a dead short circuit across the terminals would theoretically allow 9/1.7 = 5.2A maximum ever to flow. That kind of current would dissipate about 46W in heat inside the battery causing it to explode. Also at that current, given the typical low capacity of about 154mAh, the battery would be flat within about 100 seconds.

The maximum rated current for one of these batteries (at least, the maximum current shown on any of the graphs in the datasheet) is 250mA.

You need to power your SIM800L in a completely different manner, including two important things:

1. You need a power source that can provide 2A at the rated input voltage of your module (5V?)
2. That source needs to either be separate from the Arduino (except the ground, which must connect to the Arduino as well as the module) or if it is 5V may be used to directly power the Arduino through the 5V pin.

---
Tags: arduino-uno, serial, lcd, gsm, softwareserial
---


title: ESP8266 send number in IP address

text:
# Question
Title: ESP8266 send number in IP address
I want to easily send a number from a phone to my esp8266. I have an app that sends the number in the format IP/number. How can I modify the code to give my the number behind the IP address as an integer?

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

void setup(void){

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }

  server.on("/", [](){
    Serial.println("device connected");
  });
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

```

So it would do something like this for and should be looking through every i between 0 and 200. :

```
server.on("/"+String(i), [](){
    Serial.println("i");
  });

```

# Answer
> 1 votes
First of all use the event function server.on with a path that corresponds to your function and use a url like this:

```
192.0.2.2/recordnumber?num=100

```

With a url parmeter for your number. Your code might look like this:

At the top:

```
int nums_size = 0;
const int nums_max = 128;
int nums[nums_max];

```

In setup:

```
server.on("/recordnumber", [](){
    int num;
    if(server.hasArg("num")) {
      String num_str = server.arg("num");
      if(num_str.charAt(0) == '0') {
        num = 0;
      } else {
        num = num_str.toInt();
        if(num == 0) {
          server.send(400, "text/plain", "not a number");
          return;
        }
      }
      if(nums_size < nums_max) {
        nums[nums_size++] = num;
        server.send(200, "text/plain", "saved");
      } else {
        server.send(500, "text/plain", "full");
      }
    } else {
      server.send(400, "text/plain", "bad params");
    }
});

```

# Answer
> 0 votes
First you need to extract the string that contains the number (after the /). Since it is already stored in consecutive memory you can pass the pointer to the character after the / symbol to the C function `atoi` to convert it to an integer.

I assume the pointer is already `\0` terminated.

You can use the C function `strchr` to search for the / symbol.

Tip: use a C compiler on a desktop/PC to check how these functions work. Once you know how to use them, copy them in your Arduino code. This is much faster than uploading/debugging sketches probably.

---
Tags: esp8266
---


# Question
Title: Optimization Teensy 3.6 Arduino IDE fast I/O Multiplexing Led Matirx
I'm currently working on a 10x10 LED Matrix which is controlled by 5 Shift registers using multiplexing. I've the problem that the Teensy 3.6 is too fast/slow.

One part of my code is the Shiftout function. If I use normal digitalWrite() its working perfectly fine, but its slow. If I use digitalWirteFast() or something like GPIOA\_PSOR = (1 \<\< 12); the matrix starts to display crap.

**Teensy 3.6 180MHz**

**74HC595 shift register**

**SS8050 BJT's to protect the whole thing**

scematic here: circuits.io

```
void ShiftOut(uint8_t myDataOut) {
// This shifts 8 bits out lngMsLoopstartB first,
//on the rising edge of the clock,
//clock idles low
//internal function setup
uint8_t i = 0;
//clear everything out just in case to
//prepare shift register for bit shifting

//digitalWriteFast(dataPin, LOW);//Data aus
GPIOA_PCOR = (1 << 12); // Datapin low

//digitalWriteFast(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//for each bit in the uint8_t myDataOut
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i = 0; i <= 7; i++)  {

//digitalWrite(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//if the value passed to myDataOut and a bitmask result
// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1 << i) ) {
  //digitalWriteFast(dataPin, HIGH);//Data an
  GPIOA_PSOR = (1 << 12); // Datapin high

} else {
  digitalWrite(dataPin, LOW);//Data aus
  //GPIOA_PCOR = (1 << 12); // Datapin low
}

//register shifts bits on upstroke of clock pin
digitalWrite(clockPin, HIGH);//Clock an
//GPIOA_PSOR = (1 << 13); // Clockpin high

digitalWrite(clockPin, LOW);//Clock aus
//GPIOA_PCOR = (1 << 13); // Clockpin low

//zero the data pin after shift to prevent bleed through
digitalWrite(dataPin, LOW);//Data aus
//GPIOA_PCOR = (1 << 12); // Datapin low
}
}

```

if somebody needs the **complete** code, please let me know!

1. How it looks like when I use GPIO 2.Picture how it should look like: Imgur

**Problem**

The thing I want is to make the whole multiplexing faster. Currently 1 Time all 10 rows takes about 480 microseconds. Then add a 4 Bit Bit angle modulation (480\*16) its: 7680 microseconds (7.68ms). So if you now divide 1000 by 7.68 = 130,2 Hz refresh rate. Thats ok and Im fine with that.

The main problem is that I want 8 bit. so same thing again 480 * 256 = 112880 (112,88ms). So now divide 1000 by 112,88 = 8,86 Hz refresh rate. That looks really bad. I would like to get about 60-100.

The Problem is **not** the big LED array or setting each value every frame new. This only takes 80 microseconds.

# Answer
I have also written a driver for LED matrices based on shift registers. To quickly shift out the bits to the shift registers for each scan update, I used SPI. On the Teensy 3.6, this works quite well.

But what I suspect your issue is (since you didn't post your whole code) is that you are calculating each of the bit updates in between each shifting out. If you are doing this, I suggest that you don't. Instead, buffer the bit calculations, and use a timer interrupt to shift out each row update. This approach takes advantage of the fact that you are likely to recalculate the bit layout for the matrix overall at a much slower frequency than the need to send our row updates to effect the multiplexing of the LED rows. I explain this design in much more detail in this Instructable.

Using the interrupt allows you to cleanly do the heavy lifting of recalculating the bit layout into a buffer while the row updates will consistently go out, creating a very stable image. It's the closest thing you'd to true threading on Arduino-like platforms. Also, this approach will allow a much smaller base interval for row updates. In my code, I use a 5 µs update interval, that gets modulated in order to be able to create a 12-bit color palette. I probably could get a richer color depth on the Teensy 3.6 given it's clock speed, but I wanted my code to be universal, so I am able to get the 12-bit color on 8-bit AVR micro controllers too (e.g., Arduino Mega).

You can study (or use) my code at this GitHub repository, and read more about my LED matrices (hardware and software) at my website.
> 1 votes

---
Tags: arduino-uno, teensy, code-optimization
---


# Question
Title: Ultrasonic sensor not getting reading while connecting to ESP8266
it's been week that i am having issue,that i can’t get ultrasonic readings when i connect with my esp8266 wifi module ,everytime it gives 0 cm reading.My

both hardwares work perfectly if i connect them individually. i also divided a code of ultrasonic and esp8266 for the debugging steps,both are working. but when i combine both code together i get no response. In my database server i get 0 distance.

Note: using external power of 5v for ultrasonic sensor. Is there any logical problem? please help Sir thanks. Here is a code

```
#include<ESP8266WiFi.h>
#include<ESP8266HTTPClient.h>
#define trigger 12
# define echo 13
float timex = 0;
float distance = 0;
float max_height = 0;
float extra_space = 4.00;

int TANK_SPECIAL_ID = 1;

void setup() {
    pinMode(trigger, OUTPUT);
    pinMode(echo, INPUT);
    Serial.begin(115200);
    delay(5000);
    WiFi.begin("AndroidAP", "lovely12");

    Serial.println("Setup Initiated\ n");

    while (WiFi.status() != 3) {
        delay(500);
        Serial.println("Waiting for connection");
        Serial.print("WiFi Status: ");
        Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
}

void loop() {
        HTTPClient http;
        int Percentage = 0;
        digitalWrite(trigger, LOW);
        delayMicroseconds(2);
        digitalWrite(trigger, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigger, LOW);
        delayMicroseconds(2);
        timex = pulseIn(echo, HIGH);
        distance = timex * 340 / 20000;

        if (max_height == 0) {
            Serial.println("Setting max_height");
            max_height = distance;
            Serial.println("max_height configured..5 seconds delay");
            delay(5000);
            Percentage = -1;
            Serial.print("MAX HEIGHT: ");
            Serial.println(max_height);
        } else {
            int revVal = int(distance / max_height * 100);
            Percentage = revVal– 100;
            Serial.print("Current Ratings: ");
            Serial.print(distance);
            Serial.print(" cm");
            Serial.print(" | Percentage: ");
            Serial.print(Percentage);
            Serial.println(" %");

        }
        if (distance > -1) {
            String Data = "x=" + String(Percentage) + "&y=" + String(max_height) + "&z=" + String(TANK_SPECIAL_ID);
            http.begin("http://zaptraff.atwebpages.com/IOT/IOTCON.php");
            http.addHeader("application/x-www-form-urlencoded");

            int sent = http.POST(Data);
            Serial.print("Request val: ");
            Serial.println(sent);
            //String httpPayload = http.getString();
            //Serial.println(httpPayload);
            if (sent > 0) {
                Serial.println("Data has been sent");
            } else {
                Serial.println("unable to send data");
            }
        }
        delay(1000);
    }
}

```

# Answer
> 0 votes
As the MIME type implies `application/x-www-form-urlencoded` is URL encoded. Non-alphanumeric characters must be percent encoded.

It looks like this line:

```
if (distance > -1) {

```

Should be:

```
if (Percentage > -1) {

```

Further:

```
Percentage = revVal– 100;

```

Is sometimes negative. So `String(Percentage)` is producing `-` which is likely tripping up your web server because this is an illegal character when parsing `x-www-form-urlencoded`.

---
Tags: esp8266
---


# Question
Title: Controlling an LED using SIM900A and Arduino
How can I turn the LED on and off using a received text message?

The sim card is able to receive the message but I can't change the pin status. I also can't see anything in the serial monitor upon reception of the message.

Below is my code.

```
#include <SoftwareSerial.h>
SoftwareSerial gsm(2,3);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }
  if (gsm.available()>0)
  Serial.write(gsm.read());

  if ( msg == "ON")
  {
    digitalWrite(LED, HIGH);
    delay(1000);
  }
  if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 if (gsm.available()>0)
 {
  msg=gsm.read();
  Serial.print(msg);
 }
}

```

# Answer
Try this code.

```
#include <SoftwareSerial.h>
SoftwareSerial gsm(2,3);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }

  if ( msg == "ON")
  {
    digitalWrite(LED, HIGH);
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}

```
> 1 votes

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: How do I use interrupt service routines inside libraries and classes?
I'm trying to have a `millis()` timer run to emulate a hardware timer inside a library, but I'm having issues compiling the code. I want the callback (pseudo ISR) to be part of the class, and not use global variables.

I'm using Christensen's / Monk's Timer library, but I'm open to suggestions if there are other better/easier timer libraries out there.

This is what I have so far. It's just an example for me to understand how this might work. I'm sure there are better ways of making an LED blink, but this is just for illustrative purposes.

Compiling gives a bunch of "invalid use of member variables in static functions" errors.

> error: invalid use of member 'Blink::\_led\_status' in static member function int \_led\_status;

## EDIT

After trying to add glue routines as per your other answer I can seem to get one instance working, but adding another stops the first light from blinking, and the second one blinks on and off at the wrong times.

The test library is on github

Blink.h

```
#ifndef Blink_h
#define Blink_h

#include "Arduino.h"
#include <Timer.h> // https://github.com/JChristensen/Timer/master
    // Timer.h uses millis() instead of built in timers

class Blink {
public:
  Blink (int led_pin, int duration);
  void begin ();
  void updateTimer();

private:
  static void _callbackGlue();
  void _callback();

  static Blink *_instance;
  Timer *_blink_timer;
  int _led_pin;
  int _duration;
  int _led_status;
  int _blink_event;
};
#endif

```

blink.cpp

```
#include "Arduino.h"
#include "Blink.h"

Blink *Blink::_instance;

Blink::Blink (int led_pin, int duration) {
  _blink_timer = new Timer();
  _led_status = 0;
  _led_pin = led_pin;
  _duration = duration;
  pinMode(_led_pin, OUTPUT);
  digitalWrite(_led_pin, LOW);
}

void Blink::begin () {
  _blink_event = _blink_timer->every(_duration, _callbackGlue);
  _instance = this;
}

void Blink::_callbackGlue() {
  _instance->_callback();
}

void Blink::_callback() {
  if (_led_status == 0) {
    digitalWrite(_led_pin, HIGH);
    _led_status = 1;
  } else if (_led_status == 1) {
    digitalWrite(_led_pin, LOW);
    _led_status = 0;
  }
}

void Blink::updateTimer() {
  _blink_timer->update();
}

```

test/test.ino

```
#include "Blink.h"

Blink first_blink (13, 500);
//Blink second_blink (12, 1000);

void setup() {
  Serial.begin(9600);
  Serial.println("Starting...");
  first_blink.begin();
  //second_blink.begin();
}

void loop() {
  first_blink.updateTimer();
  //second_blink.updateTimer();
}

```

# Answer
> 1 votes
Nick Gammon's answer is good for one `Timer` \- but now you want two!

OK, then you can take advantage of the Timer Library's `context` parameter. What's that? If you take a look at the header for `every()`, you'll see as well as passing in the function to call, you can *also* pass in another value (called `context`) to pass back to that function when it fires\*. So instead of you remembering just one copy of `instance`, get each `Timer` to remember it for you.

> \*If you can't see the `context` parameter in `Timer.h`, then make sure you're using the `v2.1` branch, ***not*** `master`.

So:

1. Get rid of `_instance` everywhere.
2. Change:
`static void _callbackGlue();`
to
`static void _callbackGlue(void *context);`
3. Change:
`void Blink::_callbackGlue()`
`{`
`_instance->_callback();`
`}`
to
`void Blink::_callbackGlue(void *context)`
`{`
`((Blink *)context)->_callback();`
`}`
4. Change:
`_blink_event = _blink_timer->every(_duration, _callbackGlue);`
to
`_blink_event = _blink_timer->every(_duration, _callbackGlue, this);`

Note that I've submitted these changes as a Pull Request on your GitHub repo.

---

Incidentally:

You don't need `_blink_timer` to be a pointer. Get rid of the `*`, get rid of the line with `new Timer()` in it, and replace all your `_blink_timer->` with `_blink_timer.`

# Answer
> 0 votes
You may add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.

More about this trick in this article here.

---
Tags: library, timers, class, isr
---


# Question
Title: Use timer0 without affecting millis() and micros()
I'm writing a library which needs an ISR to turn off an LED some time after it was turned on. Since it's all about turning an LED on and off it doesn't need to be very precise. On the other hand I would like to use this library in a program where timer1 and timer2 are given out to other (more important) tasks, and I also need the `millis()` and `micros()` functions. Last, I'm using an ATmega328P microcontroller, which only has 3 timers (and I can't easily replace it with another one).

---

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions, and – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...) and the disadvantages or side effects in using this timer in a non-Arduino library and the Arduino `millis()` and `micros()` functions.

Thanks in advance for any answer!

# Answer
> So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions,

Yes. A few ways, depending on your level of comfort:

1. You can declare the stock Arduino Timer0 OVF "weak" and write your own where you can insert your ISR. But you have to handle the interaction between the millis() / micros() related variables.
2. You can modify the stock Arduino Timer0 OVF to insert your own ISR.

And – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...)

The stock ISR would look like this:

```
ISR(TIM0_OVF_vect) {
    ...
    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

    //insert your isr here
    _mytmr0_isrptr();
}

```

Where \_mytmr0\_isrptr() is a function pointer to your own ISR handler.
3. The simplest is probably to use the output compare interrupts. You can get it to behave like a virtual timer and can do lots of other stuff.

Obviously, you can think of tons of other ways and this is just a starting point.

> What are those interrupts? How can I use them? –

Timer0 has three interrupts associated with it: overflow and compare channel A and channel B. The overflow interrupt is already being used by the timing functions millis() and micros(), as shown earlier.

The compare channel A/B interrupts are unused. And this discussion is about using them for timing purposes.

The general ideal is demonstrated in blog post *Using Spare Output Compare Channels as Timers – the Collection*.

The task there is more complicated than what you are trying to do here, but the basic ideal is the same. To do what you wanted here it is much simpler than that.

If you still cannot figure it out, I can provide you with code pieces to get you started.
> 8 votes

# Answer
I think the first solution suggested by dannyf's answer is wrong as ISR in AVR GCC can't be defined as weak function (why).

I think the best solution is to add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.

More about this trick in this article here.
> 2 votes

# Answer
An interrupt can only have one interrupt service routine. The only way you can do something else using an interrupt that is already handled elsewhere would be to modify that existing interrupt handler to also call your code. Not something that is practical for a library.

I can see no practical way of doing it short of modifying the entire `millis()` system in the main API to allow hooking of callback functions, which would be a really nice facility (chipKIT has a similar system with the Core Timer interrupt on the PIC32) and submitting it back to Arduino for inclusion in the main core - which would set a baseline version for compatibility of your library of course.
> 1 votes

# Answer
> So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions ...

No, because those functions use an already-attached interrupt.

> it doesn't need to be very precise ...

Just test for the current time (eg. using `millis` or `micros`) in your main loop.

> the program main loop is sometimes quite long (e.g. sometimes it has to execute other loops) ...

Restructure so that it doesn't do that. You can use the state machine concept to do things from time to time, without getting stuck in inner loops for a long time.
> 1 votes

---
Tags: arduino-uno, timers, millis, timing
---


# Question
Title: Hardware Serial connection for Arduino Mega 2560 NEO GY-GPSMV2 GPS module
My project is **Vehicle Tracking System**, One of my module is GPS module (Neo GY-GPSMV2). I can successfully see the GPS coordinates via Software Serial. But what I want is that my Arduino should not be connected to my laptop. So I should use Hardware Serial (correct me if I'm wrong). But I read some blogs **that I should use resistors to avoid damage** to m GPS module if I will use Hardware Serial. I searched for the wiring of it then I see this.  (Please remind that I'm using Mega so please just focus on the wiring). So I bought a 10k and 4.7k resistors. My **question is how can I appl this on an actual wiring?** should I split the wire? or what?

# Answer
Most importantly, I want to point out that a Mega has 4 `HardwareSerial` ports: `Serial`, `Serial1`, `Serial2` and `Serial3`. There is no reason to use an inefficient software serial port library. Software serial libraries use the processor to handle each bit transition, so they use much more CPU time.

`SoftwareSerial` is particularly inefficient, because it disables interrupts for the entire time that a character is being sent or received, and it can't do both at the same time. This will interfere with your sketch or other libraries. This answer lists the various serial port choices.

**To answer your question:**

> ... how can I apply this on an actual wiring? should I split the wire? or what?

Yes, 3 things get connected together at two places. Most people use breadboards for prototyping. Stick two wire ends (a "split" wire) and one end of a resistor into a common row of the breadboard, connecting them electrically.

But for a permanent solution, you should solder two separate wires and one end of the resistor together. A small piece of perfboard can help secure the wires and discrete components. It's a little kludgey, but you can strip the insulation from the middle of one piece of wire (don't split the wire) and solder one end of the resistor to it.

BTW, I always recommend real level-shifter modules that use FETs. They're fast, so you can also use them for SPI interfaces, like an SD card, and they're bi-directional (5V to or from 3.3V). And they're cheap. You would just solder individual wires from the Arduino and the GPS device to various through holes in the module PCB.

The picture in your post shows a direct connection between the GPS transmit pin and the Arduino receive pin. While this will not damage either pin, the GPS transmit voltage is not quite within the range *specified* for the Arduino receive pin.

Note the use of the word "specified". If you read the specifications for the two devices, you will see that a logic 1 out of the GPS pin (called VOH) is slightly under the minimum acceptable voltage for the logic 1 input to an Arduino pin (called VIH).

You can also use discrete components to "step-up" the GPS TX voltage up a little. You can google for many different solutions. Hackaday has a nice summary. MicroChip AppNote DS41285A has many suggestions. Again, I would strongly suggest using a level-shifting module.

Many people report using a direct connection without problems. It is possible that:

* the actual devices have a higher VOH and/or lower VIH, or
* the data is received with various amounts of errors, and the GPS parsing library (or sketch) ignores the errors. Take a look at my NeoGPS library. It is the fastest, smallest, most accurate and most reliable GPS library. It can help you detect (and reject) bad data.
> 1 votes

---
Tags: arduino-mega, gps, wires
---


title: OTA updates for Arduino using nRF24L01+

text:
# Question
Title: OTA updates for Arduino using nRF24L01+
Is it possible to send OTA updates to Arduino via nRF24L01+ module?

Here are my findings:

Here is an instructable explaining how to program Arduino wirelessly but this thing uses a BT module which shows up on PC as a COM port.

Here is something similar using Xbees.

However, these use another arduino attached to a PC on the other end. In my case, I am planning to use rPi hooked to another nRF24L01+ rather than PC.

This is an excerpt from the datasheet of Atmega chip:

> In ATmega88A/88PA/168A/168PA/328/328P the Boot LoaderSupport provides a real Read-While-Write SelfProgramming mechanism for downloading and uploading program code by the MCU itself. This feature allows flexible application software updates controlled by the MCU using a Flash-resident Boot Loader program. The Boot Loader program can use any available data interface and associated protocol to read code and write (program) that code into the Flash memory, or readthe code from the program memory.

Here is what I planned as a strategy.

Master programmer = Raspberry Pi + nRF module.

Slave arduino = Arduino + nRF24L01 + external EEPROM

Once I have to upload a new code, I can transmit the compiled code to the arduino (I can do that, right?) and Arduino will save it in the external EEPROM for the time being.

When the transfer is complete, I will send a signal which will make the arduino reset and copy the code from EEPROM to its flash memory.

My questions:

Is the strategy correct and feasible?

How should I proceed to achieve it?

Any other suggestions which you might have are welcome.

# Answer
Your best strategy would be to write your own bootloader.

The existing bootloader receives data through the serial port and writes it, a page at a time, to the flash. Your custom bootloader, instead, would receive the data through the nRF module and write it to flash, a page at a time.

You could use the source code for the existing bootloader (maybe use optiboot?) as a starting point and remove the UART code, replacing it with nRF code.

Of course, you still need a way to enter the bootloader when you want to program it - the easiest way is to ensure that is added into any sketch you upload so you can send an instruction to that sketch to enter the bootloader.

You would also need to create a program on the Pi to do the programming over the air - or modify an existing one like avrdude.

It may, in the long run, be simpler to have a pair of other Arduinos (maybe something small like an ATTiny based board) to act as bridges between UART and the nRF modules so they become a transparent wireless serial link.
> 5 votes

# Answer
There is an Arduino optiboot fork for this now, which seems to handle what you want.

You would use a PC, RPi or whatever that could run `avrdude` to send the update to an Arduino acting as the update server, which transmits the code to the client.

The instructions on the page seem quite comprehensive.
> 4 votes

# Answer
If you're working with remote sensor nodes, perhaps consider the MySensors library.

It's got support for two methods of delivering OTA updates - one using a node.js controller running on a rPi; and another third-party solution with a .NET front-end.

Failing that, you could borrow the bootloader code from the library and customise to your own needs.
> 3 votes

# Answer
It's definitely feasible and it's been done. Look at Low Power Labs site where Felix did the same thing, but with a RF69 radio and an external flash chip. You do need a modified bootloader as he uses, one that would detect the new sketch in the external flash and will upload it to the Arduino on reset. Radio difference aside this should work well for your purposes.

Given the flaky nature of the radio communication I think it's a good idea to store the program separately rather than create a highly modified bootloader which will read the radio stream - it might be that for programming you need a constant stream of bytes which the radio can't always provide (though I'm not 100% sure about this); another reason being that the extra code you would need to access the radio will make for a larger bootloader.
> 2 votes

# Answer
As per @Majenko and @Kurt suggestions:

Please check out me blog post, it is exactly about that!

https://www.2bitornot2bit.com/blog/arduino-bootloader-with-ota-over-the-air-support-over-nrf24l01

I have made a complete tutorial about this issue and also modified the suggested code above so debugging will be easier.

The basic idea is to have a local station which forwards the new sketch from the **computer-\>uart-\>spi-\>rf24** to a remote Arduino running a custom bootloader which listens on the **rf24-\>spi** instead of the UART. This bootloader does everything as usual (expecting protocol commands as part of the stk500 protocol and so on) but, instead of getting them over UART the packets arrive from the RF24 module through SPI.

During boot, the bootloader will have to initialize the RF module registers and then parse the incoming bytes if any; after a timeout, it will quit and run the sketch currently there in a loog as usual

In my blog you will see some notes about the Hardware configuration for the local station: you need a 10uF capacitor between the **RESET** and **GND** pins to avoid flashing the local station while trying to flash the remote station.

That post also incldues the commands needed to use AVRdude to flash the bootloader and then to flash the remote station (which has the new bootlaoder) through the local station running the "flasher" sketch (station with the capacitor).

Basic commands are:

```
avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0xFD:m -U hfuse:w:0xDA:m -U lfuse:w:0xFF:m -F
avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U flash:w:optiboot_atmega328_new_bootlader.hex -U lock:w:0x0F:m

```

You can find the code on my blog and links to other sources and tools needed (such as an AVR programmer).
> 2 votes

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


# Question
Title: How to solve the white blocks on LCD keypad display?
I have just bought my first Arduino (a Mega 2560 R3 clone by ELEGOO), and I got a cheap LCD display to go with it. I cannot for the life of me get it to display anything other than a row of white blocks (although I uploaded a different sketch that I change the numbers of one of the ports and now it shows the top 3 blocks of the second row as white as well).

When I read the notes on the example LCD sketch "Display" it says the following:

The circuit:

* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)

However, when I plug my display into the Arduino the pins don't seem to go into the same ports and there is no other way of fitting it in. For reference my pins go:

```
LCD - Mega2560

 VSS - AREF,
 VDD - GND,
 V0 - 13,
 RS - 12,
 RW - 11,
 E - 10,
 D0 - 9,
 D1 - 8,
 D2 - 7,
 D3 - 6,
 D4 - 5,
 D6 - 4,
 D7 - 3,
 D8 - 2,
 A - 1-TX,
 K - 0-RX,

 RST - RESET,
 5V - 5V,
 VIN - VIN,
 A0 - A0,
 A1 - A1,
 A2 - A2,
 A3 - A3,
 A4 - A4,
 A5 - A5,

```

I am not sure what to do any assistance you can provide would be greatly appreciated.

Liam

# Answer
I finally solved the issue, it turns out there was nothing wrong with the LCD shield or the sketch, the problem was the MEGA 2560 (by ELEGOO). The solder joint at port 'Digital 5' was missing, the pin was through the board but there was no joint. All I did to fix it was to properly solder the joint like the others are and it started to work.

Just in case anyone has a similar sort of problem as I did or wants to check the ports are working this is the sketch that I was using when I discovered the missing joint, its a simply scrolling LED sketch:

```
 /*
  For Loop Iteration

 Demonstrates the use of a for() loop.
 Lights multiple LEDs in sequence, then in reverse.

 The circuit:
 * LEDs from pins 2 through 7 to ground

 created 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/ForLoop
 */

int timer = 100;           // The higher the number, the slower the timing.

void setup() {
  // use a for loop to initialize each pin as an output:
  for (int thisPin = ***2***; thisPin < ***13***; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // loop from the lowest pin to the highest:
  for (int thisPin = ***2***; thisPin < ***13***; thisPin++) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }

  // loop from the highest pin to the lowest:
  for (int thisPin = ***7***; thisPin >= ***13***; thisPin--) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }
}

```

you can modify the numbers that are in asterisks in order to check whichever pins you need.

To use it you build the following circuit:

Then simply change which port you connect the wire from the anode of the LED to and wait for the LED to flash on.

Thank you to everyone who posted a message to try and help me fix it, youve helped me learn a lot.

Liam
> 0 votes

# Answer
The words you use to describe the parts of the display and which sketch you are using need to be more precise.

Regarding the part you linked to in your question, the dark blue part is the LCD (Liquid Crystal Display). Not many buy just this part. It is too hard to use.

Under it is a green board with the commonly found Hitachi LCD Controller. This is what most people buy and call the LCD. Many Arduino sketches are written for the Hitachi LCD Controller. While you could connect this type of board directly to an Arduno, you would have to make a special cable which must follow the pin assignments in the particular sketch you are using!

Finally, the darker board beneath the green board appears to be an Arduino shield. Normally Arduino shields adapt what ever circuit happens to be upon the shield to the Arduino Uno pins and form-factor. However, again, you mush use a sketch which which follow the pin assignments for the particular shield!

Armed with this knowledge, you should be using/looking-for a sketch specific to your Arduino shield. I suspect you are using the wrong sketch and this is resulting in "white blocks" on your LCD display.

Other considerations:

1. It is possible your contrast in incorrectly set. Identify if this control is available on the shield you are using and consider adjusting it.
2. Is the shield plugged in correctly? Check to make sure all the pins are connected to the Arduino. Most shields are designed specifically for the Arduino Uno form factor.
3. If you are still having problems, consider buying everything (the Arduino Uno and the LCD shield) from one specific well known vendor which can supply support through direct contact or forums. Usually a good vendor will provide support especially if they provide all parts of a project.

Other approaches:

You should find a sketch which works with your LCD & Buttons Arduino shield. However, as you have figured out the paths between the Arduino and the Hitachi like LCD Module you might try using the LiquidCrystal Library. When this library is instantiated, the pins of the Arduino which are to control the Hitachi like LCD module are passed as arguments. Using the information in the question, it is likely the instantiation should look similar to this:

```
LiquidCrystal(12, 10, 5, d5, 4, 3)

```

...Note, you are missing "d5" in your question. So the above is likely not correct. Also, from your description, the Arduino appears to control contrast ("V0" pin) for this shield. As the LiquidCrystal library does not appear to support this, you may need to create additional code to control contrast.
> 1 votes

---
Tags: arduino-mega, lcd
---


# Question
Title: I'm trying to display the numbers 0-99 by multiplexing to two 7 segment displays. One number does not display
```
//Numbers 0-9.
int numberArray[10][7] = {
  { 0, 0, 0, 0, 0, 0, 1 }, //0
  { 1, 0, 0, 1, 1, 1, 1 }, //1
  { 0, 0, 1, 0, 0, 1, 0 }, //2
  { 0, 0, 0, 0, 1, 1, 0 }, //3
  { 1, 0, 0, 1, 1, 0, 0 }, //4
  { 0, 1, 0, 0, 1, 0, 0 }, //5
  { 0, 1, 0, 0, 0, 0, 0 }, //6
  { 0, 0, 0, 1, 1, 1, 1 }, //7
  { 0, 0, 0, 0, 0, 0, 0 }, //8
  { 0, 0, 0, 0, 1, 0, 0 }, //9
};

//Turn off all segments (common anode --> high = off)
void reset() {
  for (int i = 12; i >= 6; i--) {
    digitalWrite(i, 1);
  }
}

//turn on both segments (don't write anything to them)
void on(){
  digitalWrite(4,1);
  digitalWrite(5,1);
}

void setup() {
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  reset();
  on();
}
void loop() {
  for (int i=0;i<99;i++){
    twoDigitNumber(i);
  }
}

void twoDigitNumber(int number){
    digitalWrite(4,1);                   //turn on left display
    digitalWrite(5,0);                   //turn on right display
    digit(int(floor(number/10)));        //display the tens digit
    delay(10);
    digitalWrite(4,0);                   //turn off left display
    digitalWrite(5,1);                   //turn on right display
    digit(int(number-floor(number/10))); //display the ones digit
    delay(10);
}

//make the displays show a single digit number
void digit(int number) {
  for (int i = 12; i >= 6; i--) {
    digitalWrite(i, numberArray[number][12 - i]);
  }
}

```

This is my first time doing anything at all with Arduino, and I'm also brand new to the language.

I have a bit of circuitry attached to the display. I'm using 2n5551 NPN transistors to act as a switch. Collectors connected to 5v, bases are connected to pin 4/5 with a 200 ohm resistor. Emitters are connected to the common anode of the displays. pin 4 is for the left display, pin 5 for the right display. These are to display different numbers in each display. Something's probably wrong with this but I'm having a hard time learning about transistors.

When I use the function twoDigitNumber(), it only displays the number on the left display, but I can see a very dim copy of that same number on the right display. int() is there because i thought floor() would make it into a double and cause issues, but that didn't fix it.

I know every segment works. When I use digit(), it shows the same digit on both displays (as expected).

Any help is appreciated.

# Answer
> 1 votes
Missing `pinmode(4,OUTPUT)` in your `setup` routine.

As a general comment, using variable names instead of 'magic numbers' makes your code easier to read - and thus usually easier to debug. for example:

```
const int leftDisplay = 4;
const int rightDisplay = 5;
const int seg1 = 12;
const int seg2 = 11;
[...]

```

You can also use `HIGH` and `LOW` instead of `1` and `0` for the `digitalwrite` elements

---
Tags: arduino-uno, programming, hardware, 7-segment
---


title: 4-wire shielded cable for I2C and power

text:
# Question
Title: 4-wire shielded cable for I2C and power
I have two PCBs with ATmega328 that will communicate through I2C protocol. The master will also provide power for the slave, which is located at a relatively short distance (30-40cm or 12-16 inches).

Is it feasible to use the same cable for power (3.3V) and communication?

Thank you.

# Answer
Sure. Why wouldn't it be? Power is (pretty) static and noiseless.

Just be warned that having the clock and data in the same twisted pair (if your cable has twisted pairs) could cause issues over longer distances. I2C isn't designed for running over cables like that - it's designed for routing round short traces on a PCB.
> 2 votes

---
Tags: i2c
---


title: Can't see second Arduino port on Ubuntu

text:
# Question
Title: Can't see second Arduino port on Ubuntu
I have connected two arduinos to `/etc/ttyUSB0` and `/etc/ttyUSB1`.

Only one is visible in Arduino IDE. Why and how to force second?

**UPDATE**

```
$ ls -l /dev/serial/by-id
total 0
lrwxrwxrwx 1 root root 13 Jan  6 23:32 usb-1a86_USB2.0-Serial-if00-port0 -> ../../ttyUSB1

```

I.e. it shows port, which IS NOT SHOWN in Arduino IDE (only `/dev/ttyUSB0` is shown.

**ALSO**

I can see both ports if run `arduino` with sudo. Should I run it with sudo?

Permissions are same

```
$ ls -l ttyUSB?
crw-rw-rw- 1 root dialout 188, 0 Jan  6 23:26 ttyUSB0
crw-rw-rw- 1 root dialout 188, 1 Jan  6 23:39 ttyUSB1

```

# Answer
> 1 votes
You have to add use your user to the dialout group, as explained in the installation instructions for Linux.

```
sudo usermod -a -G dialout $USER

```

Then log out and back in again.

---
Tags: ubuntu
---


title: Multiple devices on SPI

text:
# Question
Title: Multiple devices on SPI
Whenever I use multiple devices on SPI, TFT Screen, and the BME280 breakout board from Adafruit, the Arduino fails to detect the devices.

Code of the screen separately (works)

```
// include the necessary libraries
#include <SPI.h>
#include <SD.h>
#include <TFT.h>  // Arduino LCD library

// pin definitions
#define sd_cs  7
#define lcd_cs 10
#define dc     9
#define rst    8

// Define screen pins
TFT TFTscreen = TFT(lcd_cs, dc, rst);

//Define variables
char sensorPrintout[4];
char sensorPrintout2[4];

// this variable represents the image to be drawn on screen
PImage logo;

void setup() {
  Serial.begin(9600);
  while (!Serial) {  }

  Serial.print("Initializing SD card...");
  if (!SD.begin(sd_cs)) {
    Serial.println("failed!");
    return;
  } else {
    Serial.println("OK!");
  }

  // Start and clear TFT screen
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);

  // Lookup image on TFT screen
  logo = TFTscreen.loadImage("Logo.bmp");
  if (!logo.isValid()) {
    Serial.println("error while loading Logo.bmp");
  }
  if (logo.isValid() == false) {
    return;
  }

  //Draw logo on the screen
  Serial.println("drawing image");
  TFTscreen.image(logo, 0, 0);

  // Change textcolor to white
  TFTscreen.stroke(255,255,255);

  //Write some text
  TFTscreen.setCursor(0,25);
  TFTscreen.print("Schuif 1: ");
  TFTscreen.setCursor(75,25);
  TFTscreen.print((char)247);
  TFTscreen.print("C");

  //Write some text
  TFTscreen.setCursor(0,50);
  TFTscreen.print("Schuif 2: ");
  TFTscreen.setCursor(75,50);
  TFTscreen.print((char)247);
  TFTscreen.print("C");
}

void loop() {
  // Read value of A0
  int value = analogRead(A0);
  Serial.println(value);
  float voltage = value * (5.0/1023.0);
  Serial.println(voltage);
  String sensorVal = String(analogRead(A0));
  String sensorVal2 = String(voltage);

  // Change sensor value to a character array
  sensorVal.toCharArray(sensorPrintout, 4);
  sensorVal2.toCharArray(sensorPrintout2, 4);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  // Write value of sensor 1
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout);

  // Write value of sensor 2
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);

  // wait  500ms
  delay(1000);

  // Change text color to black
  TFTscreen.stroke(0,0,0);

  // Write value of sensor 1
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout);

  // Write value of sensor 2
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);
}

```

Code of the BME280 separately (works)

```
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 6

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme(BME_CS); // hardware SPI

unsigned long delayTime;

void setup() {
  Serial.begin(9600);
  Serial.println(F("BME280 test"));

  bool status;

  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  status = bme.begin();
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  Serial.println("-- Default Test --");
  delayTime = 1000;
  Serial.println();
  delay(100); // let sensor boot up
}

void loop() {
  printValues();
  delay(delayTime);
}

void printValues() {
  Serial.print("Temperature = ");
  Serial.print(bme.readTemperature());
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.readPressure() / 100.0F);
  Serial.println(" hPa");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.print("Humidity = ");
  Serial.print(bme.readHumidity());
  Serial.println(" %");
  Serial.println();
}

```

Code of the TFT screen with the BME280 (doesn't work)

```
// include the necessary libraries
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <SPI.h>
#include <SD.h>
#include <TFT.h>   // Arduino LCD library
#include <Wire.h>

// pin definitions
#define bme_cs  6
#define sd_cs   7
#define rst     8
#define dc      9
#define lcd_cs 10
#define mosi   11
#define miso   12
#define sck    13

//var definitions
#define SEALEVELPRESSURE_HPA (1013.25)

//Define hardware SPI connection with BME280
Adafruit_BME280 bme(bme_cs); // hardware SPI

// Define screen pins
TFT TFTscreen = TFT(lcd_cs, dc, rst);

//Define variables
char sensorPrintout1[6];
char sensorPrintout2[6];
unsigned long delayTime;

// this variable represents the image to be drawn on screen
PImage logo;

void setup() {
  Serial.begin(9600);
  while (!Serial) {  }

  bool status;

  // Initializing SD card
  Serial.print("Initializing SD card...");
  if (!SD.begin(sd_cs)) {
    Serial.println("failed!");
    //while (1);
  } else {
    Serial.println("OK!");
  }

  //Initializing BME280
  Serial.print("Initializing BME280");
  status = bme.begin();
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  } else {
    Serial.println("BME 280 sensor found");
  }

  // Start and clear TFT screen
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);

  // Lookup image on TFT screen
  logo = TFTscreen.loadImage("Logo.bmp");
  if (!logo.isValid()) {
    Serial.println("error while loading Logo.bmp");
  }
  if (logo.isValid() == false) {
    return;
  }

  //Draw logo on the screen
  Serial.println("drawing image");
  TFTscreen.image(logo, 0, 0);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  //Write some text
  TFTscreen.setCursor(0,25);
  TFTscreen.print("temperatuur 1: ");
  TFTscreen.setCursor(100,25);
  TFTscreen.print((char)247);
  TFTscreen.print("C");

  //write some text
  TFTscreen.setCursor(0,50);
  TFTscreen.print("luchtvochtigheid 2: ");
  TFTscreen.setCursor(100,50);
  TFTscreen.print((char)37);
  TFTscreen.print("C");
}

void loop() {
  // Read value of temperature
  int value1 = bme.readTemperature();
  int value2 = bme.readHumidity();
  String sensorVal1 = String(value1);
  String sensorVal2 = String(value2);

  // Change sensor value to a character array
  sensorVal1.toCharArray(sensorPrintout1, 6);
  sensorVal2.toCharArray(sensorPrintout2, 6);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  // Write value of temperature sensor
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout1);

  // Write value of humidity sensor
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);

  // wait  500ms
  delay(1000);

  // Change text color to black (aka overwrite text)
  TFTscreen.stroke(0,0,0);

  // Write value of temperature sensor
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout1);

  // Write value of humidity sensor
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);
}

```

Now this is the serial output:

```
Initializing SD card...failed!
Initializing BME280Could not find a valid BME280 sensor, check wiring!

```

At first it only showed the first line, then it stopped because of the `while(1)` loop. So I put it in comment to see if the BME initializes on its own.

I also tested the screen+SDcard and the BME280 separately, which worked just fine.

**Update**

I tried to test the programs with the complete circuit. The program of the TFT screen works fine that way but when I try the program of the BME280 it doesn't work. I have to remove the TFT screen from the breadboard to make it work.

**Update 2**

After some measurements with the scope I determined that the MOSI is pulled to 0V when I connect the 5V to the TFT screen. I also saw that the MOSI output on the BME280 board is 3.3V instead of 5V.

Could it be that the conflict in voltages is the cause for all my troubles?

# Answer
> 0 votes
Please check my blog post about this issue exactly.

The main idea is that the different SPI components do not respect the chip select and interfere with each other on the SPI bus. The way I solved it was to toggle between the different components using an array of switches- transistors in a way that in any given time only one component is connected to my Arduino (or any other master) through the SPI.

# How to use multiple SPI devices with Arduino

While building my SmartHomeDIY project I encountered a problem trying to use multiple SPI devices connected to the same Arduino. Although the SPI bus should support multiple devices at the same time (toggling the Chip-Select line), this does not always work (mostly due to the part using the bus not respecting the chip select or other configuration issues). So after reading for some time and experimenting I came up with the following solution.

The above station is an IR recorder and sransmitter station. It can be set into recording state, which then saves the recorded IR-in data into and SDCard connected over SPI. But when not in recording mode it will listen over the RF24 (also connected via SPI) for commands. Once a command is given it will try to send the IR code request (for example turn TV on). To do that it will again have to move to SDCard mode and read the previously recorded data and retransmit it over the IR out LED.

So to solve this I have connected the SPI lines to couple of transistors/switches, then just CUT the lines of the part not being used at the moment and there for prevent the SPI lines collision.

Attached is the code and hardware layout to do just that.

Note that it does not matter which type of project you have. You can always do the same transistor-switch trick to cut of the problematic SPI lines while using the others.

A special note for the transistor configurations. It will not work if you pass as usually suggested, which means to set a logic level by design at the output of the transistor so that the base will toggle the out voltage (same as an amplifier).

Instead I set the signal to go trough the transistor, which is needed, so testing to select the transistor, which does not affect the actual signal (it will depend on the transistor type, spec and configuration...). So it took me some time to figure out the right transistor values and configuration.

For trial and error I used a logic analyzer with 8 logic lines or an oscilloscope.

I inspected the incoming signal and the outgoing signal to make sure the transistor does not temper with the incoming signal, so everything will continue to work as expected (the transistor is transparent to the actual data).

You could also use this logic multiplexer \[8 Channel Logic Level Converter Convert TTL Bi-directional\] to do the same job, which I have not tested yet. But I think my way is more fun! :)

# Answer
> 2 votes
Connect the BME280 board by I2C, it cannot be used in a multi-SPI setup. The problem is that the MISO line it not decoupled from the bus if CS is HIGH but constantly pulled HIGH. This will disturb other bus members.

---
Tags: arduino-uno, spi, tft
---