# Question
Title: i uploaded the code but when i open the serial monitor, but the 'sendCommand' isn't working in serial monitor...plzz help
```
#include <SoftwareSerial.h>
#define DEBUG true

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

void setup() { // Open serial communications and wait for port to open:
Serial.begin(9600); //for monitoring purposes
esp8266.begin(9600);

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

  }

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

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

  if (debug) {
   Serial.print(response);
  }
  return response;
  }

```

# Answer
> 1 votes
I don't know where you found (or how you came up with) this bit of code:

```
long int time = millis();
while ((time + timeout) > millis()) {
    while (esp8266.available()) {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response += c;
    }
}

```

But it's horrible.

Not only is your time calculation completely wrong and will suffer a nasty death when millis() rollover occurs, but the whole concept of what you are doing there is bad.

The ESP8266 (assuming it's working, which hasn't been confirmed) sends a response that is terminated by a line-feed ("\n") character. You are ignoring that and just reading for a pre-defined amount of time (badly).

Instead you should be reading up until you get that "\n" character, or breaking if your timeout has been exceeded.

For instance:

```
String sendCommand(String command, const int timeout, boolean debug) {
    String response = ""; // ugh... strings... yuck
    esp8266.println(command);
    uint32_t ts = millis();
    while (millis() - ts < timeout) {
        if (esp8266.available()) {
            char c = esp8266.read();
            if (c == '\n') {
                #ifdef DEBUG
                    Serial.println(response);
                #endif
                return response;
            } else {
                response += c;
            }
        }
    }
    return String("timeout");
}

```

Better that that though is to ditch those nasty String objects. Instead pass a char\* buffer to collect the response in:

```
int sendCommand(const char *command, uint32_t timeout, char *response, uint32_t rlen) {
    esp8266.println(command);
    response[0] = 0;
    uint32_t rpos = 0;
    uint32_t ts = millis();
    while (millis() - ts < timeout) {
        if (esp8266.available()) {
            char c = esp8266.read();
            if (c == '\n') {
                if (debug) Serial.println(response);
                return rpos;
            } else {
                if (rpos < rlen - 2) {
                    response[rpos++] = c;
                    response[rpos] = 0;
                }
            }
        }
    }
    return -1;
}

```

Then you use that like this:

```
char response[80];

if (sendCommand("AT+CIFS+RST", 1000, response, 80) == -1) {
    Serial.println("CIFS Timed out!");
}
if (sendCommand("AT+IPR=115200", 1000, response, 80) == -1) {
    Serial.println("IPR Timed out!");
}

```

And so on.

By the way - that `AT+IPR=115200` is a bit of a stupid thing to do. You create a software serial port at 9600 baud (fine), then almost immediately instruct the ESP8266 to switch to 115200 baud instead. You don't then start communicating at 115200 baud, but stay at 9600 baud, so communication can never continue from that point on. Not only that, but SoftwareSerial is highly unstable at 115200 baud and is not recommended. Stick to 9600 baud.

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


# Question
Title: Multiple node network communication over I²C
I am working on a project where I want to send data from and to different Arduinos on a network. At the moment I²C seems the best option for my needs since I can specify where to send the data. But using this method I have a bit of an issue I can't seem to find a solution for :(.

I will try to explain my problem using the following image:

In the backend all the nodes are connected like in the first image (above the example network). But the nodes may be connected in a different sequence by a user. See the example network.

In this example network, the node with ID 1 needs to send data to ID 10 and not to any other node on the network. Node ID 12 also needs to send data to node ID 10, but no other nodes. Etc. Etc. Etc. But the node that needs to send data to the next node doesn't know the id of the node it needs to send to.

So at first the nodes need to find out what nodes they are connected to and where they need to send their data.

I thought of doing this by connecting a wire between each node (blue wire in possible solution) and when a node gets added to the network the nodes send a high signal over the blue wire and sends its ID to all nodes on the network and then all nodes on the network check if they receive a high signal and an ID.

If this is true they will send its id to the node that has been added. This works fine if you add a node one by one to the network. But it fails when you replace a node in the middle of the network or disconnect power from the network.

What would be the best way to do this (I am also open to use different data transfer protocols)?

# Answer
> 2 votes
It sounds (after discussion) like what you are after is actually a *mesh* of multiple *peer to peer* devices. That is, lots of devices, each one has multiple dedicated communication links each directly going to another device.

If you had enough UART ports you could create individual UART links between nodes. The bets Arduinos only have a handful of those, and the UNO only one. So that's not really practical.

You could possibly do it with SPI if you wanted to put a lot of work in to developing a decent control protocol to go along with it. Something along the lines of BUSRQ/BUSACK signalling:

```
BUSRQ: Signalling line pulled HIGH by resistor. All nodes INPUT.
BUSACK: Signalling line pulled HIGH by resistor. All nodes OPEN-DRAIN & LOW.
SS: Direct 1:1 GPIO links between nodes - all pulled HIGH. All nodes INPUT.

Node 1                   Node 2                  Node X
RELEASE BUSACK
DRIVE BUSRQ (OD Low)     Sees BUSRQ fall         Sees BUSRQ fall
                         RELEASE BUSACK          (could be busy...)
                                                 RELEASE BUSACK
Sees BUSACK rise
DRIVE BUSACK
SS Node 2 LOW            Sees SS go LOW
Send SPI data            Receives SPI data
SS Node 2 INPUT          Sees SS go HIGH
RELEASE BUSRQ                                    Sees BUSRQ rise
                         Sees BUSRQ rise         Drive BUSACK
                         Drive BUSACK

```

Only once all nodes have released BUSACK will the requesting node be able to send any data, and once a node has released BUSACK it knows that it must never send any data. The requesting node has basically locked the bus from other nodes accessing it.

It's not perfect, and doesn't handle multiple devices requesting the bus at the same moment, but it does prevent one device trying to send while another is actively sending.

---
Tags: i2c, attiny, networking, network
---


# Question
Title: i586-poky-linux-g++: no such file or directory Error compiling for board Intel® Edison
I'm facing this compilation issue.

Arduino: 1.8.4 (Linux), Board: "Intel® Edison"

`fork/exec /home/jimish/.arduino15/packages/Intel/tools/core2-32-poky-linux/1.6.2+1.0/i686/sysroots/pokysdk/usr/bin/i586-poky-linux/i586-poky-linux-g++: no such file or directory
Error compiling for board Intel® Edison.`

**Arduino IDE:**

---

**Web IDE:**

# Answer
The problem here is that Intel, in their infinite wisdom\* have lots of hard-coded paths to libraries in the binaries (why, heaven only knows) and then a set of scripts that munge those binaries to sort out where the libraries really are.

That script uses an option to `find` that was deprecated 13 years ago.

Way to keep up with the times, Intel...

So you need to make some fixes to get the toolchain to install properly.

I have created "fix" scripts for both the Edison and the Galileo that you can use to replace your broken toolchain.

---

\*i.e., sheer incompetence
> 3 votes

---
Tags: arduino-ide, compilation-errors, edison
---


title: ESP.deepSleep() - over and over?

text:
# Question
Title: ESP.deepSleep() - over and over?
Important note: the esp.deepsleep function uses microseconds, not milliseconds.

I posted another question here asking for clarification on how an RTC can be used to put a NodeMCU 12 to sleep for a long time (~24hrs or more).

This question concerns the use of ESP.deepSleep(\[microseconds\]) with the NodeMCU 12 board. There is a discussion here and I have followed the advice but have been unable to successfully implement the ESP.deepSleep() function using the Arduino IDE and a NodeMCU 12 board.

Initial findings:
-Connecting gpio16 (D0) to the RST pin causes a reset immediately upon entering sleep. The entire boot process and loop are repeated over and over again.
-Simply using the ESP.deepSleep() function without gpio16-to-RST generates gibberish on the serial monitor and illuminates the red led on the board.

My code is here (I just drop "deepsleep();" where I want the sleep process to begin):

```
void deepsleep() {
  Serial.println("sleeping hr 1");
  ESP.deepSleep(3600000); //1hr
  delay(100);
  Serial.println("sleeping hr 2");
  ESP.deepSleep(3600000); //2hr
  delay(100);
  Serial.println("sleeping hr 3");
  ESP.deepSleep(3600000); //3hr
  delay(100);
  Serial.println("sleeping hr 4");
  ESP.deepSleep(3600000); //4hr
  delay(100);
  Serial.println("sleeping hr 5");
  ESP.deepSleep(3600000); //5hr
  delay(100);
  Serial.println("sleeping hr 6");
  ESP.deepSleep(3600000); //6hr
  delay(100);
  Serial.println("sleeping hr 7");
  ESP.deepSleep(3600000); //7hr
  delay(100);
  Serial.println("sleeping hr 8");
  ESP.deepSleep(3600000, WAKE_RF_DEFAULT);  //8hr
}

```

What is wrong with this approach and why am I (apparently) causing an error?

# Answer
Use a resistor between GPIO16 and RST. I usually use a 470 Ohm resistor. Shorting the pins with a wire does not work.

https://www.esp8266.com/viewtopic.php?t=14350#p64510

Maximum deep sleep is about 71 minutes. 3600000 microseconds = 3.6 seconds, not 1 hour. 1 hour in microseconds is 3600000000UL.

As mentioned in the comments, waking from deep sleep on the ESP8266 is a hardware reset so execution begins at the start of the setup function.
> 4 votes

---
Tags: c++, nodemcu, sleep
---


# Question
Title: Combining two sketches that both work on their own, but don't work when combined
I've got a program for a password protected doorlock, which I got working.

I'm trying to add to the code, to add functionality where I can toggle an LED on/off with a button.

Both codes function on their own and serve their desired purpose, but when I try to combine them into the same sketch, the LED button works but the rest of my design stops working. I can no longer input a password to activate the motor.

How can I combine the two codes and have them both work?

Here is the working keypad/lock code

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

#define Password_Length 5

int signalPin = 10;
int greenLedPin = 11;
int redLedPin = 12;
char Data[Password_Length] = "4";
char Master[Password_Length] = "1234";
byte data_count = 0, master_count = 0;
bool Pass_is_good;
char customKey;

const byte ROWS = 4;
const byte COLS = 3;
bool ledState = 0;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

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

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,     COLS);

LiquidCrystal_I2C lcd(0x3f, 16, 2);

void setup()
{
  lcd.init();
  lcd.backlight();
  Serial.begin(9600);
  lcd.clear();

  pinMode(redLedPin, OUTPUT);
  pinMode(greenLedPin, OUTPUT);
  digitalWrite(redLedPin, LOW);
  digitalWrite(greenLedPin, LOW);
}

void loop()
{
  lcd.setCursor(0,0);
  lcd.print("Enter Password:");

  customKey = customKeypad.getKey();
  if (customKey){
    Data[data_count] = customKey;
    lcd.setCursor(data_count,1);
    lcd.print(Data[data_count]);
    data_count++;
    }

if(data_count == Password_Length-1){
    lcd.clear();

    if(!strcmp(Data, Master)){
      lcd.print("Correct");
      pinMode(signalPin, OUTPUT);
      digitalWrite(signalPin, LOW); //turns on motor
      digitalWrite(greenLedPin, HIGH); //turns on led
      delay(2000);
      digitalWrite(signalPin, HIGH); //turns off motor
      digitalWrite(greenLedPin, LOW); //turns off led
      }
    else{
      lcd.print("Incorrect");
      digitalWrite(redLedPin, HIGH); //turns on led
      delay(2000);
      digitalWrite(redLedPin, LOW); //turns off led
      }

    lcd.clear();
    clearData();
  }
}

void clearData(){
  while(data_count !=0){
    Data[data_count--] = 0;
  }
  return;
}

```

and here is the code I'm using for the LED on/off toggle button

```
int button = 2;
int led = 13;
int status = false;

void setup(){
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP); // set the internal pull up resistor,
unpressed button is HIGH
}

void loop()
{
//a) if the button is not pressed the false status is reversed by !status
and the LED turns on
//b) if the button is pressed the true status is reversed by !status and
the LED turns off

if (digitalRead(button) == true) {
status = !status;
digitalWrite(led, status);
} while(digitalRead(button) == true);
delay(50); // keeps a small delay
}

```

# Answer
Let's step back from the Arduino for a minute and ask: assuming you know how to cook some bacon, and also how to boil some eggs, how would you simultaneously cook bacon **and** eggs?

Basically you would have to interleave any process (such as waiting for the water to boil) with some other process (such as waiting for the bacon to cook).

Once you have this concept in your head you can just take the two pieces of code, and wherever you are planning to wait for something to happen, see if the other thing is able to be done.

I have done a post about this: http://www.gammon.com.au/blink

> I just figured out that the original password code will still function, but only if i keep the LED toggle button held down.

Well, you need to remove any *blocking* loops from either part of the code.

Your code here blocks:

```
if (digitalRead(button) == true) {
status = !status;
digitalWrite(led, status);
} while(digitalRead(button) == true);

```

That's like (in my analogy) of thinking "oh the water is boiling, I'll have to stare at the eggs until they are cooked". Instead you could check the bacon, check the eggs, check the bacon again, and so on.

I'm giving you these analogies to help you solve the general problem, not this particular bit of coding.

---

> i understand that the code blocks, but that code also makes the LED toggle on and off like i need, so how do i integrate that in a way that it doesnt block the rest?

Replace the LED code with something like this (not compiled or tested):

```
void loop ()
  {
  static int oldReading = LOW;
  int newReading = digitalRead (button);
  if (newReading != oldReading)  // it changed!
    {
    oldReading = newReading;  // remember new reading state
    if (newReading == HIGH)
      {
      status = !status;
      digitalWrite(led, status);
      }  // end of a HIGH reading
    }  // end of changed state

   // password stuff here

   }  // end of loop

```

Now, whatever you do with the button, the code doesn't stop (block) so the password stuff is still executed.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Disable the Amplifier during the flashing ESP8266
I use ESP-12 and Adafruit Mono Amplifier for playing audio. It works but It has one big issue. My circuit uses RxD to transfer audio (A+ connect to RxD), also ESP uses for flashing the chip. This causes horrible noise when it is programming the ESP8266 from the speaker. The good thing about this module is it has SD pin which can be used to turn it off.

Now the question is how I can connect this SD pin to disable the amplifier during the flashing procedure and also keep it off by default in normal mode and use something like digitalWrite() to turn it on manually in my application when it is needed. Thanks

# Answer
> 2 votes
SD is pulled up to VIN by a 10kΩ resistor. You will need to pull it down to ground with something "stronger" that 10kΩ - a 1kΩ resistor would probably do it.

Then you can drive the pin HIGH and override that 1kΩ resistance to enable the module.

You could also modify the module to remove the 10kΩ pull-up resistor (the one right by the VIN label which has 1002 printed on it) and use a weaker pull-down resistor (10kΩ would be good).

---
Tags: esp8266, audio
---


# Question
Title: Decimal numbers sent over Serial get split and sent over multiple ticks
Here is my Arduino sketch:

```
#include <HX711.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
HX711 hx(9, 10, 128, 0.002229);
LiquidCrystal_I2C lcd(0x27,16,2);

void setup() {

  Serial.begin(9600);
  hx.set_offset(-9635);
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  lcd.begin(16,2);

}
void loop() {
  if(digitalRead(0) == LOW){
    lcd.clear();
    lcd.setCursor(2,0);
    lcd.print("tare recieved");
    hx.tare();
  }

  double sum = 0;
  for (int i = 0; i < 10; i++) {
    sum += hx.bias_read();
    if(sum < 0) {
      sum = 0.00;
    }

  }
  sum = sum/10;
  lcd.clear();
  lcd.setCursor(4,0);
  lcd.print("Weight");
  lcd.setCursor(5, 1);
  lcd.print(sum);
  lcd.print("g");
  Serial.println(sum);
  delay(10);
 }

```

Here is an example output as seen on the Arduino Serial Monitor:

```
150.34
150.39
150.40
150.37
150.38

```

The Problem is when the data reaches node-serialport the value is split up on multiple lines.

```
 comport.on("data", function (data) {
    console.log(data.toString());
 }

```

When i log the data... it comes back like this:

```
1
50.4
5
150.
49
15
0.47
150.
48
15
0.45

```

Is there anyway to have Arduino only send the data if it is the full value and not the split up values?

# Answer
As explained in Majenko’s comment, the serial link is not packetized: it transmits individual bytes and nothing else. If you need to convey a notion of “data packet”, or “full message”, you will have to devise a way to signal the message boundaries. This is called message “framing”.

Your Arduino is sending ASCII data. In this case, the most common way to frame messages is linewise: each message is a single line, and each line is terminated by an “end of line” sequence. The standard end of line sequences are CR (carriage return, i.e. `0x0d` or `'\r'`), LF (line feed, i.e. `0x0a` or `'\n'`), and the pair CRLF (CR followed by LF, or `"\r\n"`).

Actually you are already doing that: you are using `Serial.println()`, and this method automatically appends CRLF at the end of whatever it prints. So now you just have to *parse* that at the other end: you put all the incoming characters into a buffer until you see that incoming CRLF. Then you know you have a full line, which you can report as an entire message.

This procedure is very common and there is a standard Node.js module for it. It once was part of the serialport module, but it seems to have split into a separate module. It is called *parser-readline*, and you would use it like this:

```
const Readline = require("parser-readline"),
      parser = comport.pipe(new Readline({ delimiter: "\r\n" }));

parser.on("data", data => console.log(data.toString()));

```

C.f. the documentation of ReadLineParser.
> 1 votes

---
Tags: arduino-uno, node.js
---


# Question
Title: Problem while connecting two arduino with NRF24L01
I am a beginner in Arduino programming so that program is also little bit lengthy sorry for inconvenience. I have make a program for wire less controlling of a servo motor and LED(7 Nos.) using ARDUINO UNO, Funduino Joy stick shield V1.A and NRF24L01.First i have prepare the program (using Array) only for controlling the LEDs and its become success as that LEDs working as per program.Than i added Servo motor also in circuit and make some changes in existing LED program. Unfortunately the result is erratic out put.joy stick input signal interrupting the led signal and some time servo motor respond led input .Transmitting code and Reciever code given below.

I came to know that this problem will solve using "struct" command in existing program . Please help me to modify the program with "struct".Because i have no thorough knowledge in C,C++

TRANSMITTER

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

>

#define xAxis A0
RF24 radio(9,10);
const uint64_t pipe = 0xF0F0F0F0D2L;

int msg[1];
int buttonPin1 = 2;
int buttonPin2 = 3;
int buttonPin3 = 4;
int buttonPin4 = 5;
int buttonPin5 = 6;
int buttonPin6 = 7;
int buttonPin7 = 8;
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
int buttonState6 = 0;
int buttonState7 = 0;

void setup(void)
{
  radio.begin();
  radio.openWritingPipe(pipe);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  pinMode(buttonPin5, INPUT_PULLUP);
  pinMode(buttonPin6, INPUT_PULLUP);
  pinMode(buttonPin7, INPUT_PULLUP);
}

void loop(void)
{
  int potValue = analogRead(A0);                              //  INPUT FOR SERVO MOTOR
  int angleValue = map(potValue, 0, 1023, 0, 180); // INPUT FOR SERVO MOTOR
  radio.write(&angleValue, sizeof(angleValue));         // INPUT FOR SERVO MOTOR

  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);
  buttonState5 = digitalRead(buttonPin5);
  buttonState6 = digitalRead(buttonPin6);
  buttonState7 = digitalRead(buttonPin7);

 if (buttonState1 == LOW){
    msg[0] = 111;
    radio.write(msg, 1);               // INPUT FOR LED1
   }
 if (buttonState2 == LOW){
    msg[0] = 222;
    radio.write(msg, 1);               // INPUT FOR LED2
   }
 if (buttonState3 == LOW){
    msg[0] = 212;
    radio.write(msg, 1);               // INPUT FOR LED3
   }
 if (buttonState4 == LOW){
    msg[0] = 216;
    radio.write(msg, 1);                 // INPUT FOR LED4
   }
 if (buttonState5 == LOW){
    msg[0] = 218;
    radio.write(msg, 1);                // INPUT FOR LED5
   }
 if (buttonState6 == LOW){
    msg[0] = 220;
    radio.write(msg, 1);                 // INPUT FOR LED6
   }
    if (buttonState7 == LOW){
    msg[0] = 224;
    radio.write(msg, 1);
   }                                              // INPUT FOR LED7

  }

```

RECIEVER

```
 #include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>  // SERVO LIBRARY INCLUDED

Servo myServo;
RF24 radio(9,10);
const uint64_t pipe = 0xF0F0F0F0D2L;

int led1 = 2;
int led2 = A2;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 7;
int led7 = 8;
int msg[1];
int angleValue ;

void setup(void)
{
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, pipe);
  radio.startListening();
  myServo.attach(3);                  // SERVO CONNECTED TO PIN 3
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
}
void loop(void)
{
   // Receiving code for LED 1 TO LED 7

  if(radio.available()){
    bool done = false;
    while (!done) {
    done = radio.read(msg, 1);
    Serial.println(msg[0]);

    if (msg[0] == 111) {
      digitalWrite(led1, HIGH);
      digitalWrite(led7, LOW);
      }
    if(msg[0] == 222){
        digitalWrite(led1, LOW);
        digitalWrite(led2, HIGH);
        digitalWrite(led7, LOW);
        }
     else if (msg[0] == 111){
          digitalWrite(led2, LOW);
        }
     else if(msg[0] == 212){

          digitalWrite(led3, HIGH);
        }
    else if(msg[0] == 216){
          digitalWrite(led4, HIGH);
        }
    else if(msg[0] == 218){
          digitalWrite(led5, HIGH);
        }
    else if(msg[0] == 220){
          digitalWrite(led6, HIGH);
        }
    else if(msg[0] == 224){
          digitalWrite(led7, HIGH);
          digitalWrite(led1, LOW);
          digitalWrite(led2, LOW);
        delay(10);
        }
      }
   }

//Recieving code for servo motor

    if(radio.available()){
      bool done = false;
      while (!done) {
      done = radio.read(&angleValue,sizeof (angleValue) );
      myServo.write(angleValue);}
      delay(10);
     }
                  //Receiving code for LEDs
      else {
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
      digitalWrite(led6, LOW);

      }
 }

```

---

I have tried to make a program using "struct" for 6 button state and one angle input signal to control using 6 LEDs and one Servo and its working fine(Program mentioned below.) But problem is that when i add two more input signal that time output become erratic and output is not getting as per program.Please help to modify the program. transmitter

```
#include <SPI.h>
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int upbut = 2;
int rightbut = 3;
int downbut = 4;
int leftbut = 5;
int nuetral = 6;
int starte = 7;
int stope = 8;
struct data {
    uint8_t leds;
    uint8_t angle;
};
struct data packet;
void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(pipe);
  pinMode(upbut,INPUT_PULLUP);
  digitalWrite(upbut,LOW);
  pinMode(rightbut,INPUT_PULLUP);
  digitalWrite(rightbut,LOW);
   pinMode(downbut,INPUT_PULLUP);
  digitalWrite(downbut,LOW);
  pinMode(leftbut,INPUT_PULLUP);
  digitalWrite(leftbut,LOW);
  pinMode(nuetral,INPUT_PULLUP);
  digitalWrite(nuetral,LOW);
  pinMode(starte,INPUT_PULLUP);
  digitalWrite(starte,LOW);
  pinMode(stope,INPUT_PULLUP);
  digitalWrite(stope,LOW);
  //end pinMode and digitalWrite
}//--(end setup )---
void loop(){
int potValue = analogRead(A0);
packet.angle = map(potValue, 0, 1023, 0, 180);

packet.leds = 0;
packet.leds = digitalRead(upbut) ? 0x00 : 0x01;
packet.leds |= digitalRead(rightbut) ? 0x00 : 0x02;
packet.leds |= digitalRead(downbut) ? 0x00 : 0x04;
packet.leds |= digitalRead(leftbut) ? 0x00 : 0x08;
packet.leds |= digitalRead(nuetral) ? 0x00 : 0x10;
packet.leds |= digitalRead(starte) ? 0x00 : 0x20;
/*packet.leds |= digitalRead(starte) ? 0x00 : 0x30;*/

radio.write((uint8_t *)&packet, sizeof(struct data));
}

```

receiver

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

#include <Servo.h>
#define CE_PIN 6
#define CSN_PIN 7
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
const int servo1 = 9;
int servoVal;
Servo myservo1;
struct data {
    uint8_t leds;
    uint8_t angle;
};
struct data packet;
int led1 = 2; // digital out put
int led2 = 3; // digital out put
int led3 = 4; // digital out put
int led4 = 5; // digital out put
int led5 = 8; // digital out put
int led6 = A0; // digital out put
int led7 = A1; // digital out put
void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  myservo1.attach(servo1); // attaches the servo1 /analog output

  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  Serial.println("Nrf24L01 Receiver Starting");
  radio.begin();
  radio.openReadingPipe(1,pipe);
  radio.startListening();;
}                             //--(end setup )---

void loop(){

if (radio.available()) {
    radio.read((uint8_t *)&packet, sizeof(struct data));
    myservo1.write(packet.angle);
   if (packet.leds ==0x01){
    digitalWrite(led1, packet.leds & 0x01);
    digitalWrite(led2, packet.leds & 0x00);
    digitalWrite(led6, packet.leds & 0x00);
    }
   else if (packet.leds ==0x02){
    digitalWrite(led2, packet.leds & 0x02);
    digitalWrite(led1, packet.leds & 0x00);
    digitalWrite(led6, packet.leds & 0x00);
    }
    else if (packet.leds ==0x20){
    digitalWrite(led6, packet.leds & 0x20);
    digitalWrite(led1, packet.leds & 0x00);
    digitalWrite(led2, packet.leds & 0x00);
    }
    digitalWrite(led3, packet.leds & 0x04);
    digitalWrite(led4, packet.leds & 0x08);
    digitalWrite(led5, packet.leds & 0x10);

   /*digitalWrite(led7, packet.leds & 0x30);*/
}
}

```

# Answer
Your whole method is completely wrong.

Instead of sending bytes with some unknown meaning at random times you need a far more structured approach to sending your data.

You need to either:

* Send the meaning of the byte(s) along with the byte(s), or
* Send all the information every time at pre-defined periods.

Of the two options I'd favour the latter, using a `struct`:

```
struct data {
    uint8_t leds;
    uint8_t angle;
};

```

And then:

```
struct data packet;

int potValue = analogRead(A0);
packet.angle = map(potValue, 0, 1023, 0, 180);

packet.leds = 0;
packet.led |= digitalRead(buttonPin1) ? 0x00 : 0x01;
packet.led |= digitalRead(buttonPin2) ? 0x00 : 0x02;
packet.led |= digitalRead(buttonPin3) ? 0x00 : 0x04;
packet.led |= digitalRead(buttonPin4) ? 0x00 : 0x08;
packet.led |= digitalRead(buttonPin5) ? 0x00 : 0x10;
packet.led |= digitalRead(buttonPin6) ? 0x00 : 0x20;

radio.write((uint8_t *)&packet, sizeof(struct data));

```

Then when reading you do the exact opposite:

```
struct data packet;

if (radio.available()) {
    radio.read((uint8_t *)&packet, sizeof(struct data));
    myServo.write(packet.angle);
    digitalWrite(led1, packet.leds & 0x01);
    digitalWrite(led2, packet.leds & 0x02);
    digitalWrite(led3, packet.leds & 0x04);
    digitalWrite(led4, packet.leds & 0x08);
    digitalWrite(led5, packet.leds & 0x10);
    digitalWrite(led6, packet.leds & 0x20);
}

```

The `struct` combines a number of variables together into one single block of data giving you easy access by name to the different portions. One, the `leds` variable, is then used as a *bitmap* of whether each LED is on (1) or off (0). That way you can send the current state of up to 8 LEDs in just a single byte. If you want to expand that to send different combinations of LEDs then just change which bits of the byte are set.

If you want to "toggle" the LEDs then it will be necessary to keep a record at the sender of the states and send that instead of the raw button data.
> 1 votes

---
Tags: nrf24l01+
---


title: Connecting LCD TFT shield to NodeMCU

text:
# Question
Title: Connecting LCD TFT shield to NodeMCU
I have the following screen:

I want to connect it to a NodeMCU device:

I read somewhere that it is not possible. However, I am not interested in the touch ability nor the SD card. I just want to draw something on the screen.

Is it possible to make the connection in somehow?

# Answer
The driver chip was identified by https://www.waveshare.com/wiki/2.8inch\_TFT\_Touch\_Shield and https://www.waveshare.com/w/upload/8/84/2.8inch-TFT-Touch-Shield-UserManual-EN.pdf as being the **HX8347D**.

At https://github.com/jshnaidman/UTFT\_ESP8266\_HX8347D there seems to be a library, with which you can use the `HX8347D` display type to instantiate a `UTFT` object, with which you can draw. You can build upon this demo code.

The connections for the SPI interface are detailed here. BL (backlight) pin is detailed here. The pin number for the D/C pin must be given in the code in the constructor and can be chosen freely.

Other reference code (which you might have to port) are:
> 3 votes

---
Tags: esp8266, lcd, nodemcu, tft
---


# Question
Title: Is it correct to use a 9V 1A transformer to power my project?
I have a quick question:

I have a small alarm project running on an ArduinoNanoV3 (a chinese clon). Counting *sensors, actuators* and the *arduino itself* the consumed current (theoretically speaking, calculated by the data provided by the datasheets) doesn't approach to a max of 300mA. Now, the way I plan to feed the project is using a 110V (AC) transformer that gives me **9V** output with **1A** maximum output. My fear is the output of this transformer (that says 1A) when in all places recommend not to use sources that give currents greater than **500mA** when you are going to feed it by the pin VIn with **9V**.

My question is: if my project is not going to consume more than 300mA, is there any danger/trouble when connecting the 9V ~ 1A transformer for energize my Arduino based project?

# Answer
> 5 votes
> in all places recommend not to use sources that give currents greater than 500mA when you are going to feed it by the pin VIn with 9V.

Nowhere says that. They say you should not *draw* more than 500mA when you supply with 9V.

The heat generated by the 5V voltage regulator is proportional to the current multiplied by the voltage. The more current you draw the hotter the regulator will get. The higher the input voltage, the more voltage it has to drop, and thus the hotter it gets.

So the higher the input voltage the lower the current drawn by your project can be before the regulator gets too hot.

Since you are only around 300mA that's below the recommended maximum for a 9V input.

---
Tags: arduino-nano, current
---


title: help compiling code for flora project

text:
# Question
Title: help compiling code for flora project
I'm working on the Adafruit Firewalker shoes.

I can't make my code compile to test my flora project.

This is my error message:

```
Arduino: 1.6.7 (Windows 10), Board: "Adafruit Flora"

C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel: No such file or directory

 #include <Adafruit_NeoPixel>

                             ^

compilation terminated.

exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

```

---

https://learn.adafruit.com/firewalker-led-sneakers/test-circuit

```
    #include <Adafruit_NeoPixel.h>

const int analogInPin = A9;  // Analog input pin that the potentiometer is attached to
Adafruit_NeoPixel strip = Adafruit_NeoPixel(10, 6, NEO_GRB + NEO_KHZ800);
int sensorValue = 0;        // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
 pinMode(9, INPUT_PULLUP);
   strip.begin();
  strip.show(); // Initialize all pixels to 'off'

}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // print the results to the serial monitor:
  Serial.print("sensor = " );
  Serial.println(sensorValue);

if (sensorValue < 100){
  Serial.println("leds triggered");
colorWipe(strip.Color(255, 0, 0), 25);
colorWipe(strip.Color(0, 0, 0), 25);
}

}

void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
}

```

# Answer
> 1 votes
I had the same problem, you just have to download the Adafruit Neo Pixel library:

# Answer
> -1 votes
i think issue is in your this path C:\Users\Devi\Documents\Arduino\test\_2\test\_2.ino\test\_2.ino.ino:1:29: fatal error: Adafruit\_NeoPixel:

make new arduino file and copy the same code and save it on other folder on desktop or other drive then compile it

**Compilation** I compiled you same code and my stored path of .ino file is C:\Users\Muhammad Hassaan\Documents\Arduino\sketch\_mar04a

---
Tags: c++, compile
---


# Question
Title: Motor shield not providing enough current to 2 12V DC fans
I have 2 fans and they require up to 3A current, but my motor shield (Arduino Motor Shield Rev3) on my Arduino MEGA can only provide 2A per channel (4A max). Is it ok to run the fans at a lower speed or are there other options to run (H-bridge)? Thanks.

Fans: https://www.amazon.com/HIGHFINE-4000RPM-Cooling-FFC1212DE-Computer/dp/B01LLYQ2VE/ref=sr\_1\_1?ie=UTF8&qid=1523596613&sr=8-1&keywords=12V+dc+fan+200+cfm

# Answer
I kinda doubt that that fan will actually draw 3A. You could probably get away with using your shield--just measure the fan current draw by directly connecting it up to a 12V supply and measuring with a multimeter.

If it actually draws 3A, any of these sounds like a decent idea:

https://www.amazon.com/WGCD-Controller-Module-Stepper-Arduino/dp/B06X9D1PR9/ref=sr\_1\_4?s=electronics&ie=UTF8&qid=1523692716&sr=1-4&keywords=arduino+h+bridge

https://www.amazon.com/Diymall-Module-Stepper-Modules-Arduino/dp/B00NJOTBOK/ref=sr\_1\_8?s=electronics&ie=UTF8&qid=1523692716&sr=1-8&keywords=arduino+h+bridge

https://www.amazon.com/SainSmart-Stepper-Controller-Mega2560-Duemilanove/dp/B00AJGM37I/ref=sr\_1\_11?s=electronics&ie=UTF8&qid=1523692716&sr=1-11&keywords=arduino+h+bridge
> 1 votes

---
Tags: current, motor
---


title: nodemcu pins + sensors reading values

text:
# Question
Title: nodemcu pins + sensors reading values
what are the SDA & SCL pins in NodeMCU? (Pins 20 & 21 in Arduino MEGA2560) I already implemented a simple project to read 2 accelerometers values from Arduino and send them through wifi to firebase database. I used Arduino Mega before for the same project and the sensors gave me readings between approximately -300 to 300. Now when I moved to NodeMCU the sensors became very sensitive and are getting values up to 65500+. And with a very small angle change the axis reading drop down to 20 or less.

I used pins D1 and D2 for SCL and SDA. Are the pins correct? And What about the reading values how to fix that?

# Answer
> 3 votes
The ESP8266 doesn't have a hardware Two Wire Interface. I²C is done in software, so you can use any 2 pins, as long as you specify them in your code using `Wire.begin(SDA, SCL)`.

My guess would be that there's another problem. 65500+ sounds like an integer overflow, for example. (`(uint16_t) -1 == 65535`)

---
Tags: arduino-mega, sensors, i2c, nodemcu
---


title: "Serial does not name a type error"

text:
# Question
Title: "Serial does not name a type error"
I m getting serial does not name a type error, expected declaration before '}' token line 69

```
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;

// defines variables
long duration;
int distance;
int safetyDistance;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(buzzer, OUTPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

// Calculating the distance
  distance = duration * 0.034 / 2;

  safetyDistance = distance;
  if (safetyDistance <= 5) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 1000);
    delay(100);
    noTone(buzzer);
    delay(100);
  }

  else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  if (safetyDistance > 5 && safetyDistance <= 10) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 3000);
    delay(3000);
    noTone(buzzer);
    delay(3000);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  }
  Serial.print("Distance: ");
  Serial.println(distance);

}

```

# Answer
```
  if (safetyDistance > 5 && safetyDistance <= 10) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 3000);
    delay(3000);
    noTone(buzzer);
    delay(3000);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  }                           //<--
  Serial.print("Distance: ");
  Serial.println(distance);

}

```

There is a duplicate `}` after the `else` clause is closed. Remove it and your code will compile.
> 1 votes

---
Tags: arduino-uno, serial
---


title: NodeMCU ESP12 Voltage

text:
# Question
Title: NodeMCU ESP12 Voltage
I'd like to power an NodeMCU off of four 1.5v batteries. That's 6v.

Depending on the source I've read that 5.1v will fry the board and, just a few clicks later, that the board will take up to a 20v input.

What is the real, practical input voltage range for an NodeMCU? Even the spec sheets seem to disagree.

# Answer
> 1 votes
I edited your question and changed ESP-12 to NodeMCU, based on the title and tag.

5.1 V will 'fry' a plain ESP12, but the NodeMCU is development board with esp8266 and the board has a power regulator for USB power or Vin pin. The parameters of the regulator depend on the regulator used by the manufacturer of your board.

---
Tags: esp8266, nodemcu, voltage
---


# Question
Title: Bluetooth a pushbutton from one arduino to another to turn on a LED
For a major project at school i need to get a bluetooth module to be able to communicate between two HC-05 modules as a master and slave. They need to be able to press a pushbutton on the slave and it lights up a LED on the master. I have been able to get the two hc-05's to connect to each other but i cant find a code and wiring that will work for what i need to do. any help will be appreciated. Thanks

# Answer
So, you have done the hard part and now need the easy bit :)

Firstly you need a button (failing that touching two wire together will just about do). There are loads of quick tutorials on the web, here is one https://www.arduino.cc/en/Tutorial/Button. They will end up with you having a pin that goes high or low when the button is pressed, you can either poll/loop to detect the press or go posh and use interrupts (leave that for later). When the pin detects the press you need to send some data via your HC05 link to the master, something like 'ON' or 1, who cares so long as the master understands it. And when it disconnects you need to send a off or 0 message (Remember the number 1 and the character '1' are not the same thing, so make sure you know what you are sending).

When the master receives the command it will execute a bit of code that will send a pin high (lets say pin 7). Connected to pin 7 will be the +ve side of a LED, the -ve leg of the led will be connected to a resistor of 200-250 ohms and the other end of the resistor will be connected to ground. Then when pin7 goes high it will light the resistor.

simulate this circuit – Schematic created using CircuitLab

As always you probably will need to break it down to test it, have a little app that toggles pin 7 high for 2 seconds and low for two seconds, etc (just like blink).

There is a phenomenon called 'bouncing' which is where the useless human finger presses a switch and doesn't instantly create a perfect connection and perfect disconnection. This might make the slave send 101010101010101 when you just expect 1, you can either debounce using software or hardware, but only worry about that if you have a good quality switch :)
> 1 votes

---
Tags: arduino-uno, led, bluetooth, hc-05
---


# Question
Title: Arduino - use print(.., DEC) to save into variable
I am using:

```
Serial.print(rawCodes[i - 1], DEC);

```

to print into serial monitor, but how can I save `(rawCodes[i - 1], DEC)` to save into variable?

# Answer
> 4 votes
Assuming your code comes from here: https://www.alanzucconi.com/2015/08/19/how-to-hack-any-ir-remote-controller/

Since `rawCodes` is declared as

```
unsigned int rawCodes[35];

```

I.e., it is a 35-element array of `unsigned int` elements, we can access a single `unsigned int` element at some index and save it in a variable like

```
unsigned int myVariable = rawCodes[i - 1]; //assuming i is some integer variable
                                           //and exists in this scope

```

If conversion to a `String` object is needed it can be passed into the constructor of the `String` class as

```
String myString = String(myVariable);

```

That answers your syntactical question on how to save that element into a variable; however, it is unlikely that this is your real underlying problem. We cannot determine that until you tell us what exactly you actually want.

References:

---
Tags: arduino-uno, serial, variables
---


# Question
Title: transmit a sequence of bit using arduino uno
How do i code to transmit a sequence of bit using arduino uno?My project is about a transmitter and a receiver.Arduino as the transmitter and an application as the receiver.Light sensor will detect the bits sent.How do i send a sequence of bit for example 00101010.What kind of function should i use? i am a beginner for arduino. thank you.

# Answer
Bit-wise sending of a chunk of data is really just:

* go through each byte of the data
* for each byte (= 8-bits), put each bit on the LED and wait

This also has some substantial drawbacks:

* no error detection or correction. If you get interference on your light sensor / camera due to the environment, you will read wrong data. For this you would need to code the data with some coding scheme or append a checksum
* outputting on the built-in LED on the Arduino Uno / Nano is a bad idea sine it's directly next to the power, RX and TX LED
* outputting in the visible spectrum is asking for interference. That's why we have InfraRed transmissions.
* receiver and transmitter might out of sync; that means that the receiver does not sample the output of the transmitter at the correct time -- you should use a preamble, oversampling and averaging at the receiver to overcome this

That said, you might be better off using other proven methods such as IR, 2.4GHz transceivers, et cetera, from my point of view. Other microcontrollers (example) have even built-in peripherals to do IR transmission according to some protocol.

On the Arduino Uno/Nano you could also use the IRemote library to send and receive data using a cheap IR LED and a IR receiver, many of which are included in starter kits (and are also otherwise cheap).

The code below simply takes a stream of bytes and outputs them bit-wise on the LED. Nothing else done. Also, `digitalWrite` is slow and should be replaced by a faster variant.

```
#include <Arduino.h>

/* LED to output from */
const int LEDTrans = 13;
/* Length of a symbol */
const int timeWait = 500;

const char dataToSend[] = "Hello World";

/* Transmits data bitwise */
void transmitData(const char* data, size_t length) {
    //go through each byte of the data
    for(size_t i = 0; i < length; i++) {
        uint8_t currentByte = (uint8_t) data[i];

        //Go through each of the 8 bits in the byte
        //Goes from LSB to MSB (right-to-left)
        for(int j = 0; j < 8; j++) {
            //uses Arduino.h macro "bitRead"
            bool currentBit = bitRead(currentByte, j);

            //Set the LED on/off
            digitalWrite(LEDTrans, currentBit);
            //Wait for the symbol time
            delay(timeWait);
        }
    }
}

void setup() {
    pinMode(LEDTrans, OUTPUT);
}

void loop() {
    transmitData(dataToSend, strlen(dataToSend));
    //turn LED OFF again
    digitalWrite(LEDTrans, 0);
    delay(2000);
}

```
> 1 votes

---
Tags: arduino-uno, serial, atmega328, bit
---


# Question
Title: Arduino receive response from SIM800H to AT+CCLK? command
I've been trying to make a program that interacts with SIM800H trough AT commands. It worked with the String class, but it was full of "memory leaks" and after a few hours it just hanged. Then I tried to write it again with char arrays, but for some reason I couldn't get it to work properly.

Can someone suggest me a correction to my program and also a way to get char by char with loop and `Serial.read();`? Serial in this case (Arduino Leonardo) is the USB port and Serial1 is the port to the modem.

Here is my code:

```
const long interval = 2000;
static long currentMillis;

char wherecclk = 0; // To determine where is the + in +CCLK in the char array

char serialdata[256] = ""; // Array to store the chars before parsing

char rtcy1[3]; // Current year  Format: yy\0
char rtcm1[3]; // Current month  Format: mm\0
char rtcd1[3]; // Current day  Format: dd\0
char rtch1[3]; // Current hour  Format: hh\0
char rtcmm1[3]; // Current minute  Format: mm\0
char rtcs1[3]; // Current second  Format: ss\0

int rdpos = 0;

void setup() {
  Serial.begin(9600); // USB to Computer
  Serial1.begin(9600); // UART to Modem
  Serial1.print("ATE0\r"); // Disable echo
}

void loop() {
  wherecclk = 0;
  if (Serial1.available () > 0) { // when something comes on real serial
    strcpy(serialdata, "OK\n\n+CCLK: \"04/01/01,01:35:31+00\"\n\nOK\n"); // This is a real sample of the response coming from the modem emulated

    while (rdpos < 256) { // loop timeout: 256 bytes
      if (serialdata[rdpos] == '+') {
        break; // We have reached the first + char. Stop incrementing it
      }
      rdpos++;
    }

    if (serialdata[rdpos + 1] == 'C' && serialdata[rdpos + 2] == 'C' && serialdata[rdpos + 3] == 'L' && serialdata[rdpos + 4] == 'K') { // If the serial command mathes +CCLK save its position
      wherecclk = rdpos;
    }
    rdpos = 0;

    if (wherecclk != 0) {
      rtcy1[0] = serialdata[wherecclk + 8]; // getting first char with its offset
      rtcy1[1] = serialdata[wherecclk + 9];
      rtcy1[2] = '\0';
      rtcm1[0] = serialdata[wherecclk + 11];
      rtcm1[1] = serialdata[wherecclk + 12];
      rtcm1[2] = '\0';
      rtcd1[0] = serialdata[wherecclk + 14];
      rtcd1[1] = serialdata[wherecclk + 16];
      rtcd1[2] = '\0';
      rtch1[0] = serialdata[wherecclk + 17];
      rtch1[1] = serialdata[wherecclk + 18];
      rtch1[2] = '\0';
      rtcm1[0] = serialdata[wherecclk + 20];
      rtcm1[1] = serialdata[wherecclk + 21];
      rtcm1[2] = '\0';
      rtcs1[0] = serialdata[wherecclk + 23];
      rtcs1[1] = serialdata[wherecclk + 24];
      rtcs1[2] = '\0';
    }
  }

  if (millis() - currentMillis >= interval) { // This is done every second
    Serial1.print("AT+CCLK?\r"); // ask for the time
    // delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());
    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    currentMillis = millis();
  }
}

```

Here is the output (a screenshot, because serial monitor doesn't give me full code):

# Answer
> 2 votes
You declare your variables for month and minute differently (`rtcm1[3]` vs `rtcmm1[3]`), but you load `rtcm1` with month, and then a few lines later, with minutes.

# Answer
> 1 votes
Here's the final code in case someone needs it:

```
const long interval = 1000;
static long currentMillis;

char wherecclk = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256] = ""; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

int rdpos = 0;

int pointingfinger = 0;

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (Serial1.available () > 0) { //when something comes on real serial
    rdpos = 0;
    wherecclk = 0;
    if (pointingfinger == 255) {
      pointingfinger = 0;
    }

    serialdata[pointingfinger] = Serial1.read();

    while (rdpos < 256) //loop timeout: 256 bytes
    {
      if (serialdata[rdpos] == '+') {
        break; //We have reached the first + char. Stop incrementing it
      }
      rdpos++;
    }
    if (serialdata[rdpos + 1] == 'C' && serialdata[rdpos + 2] == 'C' && serialdata[rdpos + 3] == 'L' && serialdata[rdpos + 4] == 'K') { //If the serial command mathes +CCLK save its position
      wherecclk = rdpos;
    }

    pointingfinger++;
  }

  if (millis() - currentMillis >= interval) //This is done every second
  {
    pointingfinger = 0;
    //Serial.println("=========");
    //Serial.println(serialdata);
    //Serial.println("=========");
    if (wherecclk != 0) {
      rtcy1[0] = serialdata[wherecclk + 8]; //getting first char with its offset
      rtcy1[1] = serialdata[wherecclk + 9];
      rtcy1[2] = '\0';
      rtcm1[0] = serialdata[wherecclk + 11];
      rtcm1[1] = serialdata[wherecclk + 12];
      rtcm1[2] = '\0';
      rtcd1[0] = serialdata[wherecclk + 14];
      rtcd1[1] = serialdata[wherecclk + 15];
      rtcd1[2] = '\0';
      rtch1[0] = serialdata[wherecclk + 17];
      rtch1[1] = serialdata[wherecclk + 18];
      rtch1[2] = '\0';
      rtcmm1[0] = serialdata[wherecclk + 20];
      rtcmm1[1] = serialdata[wherecclk + 21];
      rtcmm1[2] = '\0';
      rtcs1[0] = serialdata[wherecclk + 23];
      rtcs1[1] = serialdata[wherecclk + 24];
      rtcs1[2] = '\0';
    }
    Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    currentMillis = millis();
  }
}

```

---
Tags: serial, array
---


# Question
Title: Why is this variable giving me always the value of 0?
I am doing a project and here is the code that I am using, but I do not know why the values of duration and sofia is always 0 so the values of distance and monroy are also 0

```
const int trigPin = 9;
const int echoPin = 10;

const int t = 8;
const int e = 7;

long duration, sofia;
int distance, monroy;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(t, OUTPUT);
  pinMode (e, INPUT);
  Serial.begin(9600); // Starts the serial communication
}
void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  digitalWrite (t, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  digitalWrite (t, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  digitalWrite (t, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  sofia = pulseIn(e, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  monroy = sofia * 0.034 / 2;
  Serial.print(duration);
  if (distance = 15);
  {
    digitalWrite (3, HIGH);
    delay (5000);
    digitalWrite (3, LOW);
  }

  if ((monroy >= 0) && (monroy <= 5));
  {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
  }
  if ((monroy >= 5.1) && (monroy <= 9));
  {

    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
  }
  if (monroy >= 9.1);
  {

    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
  }
}

```

# Answer
> 4 votes
When I formatted your code for readability and then compiled it I got these warnings:

```
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino: In function 'void loop()':
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:20: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   if (distance = 15);
                    ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (distance = 15);
                     ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:41:38: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 0) && (monroy <= 5));
                                      ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:47:40: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 5.1) && (monroy <= 9));
                                        ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:53:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (monroy >= 9.1);

```

These are **important** \- you should pay attention to them. For example, here:

```
  if (distance = 15);  // <-- NO SEMICOLON NEEDED HERE!
  {
    digitalWrite (3, HIGH);
    delay (5000);
    digitalWrite (3, LOW);
  }

```

Putting a semicolon there means that stuff under the `if` is **always executed** \- the semicolon terminates the scope of the `if`.

---

To see the warnings open the Preferences dialog in the IDE GUI and change "Compiler warnings" to "All".

---

Also:

```
  if (distance = 15);

```

This **assigns** 15 to distance, so distance will always be 15. You mean:

```
  if (distance == 15)

```

---
Tags: sensors, c++
---


# Question
Title: Make one Arduino fire interrupt on another
**Problem**

I have an Arduino Duemilanove which needs to communicate with an Ardiuno Mega. The only pin available on the Duemilanove is D13. The Duemilanove is in charge of driving state on my robot, and the Mega is in charge of sensor readings and navigation. The Mega needs to send drive state updates to the Duemilanove. I2C, PWM, Serial, anything requiring different pins on the Duemilanove is out of the question at this point.

**Idea** I plan to have the Duemilanove send the "pipe" pin high, triggering an interrupt on the Mega. The ISR will send the current drive state to the Duemilanove which will change pinmode and read a digital pulse. The length of the pulse is the drive state.

**Roadblock** I am having trouble finding an example of how to set this up. I can't get the ISR to fire, and I'm not sure why.

**Mega Code**

```
int pipe = 18;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(pipe, INPUT);
  attachInterrupt(digitalPinToInterrupt(pipe), driveStateISR, CHANGE);
}

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

}

void driveStateISR(){

  Serial.println("ISR fired");
  pinMode(pipe, OUTPUT);

  digitalWrite(pipe, HIGH);
  delay(50);
  digitalWrite(pipe, LOW);

  Serial.println("Pulse sent!");

  pinMode(pipe, INPUT);

}

```

**Duemilanove Code**

```
int pipe = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(pipe, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(pipe, HIGH);
  delay(30);
  pinMode(pipe, INPUT);

  unsigned long duration = pulseIn(pipe, HIGH);

  Serial.println(duration);

  delay(3000);
}

```

Nothing happens at all. I'm thinking the main framework is here, but since there aren't many examples of this out there I'd love to get some other eyes on the issue. Thanks!

# Answer
> 2 votes
You should not do `delay()` or `Serial.print()` inside an ISR. That would cause it to hang. For more information see my page about interrupts and also How do interrupts work on the Arduino Uno and similar boards?

# Answer
> 0 votes
since it is one-way communication, it should be fairly simple, as long as you decide what the protocol you intend to use.

it could be pwm for example -\> the duty cycle is the encoded data; or analog output; or uart tx; ...

after that, pick who the master is and who the slave is. generally it is (much) harder to code a slave so pick the slave that has the necessary hardware on the pin you have and go from there.

---
Tags: interrupt
---


# Question
Title: Why bootloader sizes differs from 0.5 to 8 kilo bytes for different boards?
According to official web info bootloader sizes are **0.5, 2 and 8 kilo bytes** for UNO, Pro mini and ATMega2560. I believe all three boot loaders do similar job of receiving serial link data and write to Flash memory.

UNO and Pro mini use **same/similar** ATMega168/328 chips but boot loader size are 0.5 and 2 KB.

ATMega2560 apparent has a more **advanced MCU** which presumably should use similar or even less memory to do the same task, but the size is significantly large at **8 KB**.

Why sizes differ? Small difference may be explained by different development teams, but, should be **that much different**, from 0.5 to 8KB.

# Answer
Bootloader of the Mini and Uno are pretty much the same. (I can't find the source-code but the hex files are only slightly different).

The 2k is because they haven't updated `mini328.upload.maximum_size` in `boards.txt`. Probably because that would break the board for users that haven't updated the bootloader yet.

The 2560 is using a stk500v2 compatible boot loader instead of Optiboot (uno and mini), because optiboot only supports upto 64kb addresses. Not sure why it is that much bigger though.
> 6 votes

# Answer
Generally speaking the chips offer four possible bootloader size configurations. For example, on the Atmega328 you can have 512, 1024, 2048 or 4096 bytes (notice that the sizes increase by a power of 2).

The chips with less program memory offer smaller bootloaders because they won't want to use a lot of that memory for something that is only used to upload code. The chips with more memory (like the Atmega2560) offer larger bootloaders, ie. 1k, 2k, 4k, 8k (again it increases by a power of 2).

The Uno manages to use a 512 byte bootloader (Optiboot). The Mega, which has more complex instructions (to handle a larger address space) would need larger bootloaders. Also in some cases the bootloader writers add in extra stuff like a debugging console.
> 1 votes

---
Tags: arduino-uno, bootloader, arduino-pro-mini
---


# Question
Title: add ID number to the feather m0 bootloader (flash)
I'm trying to add a serial number to the bootloader's flash area of Adafruit Feather m0 board. Seems like feather m0 0-0x2000 area on the flash is non writable by the arduino sketch. i wanted to add a serial number to address 0x2000 - 8 on the flash. The idea is for the data to be included in the bootloader elf\bin so i can easily flash it on devices and later on access it using flash address (0x2000 - 8) with NVMCTRL.

I've started out with this solution:

downloaded the code from samd21 arduino bootloader github directory and in ./bootloaders/zero edited the boololoader ld script, first the "Memory" section

```
FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x2000 /* First 8KB used by bootloader */
FLASHID (rx) : ORIGIN = 0x00002000 - 0x0008, LENGTH = 8

```

Then the 'sections' section:

```
.id_sec :
  {
    KEEP(*(.myid))
  } > FLASHID

```

This should have saved some room in the end of the flash for the id. now in the main.c file:

```
__attribute__ ((section(".myid"))) const unsigned long ID = 0xdead1234;

```

Which should have saved the 0xdead1234 hex value in the (0x2000-8) address.

The issue is this: I compiled this code and linked it just fine, got .hex,.bin,.elf files. If i'm correct (unless they are somehow compressed) i should be able to see the code 0xdead in the binary. **BUT** i don't. After objdump on the binary(any of them) i can't find the 0xde 0xad in any order anywhere. The `arm-none-eabi-size" --format=sysv -t -x build/.elf` does not show the new section i added no where. Also i do wonder, as i said the 0x2000 address on the flash is non writable once i flashed with atmel-ice \j-link even the bootloader code cannot write to it, i did define in the ld script that i want that memory region part of the flash so i do expect that the compiler + linker + jlink flasher will know to write that data to the right place but not sure.

Anyone got some experience with it ? did it before ?

# Answer
> 3 votes
This is quite an easy fix, actually.

The problem here is the compiler doesn't think the const is used for anything - so it (quite rightly) throws it away.

All you need to do is tell the compiler that it's `used` and all should be good:

```
__attribute__((section(".myid"),used)) const unsigned long ID = 0xdead1234;

```

And when you compile:

```
build/.elf  :
section             size         addr
.vectors            0x40          0x0
.text             0x18d4         0x40
.data               0x5c   0x20000000
.bss               0x34c   0x2000005c
.id_sec              0x4       0x1ff8
.ARM.attributes     0x28          0x0
.comment            0x80          0x0
.debug_frame        0x68          0x0
Total             0x1dd0

```

Properly, though, you should make some more changes to the linker script to properly isolate those 8 bytes of flash (though you don't *have* to).

1. You should reduce `FLASH` by 8 bytes.
2. You should include the FLASHID length in the `__sketch_vectors_ptr` calculation.

That's:

```
MEMORY
{
  FLASH   (rx) : ORIGIN = 0x00000000, LENGTH = 0x1FF8 /* First 8KB used by bootloader */
  FLASHID (rx) : ORIGIN = 0x00001FF8, LENGTH = 8
  RAM    (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000-0x0004 /* 4 bytes used by bootloader to keep data between resets */
}

```

And:

```
PROVIDE(__sketch_vectors_ptr = ORIGIN(FLASH) + LENGTH(FLASH) + LENGTH(FLASHID));

```

That way the compiled bootloader code can never be placed in the FLASHID area (not that it would at the moment, but if a new version of the bootloader were released that used 100% of the lower block of flash it would conflict).

Of course, if all you need is something unique to identify the board with, all AVR and SAMD devices that have built-in USB support have a unique ID number. This is intended to be used as the Serial Number for the USB, but could also be used for a MAC address for Ethernet (or for portions of it anyway) or other unique "node" addresses.

---
Tags: bootloader, adafruit, samd21g
---


# Question
Title: How to write a code to detect how many times the IR detector has detected an IR signal.... HELP
I am trying to write a code so that I can detect how many times the IR detector has detected the IR signal from the IR transmitter.

# Answer
Its quite simple:

```
IRDetectorLibraryObject ir;
int counter = 0;

void setup()
{
    ir.setup();
}
void loop ()
{
    if (ir.detectedSignal())
    {
      ++counter;
    }
}

```
> 0 votes

---
Tags: arduino-uno
---


title: Arduino 4wd rover

text:
# Question
Title: Arduino 4wd rover
Guys i have made an arduino 4wd rover using L298N BRIDGE MODULE, HC-05 and Arduino uno but the power supply output of L298N was very low that even 1 motor is working too slow so please help me with power out put please... Here is the code...

```
#define enA 9
#define in1 4
#define in2 5
#define enB 10
#define in3 6
#define in4 7

int xAxis, yAxis;
int  x = 0;
int  y = 0;

int motorSpeedA = 0;
int motorSpeedB = 0;

void setup() {
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
  // Default value - no movement when the Joystick stays in the center
  xAxis = 510;
  yAxis = 510;

  // Read the incoming data from the Smartphone Android App
  while (Serial.available() >= 2) {
    x = Serial.read();
    delay(10);
    y = Serial.read();
  }
  delay(10);

  // Makes sure we receive corrent values
  if (x > 60 & x < 220) {
    xAxis = map(x, 220, 60, 1023, 0); // Convert the smartphone X and Y values to 0 - 1023 range, suitable motor for the motor control code below
  }
  if (y > 60 & y < 220) {
    yAxis = map(y, 220, 60, 0, 1023);
  }

  // Y-axis used for forward and backward control
  if (yAxis < 470) {
    // Set Motor A backward
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
    // Set Motor B backward
    digitalWrite(in3, HIGH);
    digitalWrite(in4, LOW);
    // Convert the declining Y-axis readings for going backward from 470 to 0 into 0 to 255 value for the PWM signal for increasing the motor speed
    motorSpeedA = map(yAxis, 470, 0, 0, 255);
    motorSpeedB = map(yAxis, 470, 0, 0, 255);
  }
  else if (yAxis > 550) {
    // Set Motor A forward
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
    // Set Motor B forward
    digitalWrite(in3, LOW);
    digitalWrite(in4, HIGH);
    // Convert the increasing Y-axis readings for going forward from 550 to 1023 into 0 to 255 value for the PWM signal for increasing the motor speed
    motorSpeedA = map(yAxis, 550, 1023, 0, 255);
    motorSpeedB = map(yAxis, 550, 1023, 0, 255);
  }
  // If joystick stays in middle the motors are not moving
  else {
    motorSpeedA = 0;
    motorSpeedB = 0;
  }

  // X-axis used for left and right control
  if (xAxis < 470) {
    // Convert the declining X-axis readings from 470 to 0 into increasing 0 to 255 value
    int xMapped = map(xAxis, 470, 0, 0, 255);
    // Move to left - decrease left motor speed, increase right motor speed
    motorSpeedA = motorSpeedA - xMapped;
    motorSpeedB = motorSpeedB + xMapped;
    // Confine the range from 0 to 255
    if (motorSpeedA < 0) {
      motorSpeedA = 0;
    }
    if (motorSpeedB > 255) {
      motorSpeedB = 255;
    }
  }
  if (xAxis > 550) {
    // Convert the increasing X-axis readings from 550 to 1023 into 0 to 255 value
    int xMapped = map(xAxis, 550, 1023, 0, 255);
    // Move right - decrease right motor speed, increase left motor speed
    motorSpeedA = motorSpeedA + xMapped;
    motorSpeedB = motorSpeedB - xMapped;
    // Confine the range from 0 to 255
    if (motorSpeedA > 255) {
      motorSpeedA = 255;
    }
    if (motorSpeedB < 0) {
      motorSpeedB = 0;
    }
  }
  // Prevent buzzing at low speeds (Adjust according to your motors. My motors couldn't start moving if PWM value was below value of 70)
  if (motorSpeedA < 70) {
    motorSpeedA = 0;
  }
  if (motorSpeedB < 70) {
    motorSpeedB = 0;
  }
  analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
  analogWrite(enB, motorSpeedB); // Send PWM signal to motor B
}

```

# Answer
> 2 votes
You need more power!

The formula for power is Volts * Amps. A PP3 has about 500mAh, which means its can (in theory) output 9V at 500mA for an hour, which means you have about 4.5 watts.

So what power do your motors need? I'll assume they are about 1.5W motors, which means you need 6W to drive all the motors.

Your PP3 can output 6W, but it won't last long if it does and it will get hot. Also, if you have 12V motors and are only giving the 9V then they are going to be asking for 1/3 more amps to balance the equation and get their power. You are probably asking the PP3 to supply 1A which means it will last less than 30 minutes if it is brand new and good quality.

A "simple" solution would be to use two (or more) batteries in parallel. Parallel gives you more power without changing the voltage. A better solution would be to look at alternative battery packs, a couple or LiPo 3.7V 1100mAh battery packs, a sealed lead acid gel (heavy). An even better solution would be to see if you can get lower power motors that can supply the same torque.

Failing that, get a meaty desktop power supply and a long cable :)

---
Tags: arduino-uno, hc-05, l298n
---


title: Measuring ADC sample rate - Arduino DUE

text:
# Question
Title: Measuring ADC sample rate - Arduino DUE
I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode. Hints are welcome, I really don't know where to start.

# Answer
Measure how many times per second was main loop called:

```
bool secondPassed()
{
  static long lastTick = 0;
  long now = millis();

  if (now <= lastTick + 1000)
    return false;

  lastTick = now;
  return true;
}

int counter = 0;
void loop()
{
  analogRead(A0);
  counter++;
  if (secondPassed())
  {
    Serial.println(counter);
    counter = 0;
  }
}

```
> 1 votes

---
Tags: arduino-due, adc
---


# Question
Title: if/else statements without comparison operators and curly braces
I recently came across this code in a tutorial. The code works, but this form of syntax seems to differ quite a bit from https://www.arduino.cc/reference/en/language/structure/control-structure/if/, as it's lacking comparison operators and curly braces for statements. Can someone please run down why this works?

```
for (int i = 0; i < 15; i++)
{
lcd.setCursor(i, 1);
if (pressed[i])
  lcd.print("X");
else
  lcd.print(" ");

if (justpressed[i])
  digitalWrite(led, HIGH);
else
  digitalWrite(led, LOW);
 }

```

# Answer
About the missing conditions, e.g.:

```
if (pressed[i])

```

If is supposed to be a boolean, this is the prefered way, as long as the boolean has value zero (0) when false and nonzero when true. It is the same as writing:

```
if (pressed[i] != 0)

```

It is not usual to do this for integers, only for booleans.

About the brackets: If you have only one statement the brackets can be omitted. But it is quite a bad programming practice, since sooner or later you add a statement, without the brackets added and you have a bug introduced.

If you really want to shorten it than instead of

```
if (justpressed[i])
  digitalWrite(led, HIGH);
else
  digitalWrite(led, LOW);

```

use

```
digitalWrite(justpressed[i] ? HIGH : LOW);

```

This is called the Ternary operator.

**update**

Using the remark of wondra but with the ternary operation your code can be

```
for (int i = 0; i < 15; i++)
{
    lcd.setCursor(i, 1);
    lcd.print   (     pressed    [i] ? "X"  : " ");
    digitalWrite(led, justpressed[i] ? HIGH : LOW);
}

```
> 6 votes

# Answer
1. **if (something)** is the same as **if(something!=0)**, if condition is a non-zero value, it is considered as fulfilled condition, read about the Conditionals - The true or false story
2. For single line statements you don't need to use curly braces. But using the braces makes the code more readable and the code is less prone to errors
> 4 votes

---
Tags: programming
---


# Question
Title: esp8266 not responding to the AT commands
I am integrating Arduino Uno with the WiFi module ESP8266. I have already made the connections between the ESP8266 and the Arduino Uno which are :

```
txd uno -> rxd esp8266
rxd uno -> txd esp8266
gnd uno -> gnd esp8266

```

The VCC and chid pind of ESP8266 are connected to an external supply of voltage 3.3V and 160mA current. The code is getting uploaded onto the Arduino and the ESP8266 is also getting powered on.But i am facing a problem while i send the AT commands on the serial monitor. It is not responding even though the red led is on constantly and when i press enter after sending the command , the blue led blinks for a few seconds. Do i have to update the firmware of the ESP8266?

# Answer
I had same problem. It helped to connect GNDs of both power supplies namely the one powering the arduino and the 3.3V one powering the ESP8266.
> 2 votes

# Answer
Okay, I'll just summarize the stuff I've seen in the comments and answers. It's quite a basic issue? You'll find a lot resources on it on the web.

**Current (draw of chip too high?):**

Wireless communication can take a lot of current. You should have a good power supply. Arduino usually can't supply enough current. Check the datasheet of the chip to see it max current draw.

**Rx/Tx (Wiring):**

Be sure you send through the Tx pin, into the Receive (Rx) pin of the other device. Also, you can't use the same Tx pins for USB communication AND to connect to the ESP, that basically won't work.

**Voltage (3.3V vs 5V):**

The arduino runs on 5V, but, the ESP on 3.3V you shouldn't want to mix these up. It'll do in some cases. Putting 3.3V (Tx of ESP) on the Rx of arduino (5V) won't damage it. But the other way around is strongly discouraged. Use a logic level shifter or voltage divider between it.

**Chip might be broken**

If the chip isn't doing anything at all, you should take in consideration that it's possible the chip is broken... I've spent too many hours on debugging my code while the chip simply wasn't working. Also after having applied 5V to the ESP8266, this becomes quite likely.
> 1 votes

# Answer
We had a similar issue and landed up spending a lot of time figuring out what was going wrong, the following certainly helped us resolve the issue:

1. We set the Baud rate of the Serial communication to 1200. This started showing the responses from ESP correctly with no / minimal junk
2. We set the baud rate of communication with ESP to 115200. This ensured that the ESP received correct commands.
3. We ensured that each command we send is terminated by a CR for e.g. ESP8266.println(espCmd + "\r"); // where ESP8266 is SoftwareSerial ESP8266 (rxPin, txPin);
4. Also, powering the ESP module with 5V gave no responses from ESP. When we powered it with 3.3V only then it started to provide any response - initially response looked like junk due to mismatched baud settings.

Hope this helps.

(Sometime you may need to use both \r\n....)

Regards
> 1 votes

# Answer
Seems like you didnt used any type of voltage divider or level shifter between the Arduino Tx -\> ESP8266 RX Line. The ESP8266 isnt really 5V friendly. Too Bad the Arduino outputs 5V on all of it Pins. You could still try it With a Voltage Divider using 2 Resistors or a level Shifter in hope it works. Elsewise With a 3.3V USB-\> UART Module or get a New ESP8266
> 0 votes

# Answer
You missed something bro!

Arduino ESP8266 Rxd -\> Txd Txd -\> Rxd 3.3 V -\> VCC GND -\> GND 3.3 V -\> CH\_PD
> 0 votes

# Answer
Even I faced a similar problem , I was Abel to communicate using AT until I uploaded another program on to the board ,that is initially all esp boards come with the AT response firmware Once you upload ur code or program if I'm not wrong I guess it replaces it so you won't get any response That was my personal experience using all sorts of esp8266 boards (01, nodeMCU ) etc As I'm still learning plz correct me if I have projected it in the wrong way Thanks
> 0 votes

---
Tags: esp8266
---


# Question
Title: Arduino IDE loses programmer after installing Visual Micro
I had this added to programmers.txt

```
mysmartusb.name=mySmartUSB light
mysmartusb.communication=serial
mysmartusb.protocol=stk500v2
mysmartusb.program.protocol=stk500v2
mysmartusb.program.tool=avrdude
mysmartusb.program.extra_params=-P{serial.port}

```

And was getting so annoyed with the loading time of Arduino IDE 1.8.5 so I tried Visual Micro but that didn't go well either. Now, Arduino IDE can no longer see my programmer. Tried rebooting, did a search for all programmer.txt files on the C: and deleted/updated as I thought appropriate. Has anyone else ever had that issue and if so, how did they solve it?

# Answer
> 1 votes
Uninstalled and installed 1.9.0 as I heard that fixes the launch time (it does). I'm aware it's beta but it fixed my issue. I assume reinstalling 1.8.5 would've also gotten me my programmer back.

---
Tags: arduino-ide, programmer, visualstudio
---


title: ESP8266 with Arduino Uno and HTTP POST

text:
# Question
Title: ESP8266 with Arduino Uno and HTTP POST
Im currently new on this and sucessfully made a sound-activated alarm with Arduino Uno and a microphone sensor. (If sound is detected, then it will alarm). Now, I am adding a ESP 8266 module into it so it can perform a HTTP GET or POST to IFTT Maker link.

My problem with it is how can I program the esp with arduino uno? Do I do something like this

> https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

(and add the threshold for the microphone sensor, buzzers and LEDs)??

Thanks for helping

# Answer
Yes, the library

Is suited for your task because it implements talking to a ESP8266 over a software serial. On this serial connection, AT+ commands will be sent. This also means that you must have the AT firmware flashed onto your ESP-01.

If that is not the case you can download the binary image here and flash it with a serial adapter, as instructed with the tools on that page. You can check whether your ESP8266 has the firmware flashed by attach a UART adpater to the TX output. It should print a "ready" on bootup.

For your wire-up, you will just have to add VCC (+3.3V), GND, TX and RX connections to the ESP-01 board, preferable with a big capacitor between VCC and GND, as the ESP8266 draws a lot of power when sending data over WiFi.
> 1 votes

---
Tags: esp8266
---


title: External power vs usb power

text:
# Question
Title: External power vs usb power
I built a sample of my project on a breadboard using little 700mh leds and other components that easily ran off my computers usb. Now I’m building my project to full size. This includes 12 7w leds, soundboard and amps. It’s still going to be controlled by a arduino mega, obviously, the power consumption is substantially higher than the usb or even the arduino can provide. I’m using a high amp power supply that can drive everything including the arduino.

The question is... how will I be able to alter my sketch later??? Is it feasible to use a panel mount usb cord modified to only allow tx and rx, (cut the red and black)? Or will I have to isolate the mega each time I need to send a change to it?

# Answer
> 2 votes
You can modify a USB cable by cutting the power (red) wire. You'll still need the ground wire with RX and TX.

# Answer
> 2 votes
Using an altered USB cable and a separate power supply will work but isn't really necessary. I usually put a connector on my high-current devices like LEDs and whatnot so I can remove them from the equation while I upload code, and for debugging I leave the external power supply attached and use a regular USB cable to the PC (see What happens if I power the Arduino with both the USB and external power voltage simultaneously?).

---
Tags: power, usb
---


# Question
Title: Configuring Accelerometer on BNO055 sensor
I'm using the BNO055 9DOF Adafruit sensor to measure the acceleration/orientation. How can I change the configuration of the accelerometer from 4G (default) to 16G?

What I already know:

The datasheet : https://cdn-shop.adafruit.com/datasheets/BST\_BNO055\_DS000\_12.pdf

From point 3.5.2 from page 27, I need to change xxxxxx01b to xxxxxx11b in the configuration file (that is the library). I use https://github.com/adafruit/Adafruit\_BNO055 but I could not find any information on what to change and where in the .h file.

Any ideas?

Thank you

# Answer
This was partly discussed as an issue on the library's github

Here's how I understand it:

The library doesn't configure the registers you want. I don't see a reference to writing to the `ACC_CONFIG` register (address 8). Not even defined in the header.

The sensor has two register-pages (0 and 1) \[refer page 50\]. I.e. if you select page 0 then the register at address X means something, at page 1 it means something else.

We want to write to `ACC_Config` at address `0x08` on Page 1.

Page 77 tells us that, regarding writing to the register: "Write: can only be changed in sensor mode, see section 3.5.2"

In code, you could hack something in there:

After changing to the sensore mode, you could then write to the register as

```
//values taken from section 3.5.2 page 27
#define BNO055_ACC_CONFIG_2G (0) //0B00
#define BNO055_ACC_CONFIG_4G (1) //0B01
#define BNO055_ACC_CONFIG_8G (2)  //0B10
#define BNO055_ACC_CONFIG_16G (3)  //0B11

//bandwidth definitions
#define BNO055_ACC_BW_7_81_Hz (0)
#define BNO055_ACC_BW_15_63_Hz (1)
#define BNO055_ACC_BW_31_25_Hz (2)
#define BNO055_ACC_BW_62_5_Hz (3)
#define BNO055_ACC_BW_125_Hz (4)
#define BNO055_ACC_BW_250_Hz (5)
#define BNO055_ACC_BW_500_Hz (6)
#define BNO055_ACC_BW_1000_Hz (7)

//powermode definitions
#define BNO055_ACC_PWRMODE_NORMAL (0)
#define BNO055_ACC_PWRMODE_SUSPEND (1)
#define BNO055_ACC_PWRMODE_LP1 (2)
#define BNO055_ACC_PWRMODE_STANDBY (3)
#define BNO055_ACC_PWRMODE_LP2 (4)
#define BNO055_ACC_PWRMODE_DEEP_SUSPEND (5)

#define BNO055_ACC_CONFIG_ADDR 0x08

//Select page ID 1 to write to the right register
write8(BNO055_PAGE_ID_ADDR, 1);
//build the config value with bitshifts
//see page 77
//use all standard values except 16G parameter
uint8_t acc_config = (uint8_t)((BNO055_ACC_PWRMODE_NORMAL << 5)
                   | (BNO055_ACC_BW_62_5_Hz << 2)
                   | BNO055_ACC_CONFIG_16G);
//write new accelerometer config
write8(BNO055_ACC_CONFIG_ADDR, acc_config);

//change back to page ID 0 (or whatever was before there)
//Otherwise we read sensor data from the wrong page with entirely different meaning
write8(BNO055_PAGE_ID_ADDR, 0);

```

Since I don't have that sensor here I have no way to test it. So this is just the basic idea. You can also read registers with `read8`, with which you can verify that before you write anything to the register, it has some standard (or expected) value. E.g., `ACC_CONFIG` should read as `0B00001101` = `0x0d`. And after you write a value there you should be able to read the same value back, otherwise the chip didn't let you execute the write and you have to investigate why.

Yes, you mostly have to do the hard work by yourself. Changing from 4G to 16G might also have the implication that some other calculations on the raw data has to be done different, however I am not sure of that.
> 2 votes

---
Tags: adafruit, accelerometer, bno055
---


# Question
Title: trouble getting out of a for loop in a function and go back to a FSM with a button
I have a finite state machine that goes to a function called patternOne, I can't seam to get out of this function though once I am in it and get back to the finite state machine. When I press a button my serial port shows it's been pressed but still stays in the function patternOne, I don't know how to get out of it and why this is happening. My code is below:

```
#include <SPI.h>
SPISettings settingsA(2000000, MSBFIRST, SPI_MODE1);
#include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
#include <Wire.h>  // Include Wire if you're using I2C
volatile unsigned long prevTime = 0;

int time_interval_for_chip = 5;
int blinking_interval = 500;
unsigned long current_time = 0;
#define PIN_RESET A6  // Connect RST to pin 9

#define DC_JUMPER 0

MicroOLED oled(PIN_RESET, DC_JUMPER);// I2C declaration

const int buttonpin = A8;
volatile int buttonState = 0;   // variable for reading the pushbutton status
volatile int buttonState2 = 0;
int buttonstate3 = 1;
const int buttonpin2 = A7;

enum State {flip, intro, option1, pattern1, intro_flip, option1_flipped, pattern1_flipped, pattern2, pattern3};
//enum is the data type that consists of user defined varaibles ie like the words pattern, intro, ext
State state = flip; //telling the intial state to start at intro

unsigned int column_pattern1[] = {0b0000000100000100, 0b0000001000001000,0b0100000010000010};
//unsigned int column_off_pattern1[]={0b0000000000000100, 0b00000000000001000,0b0100000000000010};
const int css1 = 10;
const int css2 = A0;
void setup() {
  oled.begin();    // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  //  oled.display();  // Display what's in the buffer (splashscreen)
  //  delay(1000);     // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.
  //

  pinMode(css1, OUTPUT);
  pinMode(css2, OUTPUT);
  Serial.begin(9600);
  SPI.begin();
  SPI.beginTransaction(settingsA);

  pinMode(buttonpin, INPUT_PULLDOWN);
  pinMode(buttonpin2, INPUT_PULLDOWN);
  // watermark generates this interrupt
  attachInterrupt(buttonpin, button_pressed, FALLING); // interrrupt 1 is data ready
  //attachInterrupt(buttonpin2, button_pressed2, FALLING); // interrrupt 1 is data ready

}

void loop() {

  // blinking output 4 and 8 while using a finite state machine to change from intro to a patter
  //turning off the desplay when a pattern is chosen

  switch (state) {
    case flip:
    oled.setFontType(1);
  oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
  //oled.setFontType(2);
  //  oled.setCursor(0, 0);
  oled.print(" Flip  Screen?");
  oled.setFontType(0);
  oled.setCursor(0, 30);
  oled.print("yes");
  oled.setCursor(40, 30);
  oled.print("no");
  oled.circle(10, 43, 3.5);
  oled.circle(50, 43, 3.5);
  oled.display();
  buttonState = 0;

  if (digitalRead(buttonpin2) == HIGH) {
        oled.circleFill(50, 43, 3.5);
        oled.display();
        oled.clear(PAGE); // Clear the buffer.
        delay(500);
        //buttonstate3=0;
     state=intro;
  }
   if (digitalRead(buttonpin) != buttonState) {
    oled.circleFill(10, 43, 3.5);
     oled.display();
        oled.clear(PAGE); // Clear the buffer.
        delay(500);
        state=intro_flip;
   }
  break;

    case intro:

      oled.setFontType(1);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("choose pattern");
      oled.circle(10, 40, 7);
      oled.display();
      buttonState = 0;

      if (digitalRead(buttonpin) != buttonState) {

        buttonState = 0; //reset button state
        oled.circleFill(10, 40, 7);
        oled.display();
        delay(500);
        state = option1;

      }
      break;

    case option1:
      oled.clear(PAGE); // Clear the buffer.

      //delay(300);
      oled.setFontType(0);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("Pattern 1");
      oled.setCursor(0, 10);
      oled.print("next");
      oled.setCursor(40, 10);
      oled.print("yes");
      oled.circle(10, 40, 7);
      oled.circle(50, 40, 7);
      oled.display();

      if (digitalRead(buttonpin2) == HIGH) {
        Serial.println("right button pressed");

        oled.circleFill(50, 40, 7);
        oled.display();
        delay(500);
        state = pattern1;

      }
      break;
        case pattern1:
      oled.clear(PAGE);
      oled.display();

      patternONE();
      buttonState=0;
      if (digitalRead(buttonpin) != buttonState) {
        Serial.println("left button pressed");
        //         //delay to register that the button was pressed
        delay(500);
        //
        state = intro;
      }
      break;

////////////////////////////////////////////////////////
///////////FLIPPED FINITE STATE MACHINE/////////////////
////////////////////////////////////////////////////////

case intro_flip:
  oled.flipVertical(true);
    oled.flipHorizontal(true);
     oled.setFontType(1);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("choose pattern");
      oled.circle(50, 40, 7);
      oled.display();
      buttonState = 0;

      if (digitalRead(buttonpin) != buttonState) {

        buttonState = 0; //reset button state
        oled.circleFill(50, 40, 7);
        oled.display();
        delay(500);
        state = option1_flipped;

      }
      break;

      case option1_flipped:
oled.flipVertical(true);
    oled.flipHorizontal(true);
      oled.clear(PAGE); // Clear the buffer.

      //delay(300);
      oled.setFontType(0);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("Pattern 1");
       oled.setCursor(0, 10);
      oled.print("yes");
      oled.setCursor(40, 10);
      oled.print("next");
      oled.circle(10, 40, 7);
      oled.circle(50, 40, 7);
      oled.display();

      if (digitalRead(buttonpin2) == HIGH) {
        Serial.println("right button pressed");

        oled.circleFill(10, 40, 7);
        oled.display();
        delay(500);
        state = pattern1_flipped;

      }
      break;

       case pattern1_flipped:
      oled.clear(PAGE);
      oled.display();

      patternONE();
//      buttonState=0;
      if (digitalRead(buttonpin) != buttonState) {
        Serial.println("left button pressed");
        //         //delay to register that the button was pressed
        delay(500);
        //
        state = intro_flip;
      }
      break;

  }
}////////////////////////////////////////////////////////
///////////Pattern/////////////////
////////////////////////////////////////////////////////
void patternONE() {
buttonState = 0;
   unsigned int chip1 = 0;
  unsigned int chip2 = 0;
  byte inbyte = 0;
  byte inbyte2 = 0;

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

    digitalWrite(css2, LOW);
    chip2 = SPI.transfer16(column_pattern1[i]);
    Serial.print("chip2 column off=");
    Serial.println(chip2, BIN);
    digitalWrite(css2, HIGH);

    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0001010000000000);
    Serial.print("chip1 row 8 on high driver= ");//not the chip is a look behind so the print statments are the previous output
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    delay(1);
    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0100000100000000);
    Serial.print("chip1 row 4 and 6 on low driver= ");
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    delay(2000);

    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0001010001010000);
    Serial.print("chip1 row 8 on low driver= ");
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    delay(1);

    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0100000100000100);
    Serial.print("chip1 row 4 and 6 on high driver= ");
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    digitalWrite(css2, LOW);
    chip2 = SPI.transfer16(column_pattern1[i]);
    Serial.print("chip2 column on high driver= ");
    Serial.println(chip2, BIN);
    digitalWrite(css2, HIGH);

    //turn off the previous column
//    digitalWrite(css2, LOW);
//    chip2 = SPI.transfer16(column_off_pattern1[i]);
//    Serial.print("chip2 column on high driver= ");
//    Serial.println(chip2, BIN);
//    digitalWrite(css2, HIGH);
//
    delay(2000);

  }

}

// watermark generates this interrupt
void button_pressed()
{
  cli();
  //confirmitng that the button was pressed and that its not just like a bounce"
  if (millis() - prevTime > 50) {
    Serial.println("left button pressed");
    buttonState = 1;
  Serial.println("buttonState =");
  Serial.println(buttonState);
  }

  sei();
  prevTime = millis();

}

```

# Answer
From your question, it sounds like you are expecting PatternONE() to return on a button press but I don't see any code in the function that refers to a button or acts on one. The function defines a local variable `buttonState` and initializes it to 0, but never refers to it again.

I suspect you meant that as a declaration of the global `buttonState`, but you have two problems: 1) the function never uses buttonState to initiate a return; and 2) the local definition `buttonState` hides the global one while it is in scope; i.e., while the function is executing.
> 1 votes

---
Tags: interrupt
---