# Question
Title: Communicating between two Arduinos wirelessly only works when both are connected to the same computer
The transmitter is an Arduino Mega 2560 (China) that is connected to a computer over Serial, from which it only reads data and sends it using a SYN115 433mhz transmitter.

The receiver is an Arduino Nano (China) that drives an 8x8 * 5 led matrix and it reads data using a SYN480R 433mhz receiver.

Everything works as it should, when both devices are connected to my computer over USB.

If I unplug the receiver, the transmitter now stops responding to Serial data and I have to upload a sketch to make it work again, no resetting or power cycling works. But even after "fixing" the transmitter, if the receiver is not to connected to my computer but an external USB power supply (2A) it never receives any data.

I can then plug the receiver back into the computer and things work again. Also, if I unplug the transmitter while the receiver is still plugged into the computer, the receiver crashes and resets itself.

Obviously there's some power issue when unplugging USB devices causing feedback, but the real issue is the wireless stops working on external power supply.

Both devices are running, it's easy to confirm since the receiver has some scrolling text, and the transmitter blinks an LED when it receives and sends data.

I read at Serial communication not working between two Arduinos unless connected to computer that both systems need to share ground if connected by wires. Could this affect the wireless signal somehow?

**UPDATE:** Connecting the receiver to a second computer works! (thanks Chris!! I know it was simple, but one can get stuck in one's own thought process ;))

So this is probably power related... Or can the Nano I have require more than just power over USB? I don't touch the serial device on the receiver side at all btw, all it does is read from PIN 2 and pushes data over HW-SPI to the LED matrix.

**UPDATE-2:** Added reciever code as suggested, though I doubt it's the problem here as it's very simple.

```
#include <MD_MAX72xx.h>
#include <RadioHead.h>
#include <RH_ASK.h>

#define RADIO_RX 2
#define RADIO_TX 3 // not used in this scetch but still needed by RH_ASK
#define RADIO_EN 4 // -||-

RH_ASK radio( 1200, RADIO_RX, RADIO_TX, RADIO_EN, true);
MD_MAX72XX mx( SS, 5);

void setup() {
  radio.init();
  mx.begin();
  mx.control(MD_MAX72XX::INTENSITY, 0);
  mx.control(MD_MAX72XX::TEST, 0);
  mx.clear();
}

uint8_t sc_text[128] = "-- No Data --     ";
uint8_t sc_pos;
uint8_t sc_charWidth;
uint8_t sc_charPos;
uint8_t sc_buf[8];

int scrollText() {
  mx.update(MD_MAX72XX::OFF);
  if(sc_text[sc_pos] == '\0') {
    sc_pos = 0;
    return 1;
  }
  if(sc_charPos == 0) sc_charWidth = mx.getChar(sc_text[sc_pos++], sizeof(sc_buf)/sizeof(sc_buf[0]), sc_buf);
  if( sc_charPos < sc_charWidth + 1) {
    mx.transform(MD_MAX72XX::TSL);
    if(sc_charPos < sc_charWidth) mx.setColumn(0, sc_buf[sc_charPos++]);
    else sc_charPos = 0;
  }
  mx.update(MD_MAX72XX::ON);
  delay(100);
  return 0;
}

char desc[64];
int temp1, temp2;
int wind1, wind2;

uint8_t radio_preamble[] = { 0x7d, 0x6f, 0xe4, 0x26, 0xb5 };

struct wttr_packet {
  uint8_t preamble[sizeof(radio_preamble)];
  int8_t temp1, temp2;
  uint8_t wind1, wind2;
  uint8_t desclen;
  char desc[32];
};

bool get_wttr_data() {
  struct wttr_packet packet;
  uint8_t len = sizeof(packet);
  int hasdata = radio.recv( (uint8_t*)&packet, &len);
  if(hasdata && len == sizeof(packet)) {
    if(memcmp( packet.preamble, radio_preamble, sizeof(radio_preamble))) return false
    temp1 = packet.temp1;
    temp2 = packet.temp2;
    wind1 = packet.wind1;
    wind2 = packet.wind2;
    memcpy( desc, packet.desc, packet.desclen);
    desc[packet.desclen] = '\0';
    return true;
  }
  return false;
}

bool hasnewdata = false;

void loop() {
  if(get_wttr_data()) hasnewdata = true;
  if(scrollText() && hasnewdata) {
    if(temp1 == temp2 && wind1 == wind2) sprintf( sc_text, "%s     %d %cC     %d km/h      ", desc, temp1, 0xF7, wind1); // 0xF7 == '°'
    else if(temp1 != temp2) sprintf( sc_text, "%s     %d/%d %cC     %d km/h      ", desc, temp1, temp2, 0xF7, wind1); // 0xF7 == '°'
    else if(wind1 != wind2) sprintf( sc_text, "%s     %d %cC     %d/%d km/h      ", desc, temp1, 0xF7, wind1, wind2); // 0xF7 == '°'
    else sprintf( sc_text, "%s     %d/%d %cC     %d/%d km/h      ", desc, temp1, temp2, 0xF7, wind1, wind2); // 0xF7 == '°'
    hasnewdata = false;
  }
}

```

**UPDATE-3:** Turns out this wasn't a power issue after all. I had forgotten about a voltage divider I put on the board for using it as a transmitter! The radio module has 3.3V TTL so this is needed for the transmitter but NOT the receiver!

Why this made it work plugged in to USB and not any other power brick I have no idea.

# Answer
> 0 votes
Turns out I forgot I had put a voltage divider on the data-line from the receiver since I originally build the board for transmission.

This in turn, somehow, caused the signal from the radio receiver to fall short of the TTL signals when powered by anything other than USB.

I bypassed the divider and everything works as it should again :)

---
Tags: serial, power, wireless
---


# Question
Title: Change format preferences for Arduino IDE in Linux
How can I change Arduino IDE preferences for formatting? I found the preferences file: `<user>/.arduino15/preferences.txt`, but there are no lines that control IDE formatting. In Windows there is a special file for formatting: `<ArduinoIDE_folder>/lib/formatter.conf`.

# Answer
It happened, that my `formatter.conf` was in `/usr/share/arduino/lib/`. So I copied it to `/home/<user>/.arduino15/` folder and made changes that I needed. And also:

> Copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE.
> 1 votes

---
Tags: arduino-ide, linux
---


title: Fixing Error function 'long int map

text:
# Question
Title: Fixing Error function 'long int map
```
Arduino: 1.8.5 (Windows 8.1), Board: "Arduino/Genuino Uno"

C:\Users\julie_000\Documents\Arduino\BIO_199\BIO_199.ino: In function 'void loop()':

BIO_199:19: error: too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

   t1 = map(2, 0, 1023, 2);

                         ^

In file included from sketch\BIO_199.ino.cpp:1:0:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:253:6: note: declared here

 long map(long, long, long, long, long);

      ^

exit status 1
too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

```

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

How do I fix this error?

# Answer
`map` takes 5 parameters, not 4. You have the original lower and upper bounds, the desired lower and upper bounds, but you forgot the actual value you want to map:

```
map(value, fromLow, fromHigh, toLow, toHigh)

```

So

```
t1 = map(t2, 2, 0, 1023, 2);

```

(assuming those numbers are actually meaningful...)
> 4 votes

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


title: Flash String Helper object as variable

text:
# Question
Title: Flash String Helper object as variable
So I have a Bunch of commonly used char arrays to build commands in my library. So to preserve memory, I have them put into flash, via PROGMEM ext,

```
typedef const char PROGMEM ProgChar;
ProgChar AT[] = "AT";
ProgChar AT_RST[] = "RST";

```

Then in my program I have it all go out to A port via:

```
*hws << AT << PLUS << CWMODE << EQUAL; //hws can be any Print type,

```

This is handled by overloading the \<\< operator;

```
static Print &operator <<(Print &obj, ProgChar* arg) {
  char pbuffbuffer[12]; //create a buffer,
  obj.print(loadProgmemVal(arg,pbuffbuffer)); //Load it, and then pass to obj print method.
  return obj;
}

```

But this also overloads the \<\< operator for all const char\* Which makes me have to do a workaround:

```
hws->print(1); //HACK

```

At first, I thought I would overload the operator to handle both a char\* and a Prog Char Object, But unfortunately, they are both treated as the same thing at run-time which makes that idea useless.

So after snooping I find the \__FlashStringHelper type and macro. Which would allow me to have a sepperate type for these variables, and allow me to overload.

But the problem is, I cant find a good way to Create these:

```
const __FlashStringHelper MYVAR = F("Some text to be progchared");

```

Does not compile =/

Now I could probably make some helper method to load them all in, but that is just patching a hack with another hack... Is there any Clean way to do this? So I can use \<\< for all types,

```
*hws << AT << PLUS << CWMODE << EQUAL << 1 << "\r\n"; //1 and Return break...

```

# Answer
Is this legal?

```
typedef const char ProgChar;
ProgChar AT[] = "AT";

```

I would think that the PROGMEM can't be in the typedef, i.e.:

```
typedef const char ProgChar;
ProgChar AT[] PROGMEM = "AT";

```
> 1 votes

---
Tags: arduino-uno, esp8266, flash, progmem
---


# Question
Title: Servo issue, won't go into negative range
I'm trying to create a small laser "turret" with x-axis control. The arduino receives input through IR sensor. I'm having a problem where my servo will preform my up and reset function(moves and prints as intended), but When i preform the down function the servo does not move. I believe the function is executing (it outputs angle to LCD and text to serial monitor) but there is no movement. Any help would be greatly appreciated!

```
#include <IRremote.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>

int IRPIN = 3;
int angle = 0;
int test = 0;
IRrecv irrecv(IRPIN);
decode_results results;
Servo spinnything;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup()
{
    irrecv.enableIRIn();
    lcd.begin(16, 2);
    lcd.backlight();
    spinnything.attach(5);
    spinnything.write(angle);
    lcd.setCursor(0, 0);
    lcd.print("WARNING");
    lcd.setCursor(2, 1);
    lcd.print("!!!LASER!!!");
    delay(1500);
    lcd.clear();
}

void loop()
{
    if (irrecv.decode(&results)) {
        irrecv.resume();
    }
    if (results.value == 0xE172C837) {
        up();
        results.value = 0x00000000;
    }
    if (results.value == 0xE17228D7) {
        down();
        results.value = 0x00000000;
    }if (results.value == 0xE1724CB3) {
        reset();
        results.value = 0x00000000;
    }
    lcd.setCursor(0,0);
    delay(10);
}

void up() {
    if (angle < 180) {
        angle = angle + 18;
        spinnything.write(angle);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Current Angle");
        lcd.setCursor(3, 1);
        lcd.print("=");
        lcd.setCursor(5, 1);
        lcd.print(angle);
        Serial.print("up");
    }
}
void down() {
    if (angle > -180) {
        angle = angle - 18;
        spinnything.write(angle);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Current Angle");
        lcd.setCursor(3, 1);
        lcd.print("=");
        lcd.setCursor(5, 1);
        lcd.print(angle);
        Serial.print("down");
    }
}
int reset() {
    angle = 0;
    spinnything.write(angle);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Current Angle");
    lcd.setCursor(3, 1);
    lcd.print("=");
    lcd.setCursor(5, 1);
    lcd.print(angle);
    Serial.print("reset");

}

```

# Answer
First of all `Servo.write(int)` takes a value ranging from 0 to 180 degrees. Then, servos themselves can only move from 0 to 180 usually. Some can do more, some can do less. But regardless of how much a servo actually moves, you should expect that doing `Servo.write(0)` the servo would rotate all the way to one side, doing `Servo.write(180)` it should go to the other side, doing `Servo.write(90)` it should stay in the middle.

Also, `lcd.setCursor(5, 1);` is basically useless as the lcd driver itself would advance the cursor as the previous characters are written. Just do `lcd.print("= ");` if you want an additional space between the equals symbol and the number
> 2 votes

---
Tags: lcd, servo, code-review, ir
---


title: What is the work of pulseIn?

text:
# Question
Title: What is the work of pulseIn?
I have code for an ultrasonic sensor which I found from a site. Here is the code:

```
#define trigPin 12
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

```

However, I don't understand the work of `pulseIn()` function. I mean, I want to know when the time count starts and when it ends. For example, in this code, does the time start at `digitalWrite(trigPin, HIGH);` or does the time start at the `pulseIn()` function?

If it's the second one, when it stops, then how does the time give us the distance of an obstacle when I am already delaying 1000 microseconds after I send a ping in air?

# Answer
From the docs:

> Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, `pulseIn()` waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds. pulsein

So, in this case, `pulseIn(echoPin, HIGH)` starts counting the number of microseconds until `echoPin` goes HIGH and stores that in `duration`.

It starts and ends on that line, it's what is known as a blocking function. It will really sit there until `echoPin` goes high and tells you how long it took (unless you specify a timeout).

That also means that any delays you have before or after the `pulseIn` call don't affect it in any way.

The way you get distance from this time is by the following equation:

```
distance = (duration/2) / 29.1;

```

You divide by two because it goes out and back so the time would be double that of a one-way travel. The 29.1 is the speed of sound (which is 343.5 m/s =\> 1 / 0.03435 = 29.1). So note the result is in CM's, not inches. You could probably figure it out by looking at the data sheet of the sensor or just get a lot of samples relating duration to distance (you would measure the distance manually) and get an equation that is very similar.
> 9 votes

# Answer
Indeed it would be a problem if you started to measure the pulse length 1000 microseconds after it starts. However, this is not how the HC-SR04 sensor works:

* the sensor is triggered by the **falling edge** of TRIG, at `digitalWrite(trigPin, LOW);`
* the ECHO pulse starts about 0.3 ms after the trigger

That's why a delay of 1 ms doesn't affect the measurement result. `pulseIn(echoPin, HIGH)` will actually wait for the ECHO pin go HIGH, then start measuring the pulse length until it goes LOW again. As such, the duration of the TRIG pulse can be reduced to 10 microseconds (minimum TRIG duration for HC-SR04), to make the measurements faster.
> 2 votes

# Answer
It is important to know that you do not measure the time from trigger start - by setting the Trigger pin HIGH - up to the Echo signal.

The Sensor HC-SR04 starts the measurement by receiving a HIGH on the Trigger input and then sends, a short time later, the time coded as the length of the HIGH level on the Echo pin.

If you use `pulseIn()` 2 ms, i.e. 2000μs, after triggering, it should work fine.
> 0 votes

# Answer
Don't get confused, as the ultrasonic module has a particular way of working. First you set a pulse in the trigpin. When it ends, the module sends 8 bursts of 40 kHz pulses (and thats actually what is used to measure distance, not your pulse in the trigpin, which goes nowhere). At exactly the moment the first burst is sent, the echo pin sets itself in HIGH. When this is happening, the program is in the line of pulseIn, and since echopin is in HIGH it starts timing (because pulseIN(echopin,HIGH) waits for echopin to be HIGH for start timing). When the first pulse of the 40 kHz bounces in the object and gets back to the receiver, the echopin sets itself in LOW. Then the pulseIn function stops the time and returns it. Then the program continues running. This module is a little bit tricky in order to learn the way of working of pulseIn.
> 0 votes

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


title: Fastest reading through i2c

text:
# Question
Title: Fastest reading through i2c
I have an ADXL345 accelerometer and I read it with an arduino through I2C. I want to get readings at a frequency higher than 500Hz. According to the documentation this should be easily achievable, however I've downloaded and used multiple libraries and none of them was able to achieve a sampling rate higher than 100Hz. They were all based on the arduino Wire library which doesn't seen very efficient. Could someone point me to a library or give me pieces of code that will allow me to sample data at 500+Hz? I send the data to matlab, not that it probably matters.

# Answer
> 1 votes
If you want highest possible frequency, I'd use SPI instead. With 16 MHz Arduino, SPI clock can be 4MHz.

The chip only supports I2C at 400 KHz clock, which is way slower. http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf

---
Tags: i2c, accelerometer
---


title: Arduino DUE as a FTDI programmer

text:
# Question
Title: Arduino DUE as a FTDI programmer
I want to use Arduino DUE board as a FTDI programmer.

The task is to program ESP32 module which is connected to the Arduino Serial port.

I can use only DUE Native port. There is no DUE programming port in my design.

# Answer
Yes, it is possible, and not too difficult.
Also, the native port is a lot faster than the programming port ;)
All you need to do is to read the serialUSB data in and write it to the SerialX port, and read the data in from the SerialX port and write it to the SerialUSB port. It's best to do it on a byte by byte basis, and the due should be plenty fast enough.
This code should do the job. Let me know if it doesn't, and I'll take a look. (I have a Due and esp32)

```
void setup(void) {
  SerialUSB.begin(9600); //speed here doesn't matter as far as I am aware.
                         //the serial baud here should match the speed that
                         //you try to upload at to the esp32
  Serial1.begin(9600);   //change the Serial port to suit your needs
}
void loop(){
   if(SerialUSB.available()> 0){
    Serial1.write(SerialUSB.read());
   }
   if(Serial1.available()> 0){
    SerialUSB.write(Serial1.read());
   }
}

```
> 1 votes

---
Tags: arduino-due
---


title: TimerOne.h library for nodeMCU

text:
# Question
Title: TimerOne.h library for nodeMCU
Following is the code I found in Arduino example files. It compiled fine on Arduino UNO. But there was an error when I tried to compile it for nodeMCU 1.0(ESP 12E Module).

```
#include <TimerOne.h>
void setup() {
  pinMode(13,OUTPUT);
  Timer1.initialize(5000000);//5 sec
  Timer1.attachInterrupt(timerIsr);
}
void loop() {}
void timerIsr(){
  digitalWrite(13,!digitalRead(13));
}

```

Following was the error message. I had this kind of error previously on OneWire.h and I solved it by replacing the OneWire.h library with another OneWire.h library that was made especially for nodeMCU.

Error msg:

```
Arduino: 1.8.3 (Windows 8.1), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from D:\iox Prime\TEC project\code\building modules\timerIsrDemo\timerIsrDemo.ino:1:0:

C:\Program Files (x86)\Arduino\libraries\TimerOne/TimerOne.h:39:20: fatal error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

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

```

I searched the library everywhere in the internet to solve this error but end up with no success. I wish somebody modifies the existing library for me. Thank you for the help.

# Answer
> 2 votes
I have found a solution. There is a library called Ticker.h I found this on github: https://github.com/esp8266/Arduino/tree/master/libraries/Ticker

Following is my demo code:

```
#include <Ticker.h>
Ticker ticker;
void setup() {
  pinMode(D7,OUTPUT);
  ticker.attach(1,isrFunc);//tickerObj.attach(timeInSecs,isrFunction)
}

void loop() {}
void isrFunc(){
  digitalWrite(D7,!digitalRead(D7));
}

```

For me, this code worked seamlessly on nodeMCU. Thank you.

# Answer
> 1 votes
The TimerOne library is specifically for Timer 1 on the AVR microcontrollers1. No other microcontroller has the exact same timer structure, so the library cannot be used with them.

You need a library that works with the timers the ESP8266 has, or you need to manually manipulate the timer registers, for which you will need to consult and understand the datasheet.

---

1: It also appears to have #defines in it for ARM (Teensy 3.x) chips.

# Answer
> 0 votes
There is a another Ticker.h for non ESP processors like UNO, see below:

```
// Filename: Ticker_Example - Does'nt work on ESP)
// this is based upon published version V3 of 3/2018
// refer to : https://github.com/sstaub/Ticker/blob/master/examples/Example.ino
// Complete example. Here we created five timers, you can run it and test the result
// in the Serial monitor and the on board LED.
#include "Ticker.h"

void printMessage();
void printCounter();
void printCountdown();
void blink();
void printCountUS();

bool ledState;
int counterUS;

/*
Creates a Ticker object          Constructors / Destructor
Ticker(fptr callback, uint32_t interval, uint16_t repeats = 0, resolution_t resolution = MICROS)
    parameter callback for the function name you want to call
    parameter interval sets the interval time in ms or us when using MICROS_MICROS with the resolution parameter
    parameter repeats sets the number of repeats the callback should executed, 0 is endless
    parameter resolution sets the internal resolution of the Ticker, it can MICROS, MICROS_MICROS or MILLIS
or in Ray's simpler terms...  Ticker (give it a name)(the callback function, interval, number of times, resolution)
*/
Ticker timer1(printMessage, 0, 1);      // once, immediately
Ticker timer2(printCounter, 1000, MILLIS);  // internal resolution is milli seconds
Ticker timer3(printCountdown, 1000, 5);   // countdown 5 times, every second
Ticker timer4(blink, 500);          // changing led every 500ms
// Ticker timer5(printCountUS, 100, 0, MICROS_MICROS); // originally used 'MICRO_MICROS' so the the interval time would be 100us
                                             //with a internal resolution of micro seconds BUT this did not compile
Ticker timer5(printCountUS, 2000, 0, MICROS);  // now set to 2 seconds

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  delay(2000);
  timer1.start();
  timer2.start();
  timer3.start();
  timer4.start();
  timer5.start();
  }

void loop() {
  timer1.update();
  timer2.update();
  timer3.update();
  timer4.update();
  timer5.update();
  }

void printCounter() {
  Serial.print("Counter ");
  Serial.println(timer2.getRepeatsCounter());
//  Serial.println(timer2.counter()); // this original line did not compile
  }

  void printCountdown() {
    Serial.print("Countdown ");
    Serial.println(timer3.getRepeats() - timer3.getRepeatsCounter());
    // Serial.println(4 - timer3.counter());  // this original line did not compile
    }

void printMessage() {
  Serial.println("Hello!");
  }

void blink() {    // blink every 500ms
  digitalWrite(LED_BUILTIN, ledState);
  ledState = !ledState;
  }

void printCountUS() {
  counterUS++;
 // if (counterUS == 10000) {
 // Serial.println("10000 * 100us");
  if (counterUS == 5) {
    Serial.print("5 * 2000mS when millis = ");
    Serial.println(millis());
    counterUS = 0;
    }
  }

/*
Functions called in format 'timer1.start();' for the Ticker previously named timer1

void start()
Start the Ticker. Will count the interval from the moment that you start it. If it is paused, it will restart the Ticker.

void resume()
Resume the Ticker. If not started, it will start it. If paused, it will resume it. For example, in a Ticker of 5 seconds, if it was paused in 3 seconds, the resume in continue in 3 seconds. Start will set passed time to 0 and restart until get 5 seconds.

void pause()
Pause the Ticker, so you can resume it.

void stop()
Stop the Ticker.

void update()
Must to be called in the loop(), it will check the Ticker, and if necessary, will run the callback

status_t state()
Returns the state of the Ticker.

uint32_t elapsed()
Returns the time passed since the last tick, ms or us depending from the resolution.

uint16_t counter()
Returns the number of executed callbacks.
  */

```

---
Tags: library, timers, nodemcu
---


# Question
Title: Can't power HC-05(5v) with Arduino Pro mini (3.3v)?
I am trying to use HC-05 (5V) with Arduino Pro Mini (3.3v) but I have had little success.

I am using a coin cell to power the pro mini which powers it on and is working fine.

But, my HC-05 doesn't power on. I am trying to power it externally using two 3.7v Lipo-batteries that gives a total of 7.4v but I have tried numerous changes and nothing seems to work.

Circuit Diagram attached below.

**Also, HC 05 has an onboard regulator for levelling it to 3.3v**

Please Help!!!

# Answer
> 1 votes
It seems like 7.4V DC is greater than the 5V regulator input range on the HC-05.

For example, in the Core Electronics tutorial for the HC-05 (the tutorial PDF calls it a JY-MCU. I can't find any major differences), the pinout table says the voltage should be from 3.6V to 6V DC:

These same values are confirmed by a back-of-the-circuit-board photo from arduino-info.wikispaces:

Components101 says the range is 4V to 6V.

Unfortunately your coin cell voltage is too low. That leaves you with the following options to drop your voltage (if you must use the 7.4V DC battery). Your choice will probably depend on the Wh capacity of your battery, and how efficient you need the voltage drop circuit to be.

1. Zener diode (few components, inefficient use of power)
2. Voltage divider with resistors (few components, inefficient use of power)
3. Linear regulator (few (IC) or many (discrete) components, inefficient use of power)
4. Switching regulator (many components, efficient use of power (because it does not use a resistor to drop the voltage)

Further details on each of these options are at Lower Voltage Methods Other than Voltage Dividing.

---
Tags: arduino-pro-mini, battery, hc-05
---


title: Understanding how a tilt switch works

text:
# Question
Title: Understanding how a tilt switch works
I am learning Arduino and pardon me if this is nooby. I am trying to make an LED glow when the tilt switch is tilted. The LED should not glow if the tilt is in normal position. The circuit and the code are in the attached image.

Based on my understanding of the code, I thought that when the tilt switch pin 5 is passed with HIGH signal from 5V the IF condition gets satisfied and tje LED on pin 13 would glow.

But it does not happen. The LED just glows before I tilt the tilt switch. Could you please clarify/correct my mistake. Thank you.

Attaching the code below as per suggestion

```
int ledPin = 13;
int switchPin = 5;

void setup() {
  pinMode(ledPin,OUTPUT);
  pinMode(switchPin,INPUT);
}

void loop() {
  Serial.begin(9600);
  if (digitalRead(switchPin) == HIGH) {
    digitalWrite(ledPin,HIGH);
    Serial.print("we are here");
  }
  if (digitalRead(switchPin) == LOW) {
    digitalWrite(ledPin,LOW);
    Serial.print("there");
  }
}

```

# Answer
> 1 votes
Understanding how PULLUP works lead to the solution. Also learnt that switches are supposed to be connected to ground. Thank you all for your time. Especially chrisl.

---
Tags: switch
---


title: Keypad Type 11 numbers only?

text:
# Question
Title: Keypad Type 11 numbers only?
Can someone give me any idea what condition should i use in input 11 numbers only in the switch case? I only want to type and input 11 numbers only but The problem is it can type more than 11 numbers.

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

LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

const byte Rows= 4; //number of rows on the keypad i.e. 4
const byte Cols= 3; //number of columns on the keypad i,e, 3

//we will definne the key map as on the key pad:

char keymap[Rows][Cols]=
{
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};

//  a char array is defined as it can be seen on the above

//keypad connections to the arduino terminals is given as:

byte rPins[Rows]= {1,2,3,4}; //Rows 0 to 3
byte cPins[Cols]= {5,6,7}; //Columns 0 to 2

// command for library forkeypad
//initializes an instance of the Keypad class
Keypad kpd= Keypad(makeKeymap(keymap), rPins, cPins, Rows, Cols);

char entryStr[8];
int i=0;
long number1=0;
long number2=0;

void setup()
{
   Wire.begin();
   lcd.init();
   lcd.backlight();
   Serial.begin(9600);
   delay(100);

}

```

# Answer
Three simple approaches.

1. You could get a string, and limit it to 11 characters in length. You then convert the string to `num`
2. You could check that 9999999999\<`num`\<=99999999999
3. You could count the number of valid 'kpd.getKey()' and when it gets to 11 exit the function (returning `num` as it stands)

The OP suggests only 11 digits. Of course, if less that 11 digits are acceptable, the returning value could be padded with `0`.

`lcd.print1 can natively takes a string, and the best approach is to treat`num\` as a string instead of as a number. A number (in itself) is only useful if you want to do arithmetic. A lot of times a series of digits are used as an identifier - these are not really numbers but strings with a limited character set.

Some examples (not tested):

**Example 1:** counting the digits entered. Simply added a counter `numcount` \- you can see where I use it in the conditional loop, where I increment it, and where I clear it.

```
long GetNumber()
{

  long num = 0;
  long numcount = 0;
  char key = kpd.getKey();
  while(key != '#' && numcount <= 11)
  {
    switch (key)
    {
    case NO_KEY:
      break;
    case '0':
[... skipped for brevity ...]
    case '9':
      lcd.print(key);
      num = num * 10 ;
      num= num+ (key-'0');
      numcount += 1;
      break;
  case '*':
    num = 0;
    numcount = 0;
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Re-type number:");
    lcd.setCursor(0,1);
    break;
  }
  key = kpd.getKey();
}
return num;
}

```

**Example 2:** Simple check on the value of `num`. In this case both the "#" and `num` reaching a certain value will exit the function in a controlled way. A better loop method would be to `loop ... until` \- checking the condition at the end of the loop rather than at the beginning.

```
long GetNumber()
{
  long num = 0;
  char key = kpd.getKey();
  while(key != '#' && num <= 99999999999)
  {
    switch (key)
    {
    case NO_KEY:
      break;
    case '0':
    [... skipped for brevity ...]
    case '9':
      lcd.print(key);
      num = num * 10 ;
      num= num+ (key-'0');
      break;
    case '*':
      num = 0;
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Re-type number:");
      lcd.setCursor(0,1);
      break;
    }
    key = kpd.getKey();
      }
  return num;
}

```

**Example 3:** using a string. Same comment about checking conditions at the end of the loop instead of the beginning apply. I haven't worked with strings in C for a few decades, so the routines I used (`strlen`, `strcat`) may need some work or tweaking.

```
string GetNumber()
{
  string num = "";
  char key = kpd.getKey();
  while(key != '#' && strlen(num) <= 11)
  {
    switch (key)
    {
    case NO_KEY:
      break;
    case '0':
    [... skipped for brevity ...]
    case '9':
      lcd.print(key);
      num = strcat(num,key)num * 10 ;
      break;
    case '*':
      num = "";
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Re-type number:");
      lcd.setCursor(0,1);
      break;
    }
    key = kpd.getKey();
    }
  return num;
}

```
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: Sending servo position data from one Arduino to another
I'm trying to take the position data generated from this servo sweep, and send over serial to another Arduino. The position data is stored as `pos` in the code I included, what would be the best method for doing this?

```
/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

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

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

# Answer
> 0 votes
Yes, sending data over Serial is as simple as using `Serial.write()` or it's siblings. When sending data over Serial you have to consider, how you want to send it.

1. **Raw binary data:** You can simply use the `Serial.write()` command, which will send the variable as binary data. If you whatch this on the serial monitor of your PC, you will not see readable numbers, because what is shown there is interpreted as ASCII-encoded data, where every byte value has a corresponding character (for example the value 97 is the letter 'a'). On the other Arduino you just use `Serial.read()` to write the byte data directly to a variable. This is practical, if you are sending always the same amount of data (like the value of one sensor). If the length of a message is variable, you have to use a delimiter, to mark the end of a message. Here the second way is more save.
2. **ASCII encoded data:** You can send your data human readable as ASCII encoded data. The value 128 then would consist of 3 bytes, one for each character. Here you always have to use a delimiter, so that the receiver can tell the values apart. A common message delimiter is the newline character '\n'. On Windows you also often have newline and carriage return '\r' together. For decoding you can use one of the many functions, that convert a string/character array to a number with the wanted format (in your case integer), for example `atoi()`.

Refer to the Serial examples in the Arduino IDE to see the code in action.

Note: Since the value of `pos` only varies between 0 and 180, you can use one byte to save and transmit it, instead of the 2 bytes the integer uses.

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


# Question
Title: How can I add phonebook entry to sim card using Arduino GSM shield?
I am using Arduino GSM Module and Arduino UNO

I want my GSM module to be stand alone once I programmed it. It will store the phone number of the user if he sends a correct passcode. Since I want the data to available even after I power off my module. I need to store it to my sim. I don't want to use an SD card shield or store data to arduino's EEPROM.

I have read Getting the contacts/ storing contacts to SIM card. The only clear reply is reading from the SIM.

Is it possible to add phonebook entry to SIM card? Do you know a tutorial?

# Answer
> 1 votes
.

Hope this helps.

Go check out (http://m2msupport.net/m2msupport/sim-phonebook-at-commands/) I use these commands on my AI Tinker A7 board for the Arduino.... 95% work perfectly...

Cheers, Capt.K

ps. I made these numbers up but the formats are all correct.

```
//----------------------------------------------------------
//---Add Entry To PhoneBook:
//----------------------------------------------------------

AT+CPBW=1, "+61416199234",145, "Paul"    //-- add entry x1

OK

//----------------------------------------------------------
//--DELETE phonebook entry:
//----------------------------------------------------------

AT+CPBW=1  //-- delete entry x1

OK

//----------------------------------------------------------
//-- AT+CPBW=[<index>],<number> [ ,<type> [,<text>]]
//----------------------------------------------------------
//
//<index>   = Entry Number in SIM Memory
//<number>  = "The Phone number"
//<type>    = "The Phone Number" (TYPE ) ie. 129,161,145,177..
              //  129 – National number type
              //  161 – National number type
              //  145 – INternational number type
              //  177 – Network specific number
//<text>    = "Person Name" etc.

//----------------------------------------------------------
//  Add 4x new entries to the SIM card
//----------------------------------------------------------
AT+CPBW=1, "+61416199234",145, "Pops"
AT+CPBW=2, "+61420921234",145, "Mum"
AT+CPBW=3, "+61733728171",145, "Wendy"
AT+CPBW=4, "+61356821234",145, "Mr Smith"

//NOTE:  In Australia (above examples) the actual phone numbers
//       above are of these types
//
// Int.Format    Aust. Dial Internal       Phone_Type
// -----------------------------------------------------------
// +61416199234  (0416) 199 234             Mobile/Cell
// +61420921234  (0420) 921 234             Mobile/Cell
// +61356821234  (03)   5682 1234           Landline/PSTN

```

---
Tags: arduino-uno, gsm
---


# Question
Title: Cannot receive data from GPS SD Shield V2-B
I am attempting to receive GPS data from a GPS SD Shield V2-B purchased from maplin. I have attempted the very simple sketch they provide on their website linksprite.com. I have also tried following a tutorial found here: http://tronixstuff.com/2014/01/15/tutorial-arduino-mediatek-3329-gps/. This is the code i am using:

```
    // Example 19.1

    #include <SoftwareSerial.h>
    SoftwareSerial GPS(2,3); // configure software serial port -

    void setup()
    {
      GPS.begin(9600);
      Serial.begin(9600);
      pinMode(13,OUTPUT);
    }
    void loop()
    {
      byte a;
        if (GPS.available() > 0 )
      {
        a = GPS.read(); // get the byte of data from the GPS
        Serial.write(a);
        digitalWrite(13,HIGH);
        delay(1000);
        digitalWrite(13,LOW);
        delay(1000);
      }
    }

```

I am using an Arduino 101. The jumpers on the GPS shield are set up as follows:

I have attempted using both power simply from my Mac and an external 9V battery connected to the Arduino. The 'blink' has been added the sketch to test whether data was being received but there was a problem with the serial monitor. This is not the case because the blink did not occur. It however did occur when moved outside of the if statement as you would expect. Any help or suggestions would be much appreciated.

# Answer
You need to set the jumps as per the instructions that came with the shield ... PAGE4 : short jumpers TX and MRX .... and RX and MTX
> 1 votes

---
Tags: arduino-uno, arduino-ide, softwareserial, gps
---


# Question
Title: Is it possible to use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage?
In STM32 microcontrollers it is possible to use a technique that ST calls **IAP**, or **In-Application Programming**, in order to write to the Flash memory from your running application. They even have a nice Application Note (ex: AN2594) to describe a really ingenious way to use two Flash memory pages to emulate EEPROM while using "wear-leveling" to reduce Flash memory wear during erase cycles.

I have wondered for years: can AVR do this? Ex: the ATmega328 mcu in the Arduino Uno, Nano, etc--**can you write code to store data from your application into Flash memory, thereby increasing non-volatile storage space for data acquisition for instance?**

If so, can you please point me to some resources or examples, including example code, reference manuals or datasheets, etc, that might help me implement this? I've done some looking in the datasheet and haven't found anything so far but maybe I'm just not looking hard enough or know well enough what I'm looking for.

# Answer
> 5 votes
The answer is **"yes, you *can* use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage, very similar to an STM32 microcontroller."**

One of these days I'm going to write an Arduino library to make this really easy for the beginner. For now, however, I'm going to simply post links to valuable references that contain the full answers and that I still need to thoroughly study myself.

## Documentation on how to implement Flash memory reading/writing:

-This is frequently called "self programming" by Atmel (now owned by Microchip).

To find these resources I went to the main ATmega328 reference page then clicked the "Documentation" link, then I searched the web page for the word "flash".

Here's what I found (in order of importance--most pertinent references first):

1. AVR106: C functions for reading and writing to Flash memory on tinyAVR and megaAVR devices
    1. "Description: This application note provides C functions for accessing the Flash memory using the Self programming Program memory which allows to reprogram the Flash memory during program run."
    2. "Introduction: The Atmel® AVR® devices have a feature called Self programming Program memory. This feature enables an AVR device to reprogram the Flash memory while executing the program. Such a feature is helpful for applications that must self-update firmware or store parameters in Flash. This application note provides the details about the C functions for accessing the Flash memory."
    3. This Application Note contains source code, including with the following ready-to-use C functions:
        * `ReadFlashByte()`
        * `ReadFlashPage()`
        * `WriteFlashByte()`
        * `WriteFlashPage()`
        * `RecoverFlash()`
2. AVR105: Power efficient high endurance parameter storage in tinyAVR and megaAVR devices Flash memory
3. AVR116: Wear Leveling on DataFlash
4. Atmega328 datasheet
    * Section 30: Boot Loader Support – Read-While-Write Self-programming (BTLDR), p. 328-344.
    * As pointed out by user SDF in his answer, especially pay attention to Section 30.8: Self-Programming the Flash, p. 334-342.
    * Also see Section 12.2: In-System Reprogrammable Flash Program Memory, p36
    * And Section 31.6: Page Size, p. 349.

# Answer
> 5 votes
Yes you can. This Arduino IDE add on lets you make calls to code store in the bootload of memory so you can make changes to the flash memory. https://majek.sh/en/writing-to-internal-flash-on-arduino/

The number of times you rewrite a cell are limited. I'd suggest you are better off with adding a FRAM memory chip. Get a 5V part with SPI interface. Fast reads, virtually unlimitless writes (trillions) https://www.digikey.com/products/en/integrated-circuits-ics/memory/774?k=fram+memory&k=&pkeyword=fram+memory&pv276=15&FV=ffe00306%2C1f140000%2C1fec000b&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25

# Answer
> 1 votes
Take a look at section 30.8 in the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P\_Datasheet.pdf

It has all the information to reprogram the bootloader section of the flash during runtime.

The bootloader partition size can be adjusted as well.

---
Tags: avr, eeprom, datalogging, flash, emulation
---


# Question
Title: ESP8266 cannot create TCP connections to this particular server
**EDIT**: I have created an issue about this here: https://github.com/esp8266/Arduino/issues/4593

---

**I have this server:** `185.205.210.197` (Check that it works: http://185.205.210.197/)

**And I have this code in my ESP8266:**

```
#include <ESP8266WiFi.h>

#define HOST "185.205.210.197"
#define PORT 80
#define WIFI_SSID "SSID"
#define WIFI_PSW "PASSWORD"

const char* ssid = WIFI_SSID;
const char* password = WIFI_PSW;

void setup () {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(5000);
    Serial.println("Connecting to Wifi...");
  }

  while(!pingServer()) {
    delay(3000); //Send a request every 3 seconds
  }
}

void loop() {}

bool pingServer() {
  WiFiClient client;

  if (!client.connect(HOST, PORT)) {
    Serial.println("connection failed");
    return false;
  }

  Serial.println("connection success!");
  return true;
}

```

**The expected result:** Connection success, but got connection failed.

If I try connecting with my PC, it works, **only with ESP8266 it doesn't**.

Tapping with Wireshark I suspect that there is a problem with ESP8266 TCP packets, here I leave them for you to analyze:

**PC TCP connection request (which works):**

`000030006b081c001a48ea4c0000000010009e098004dba400000000800401009e090b221f000000c603000004000000880254009801a7ad45b7000af5f4e90c000af5f4e90c603c0000aaaa0300000008004500003c000040003706cb37b9cdd2c5c0a82b490050df312dfea1498c6ac92aa0120000079c00000204058c0402080a336f35554aeb0fe90103030700ead7d1`

**ESP8266 TCP connection request (which receives no response from server):**

`000019006f080000952a9f520000000012049e098004daa1000801a200000af5f4e90c2c3ae80f137f000af5f4e90c5000aaaa0300000008004500002c00030000ff06431dc0a82b70b9cdd2c5c00100500000196d000000006002086040f80000020402189ccdd933`

**What I've also checked:**

* The ESP connects fine to other servers.
* There is no firewall blocking the connection between ESP and the server.
* I've tried this in different networks and conditions, the error persists.
* Other computers can connect to the server, so ESP should be able as well.
* Tried with different ESP8266 boards to rule out hardware malfunctioning.
* I am using NODEMCU V0.9 board (original firmware) with Arduino IDE and this ESP8266 library.

**How to replicate:**

1. Using the latest Arduino IDE and ESP8266 library.
2. Check that the test server works at http://185.205.210.197:80/ (just open this link basically and see that is running nginx).
3. Copy and upload the code above to your ESP8266 (NODEMCU or similar).
4. Open the Arduino IDE console/monitor and confirm that no connection is established to port 80.
5. Rage in admiration for such a strange bug.

**I've opened an Issue for this:** https://github.com/esp8266/Arduino/issues/4593

# Answer
> 1 votes
Not a cookie cutter answer, I did a quick test and my ESP8266 does connect to you nginx. Of course you do not accept the params from my fridge, but this is what I see in the log.

```
7007 :
7010 :

For online documentation and support please refer to
7012 : nginx.org.

7015 : Commercial support is available at
7018 : nginx.com.

7020 :
7022 :

Thank you for using nginx.

7024 :
7026 :
7028 : HTTP : closing connection

```

You should be able to see that on your side as well.

I am using letscontrolit/ESPEASY https://github.com/letscontrolit/ESPEasy

And their code to connect looks like

```
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  if (!ControllerSettings.connectToHost(client))
  {
    connectionFailures++;
    addLog(LOG_LEVEL_ERROR, F("HTTP : connection failed"));
    return false;
}

  boolean connectToHost(WiFiClient &client) {
    if (!checkHostReachable(true)) {
      return false; // Host not reachable
    }
    byte retry = 2;
    bool connected = false;
    while (retry > 0 && !connected) {
      --retry;
      connected = client.connect(getIP(), Port);
      if (connected) return true;
      if (!checkHostReachable(false))
        return false;
    }
    return false;
}

```

I am using generic HTTP for my controller which here: https://github.com/letscontrolit/ESPEasy/blob/503fd3555e010b08b48fb2dc18290ef120005308/src/\_C008.ino

You could try the connect to function to see if that works for you.

---
Tags: esp8266, arduino-ide, networking, tcpip
---


# Question
Title: Libraries/classes using other libraries/classes
This is, hopefully, a simple issue!

I'm trying to access my fully working libraries (fully compiles, and works with the hardware perfectly) from another library (Computer.h) to abstract it away from the Sketch.ino file.

LLRelay, and all my other libraries, work flawlessly when instanced/constructed/built/etc within the main Sketch.ino; however, when called within "Computer.h", there's issues.

I've been at this for most of the day trying different things, from instantiating the libraries in the header files, the \*.cpp files, to within functions, to changing the scope and publicity/privacy of them - still no luck. See the (2 * "HERE -") comments for the errors.

Any help is greatly appreciated!

This is what I have managed to reduce it down to for debugging:

Sketch.ino

```
// Sketch.ino
#include "Computer.h"

Computer pc1;

void setup(){};

void loop(){
    pc1.update();
};

```

Computer.h

```
// "../customLibs/Computer.h"
#ifndef Computer_lib
#define Computer_lib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class Computer {
    public:
        Computer();
        void update();
    private:
        void fans();
};
#endif

```

Computer.cpp

```
// "../customLibs/Computer.cpp"
#include "Computer.h"
#include "src/relay/LLRelay.h" /* Potential culprit, I have tried many variations and locations for this to go, all with the same, or similar compilation errors */

/* HERE - "undefined reference to `LLRelay::LLRelay(unsigned char)'" */
LLRelay fan1(13); // fan1(uint8_t relayPin);

Computer::Computer(){
    Serial.begin(9600);
};

void Computer::update(){
    fans();
};

void Computer::fans(){

    /* HERE - "undefined reference to `LLRelay::On()'" */
    fan1.On();

};

```

LLRelay.h

```
// "../customLibs/src/relay/LLRelay.h"
#ifndef LLRelay_lib
#define LLRelay_lib
#if(ARDUINO > 100)
  #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class LLRelay {
  public:
    LLRelay(uint8_t relayPin);
    void On();
    void Off();
  private:
    uint8_t _relayPin;
};
#endif

```

LLRelay.cpp

```
// "../customLibs/src/relay/LLRelay.cpp"
#include "LLRelay.h"

LLRelay::LLRelay(uint8_t relayPin){
  _relayPin = relayPin;
  pinMode(_relayPin, OUTPUT);
  digitalWrite(_relayPin, LOW);
};

void LLRelay::On(){
  digitalWrite(_relayPin, HIGH);
};

void LLRelay::Off(){
  digitalWrite(_relayPin, LOW);
};

```

# Answer
The Arduino IDE must detect the library to include it in the build process. It is done by matching a library to a header file by searching the libraries in configured library locations. Only the root folder and the `src` subfolder of a library are searched.

If your library is in the sketch folder's `libraries` subfolder and it is called `customLibs`, then only the `customLibs` folder and the `customLibs/src` subfolder are searched and the include file `LLRelay.h` in `customLibs/src/relay` folder is not found.

reference: Layout of library folders and files
> 1 votes

# Answer
The Arduino build process does not consider libraries used from other libraries. You will need to include `src/relay/LLRelay.h` in the main project file in order to make it compile.
> 0 votes

---
Tags: library
---


title: How to use the HC-05 properly?

text:
# Question
Title: How to use the HC-05 properly?
It all started when I was working on my Arduino project, which involves an Arduino Nano, an HC05 module and a bunch of sensors (DHT 11, soil moisture and LDR) with Blynk App. Everything worked as it should (compiled properly) but there was no transfer of data (HC05 was paired).

At that time before pairing, the HC05 was blinking rapidly and after pairing it was blinking twice rapidly every 5 seconds. **Note** I connected everything as the example said... (You know HC05s TX RX to HW Serial Pins vice-versa).

So later I tried again with everything stripped out (took out all sensors and just the barebones sketch) and added the button widget in the app to control the Nano's onboard LED). Again everything worked as it should but there was no connection between the HW and the Blynk APP (it was not switching on the LED).

Then I tried with an another Bluetooth app and it didn't work as it should. Then I got to know something's wrong with the board itself. So I tried to boot it into AT command mode with this Guide. But it wasn't accepting any commands (NO replies).

So what do I do?

**NOTE:** I didn't get any relevant question so sorry for that. And do you need anything else?

**Edit:** It worked. I dont really know how. I think there was maybe a problem with the voltage divider but not sure. Thanks for your time and answers.

# Answer
> 1 votes
Maybe you use the wrong baudrate with your hardware serial. Your tutorial states, that 38400 baud is the default, but I found other sources (HC-05), that say the default is 9600 baud (which is also true for my HC-06 modules). Try 9600 baud and if it still doesn't work try some other standard baudrates.

# Answer
> 0 votes
This worked perfect for me HC-05

Try it out.

# Answer
> 0 votes
Try enetering AT mode and change the default baudrate for HC-05. Maybe use some higher baudrate, it improves communication. Also, check if you’re doing the serial reading properly.

---
Tags: serial, arduino-nano, bluetooth, hc-05, blynk
---


title: Motor does not move with 4 batteries

text:
# Question
Title: Motor does not move with 4 batteries
I mada a 4wd car with ultrasonic sensors and servo. I use 4 AA 1.5 volt batteries for power. But the motor does not move. What is the problem?

# Answer
> 2 votes
In the future, please detail your attempts at solving the problem so far so we can help you better.

Approach the issue as methodically as possible. I don't know how familiar you are with electronics, so please excuse me if you think some of these questions are basic:

1. Ensure that the servo motor works first without any other motors or sensors connected to the Arduino Sensor Shield (have you used this servo motor before?)
2. Ensure that your GVS wiring is in the correct order. Servos come with a 3 way socket that plug straight onto the Sensor Shield: G goes to the Brown or Black wire, V goes to the (middle) Red wire, S goes to the Orange wire. The good news is as the +5V is in the middle, things will not blow up if you put the 3-pin plug on the wrong way. The servo just will not work until you plug it in correctly.
3. Is the Arduino Sensor shield working correctly. Does the LED pin work? Do other signals sent from the board work?
4. Remember that servo motors work differently to normal DC motors. You need to use Pulse Width Modulation to set the position. If you have never done this before, you will find the Arduino Servo Motors page useful. Also, you will get some excellent understanding and code from this Adafruit page. It is for a different Arduino shield, but the principles are the same.

# Answer
> 0 votes
Use a LiPo battery I.e 2S(7.4V)

---
Tags: power, motor, battery
---


# Question
Title: BridgeServer REST API with more string values
I wold like to make me a REST API with string values and more string Keys.

like: ~http://url.tld/foo/bar/xy to get "bar" and do more...

Can somebody tell me how to get the second word out of the URL? In this case "bar".

The tutorial show's how to use /arduino/digital/13/1 as to set pin 13 High.I would like to get a different syntax. Something like this: arduino/device1/switch/on

By now i searched quite long and tested different things as you can see below, but i can't get more than one word caught to trigger from the client object.

is boils down to the question why my client object changes the payload.

this part:

```
void process(BridgeClient client) {
  String url0 = client.readString();
  Console.print("process url0: ");      // --> is "bar/xy"
  Console.println(url0);
  String command = client.readStringUntil('/');
  String url1 = client.readString();
  Console.print("process url1: ");
  Console.println(url1);               // --> is "" aka:empty!

```

i made a MWE to show what i already did:

```
// Libraries:
#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>
#include <Console.h>

// Constants:
const bool on = HIGH;
const bool off = LOW;

// Objects:
BridgeServer server;

void setup() {
  pinMode(6, INPUT_PULLUP);
  Bridge.begin();
  server.begin();
  Console.begin();
  while (!Console);
  Console.println("setup done..");
}

void loop() {
  BridgeClient client = server.accept();
  if (client) {
    process(client);
    client.stop();
  }
}

void process(BridgeClient client) {
    String url0 = client.readString();
    Console.print("process url0: ");   // --> is "bar/xy"
    Console.println(url0);
    String command = client.readStringUntil('/');
    String url1 = client.readString();
    Console.print("process url1: ");
    Console.println(url1);             // --> is "" aka:empty!
  if (command == "device1") {
    device1(client);
  }
  if (command == "status") {
    Console.print("process: command == status  | command: ");
    Console.println(command);
    statusCommand(client);
  }
}

void device1(BridgeClient client) {
  String URL = client.readString();
  Console.println("URL:");
  Console.println(URL);                               // ---> is "on"
  String mode = client.readStringUntil('\r');
  Console.println("mode:");
  Console.println(mode);                            // ---> is ""
  String value = getStringPartByNr(URL, '/', 1);
  Console.println("value:");
  Console.println(value);                            // ---> is ""
  power(on);
  if ( URL == "on"){
    client.print(F("found /on"));
    power(on);
  }
  else if ( URL == "off"){
    client.print(F("found /off"));
    power(off);
  }
}

void power(bool on_off){
  bool checkpin = digitalRead(6);                          // machine state
  if (checkpin == LOW && on_off == HIGH) {        // means power is off and on is called
    digitalWrite(13, HIGH);
    Console.print(" checkpin == LOW && on_off == HIGH [1] ");
  }
  else if (checkpin == HIGH && on_off == LOW) { // means power is on and off is called
    digitalWrite(13, LOW);
    Console.print(" checkpin == HIGH && on_off == LOW [2] ");
  }
}

void statusCommand(BridgeClient client) {
}

// splitting a string and return the part nr index split by separator
String getStringPartByNr(String data, char separator, int index) {
    int stringData = 0;        //variable to count data part nr
    String dataPart = "";      //variable to hold the return text
    for(int i = 0; i<data.length()-1; i++) { //Walk through the text one letter at a time
        if(data[i]==separator) { //Count the number of times separator character appears
            stringData++;
        } else if(stringData==index) { //get the text when separator is the rignt one
            dataPart.concat(data[i]);
        } else if(stringData>index) { //return text and stop if the next separator appears
            return dataPart;
            break; // - to save CPU-time
        }
    }
    return dataPart; //return text if this is the last part
}

```

# Answer
You misunderstand the networking Client class concept. It is a stream like the Serial object. Bytes are stored in the Client object's buffer only until you read them.
> 1 votes

---
Tags: arduino-yun
---


title: Arduino with stepper motor

text:
# Question
Title: Arduino with stepper motor
I'm trying to control a stepper motor for my FYP with an Arduino Mega. I tried code form examples, stepper one revolution. It worked when I uploaded it but if i turn the power off during the half position of a revolution, then next time I turn on the supply it first moves that portion backwards then it works according to the program. I want that when I turn on the power supply it should move according to the code and forget the last movement. Can anybody help me on this issue?

# Answer
A stepper motor doesn't have any mechanical "steps" as such. When powered off, a stepper is free-wheeling. When you power it up - energize a set of set of coils - the rotor will move to the nearest of several positions corresponding to whichever coils are energized. Thus, it doesn't retain its position across a power-down; your code has to "find it" each time. Usually that involves driving it until the attached mechanism trips an optical or mechanical switch, giving the software a reference-point. Your other option is to apply a holding current (less than the stepping current) to the presently energized coils and not completely power down the motor's power supply when the rest of the system powers down. The software would have to save the motor position before the power down in a non-volatile memory, such as EEPROM, where it can retrieve it again at the next power-up.
> 2 votes

---
Tags: arduino-mega
---


title: LGPL and Arduino in Commercial Products

text:
# Question
Title: LGPL and Arduino in Commercial Products
I basically would like to ask this same question (in another context / more generically):

https://www.reddit.com/r/arduino/comments/25my2t/lgpl\_and\_arduino\_in\_commercial\_products/

Stated differently:

What are the legal implications of LGPL licence in commercial products using Arduino boards (and or Arduino software/firmware)?

and about creating my own libraries for Arduino? (less or more permissive licenses cases for a derivative work)

and lastly, I'm also curious about this statically vs linked library conditions of LGPL (and how this would be applicable in this case)

thanks!

# Answer
IANAL, but my understanding is:

* Any LGPL code *you modify* you need to make available as source.
* Using LGPL code in your project doesn't constitute modification of that code unless you actually modify that code (See above).
* Any code *you* write that is not contained *within* LGPL code (see above) is yours to license as you wish. That means your libraries are *your* libraries. Your sketch is *your* sketch.

So in short, things that must be released as LGPL:

* Modifications to the core code.
* Modifications to other people's libraries

Things that are yours to license as you wish:

* Your libraries
* Your sketches

Things you should (if you're nice) provide attribution for:

* Arduino API
* Third party libraries

As far as hardware goes:

> These files are licensed under a Creative Commons Attribution Share-Alike license, which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license. The Arduino software is also open-source.

Which means if you *use their designs within your own design you should attribute it and make it open source under the CC-BY license.* Otherwise, if you just use their hardware verbatim there's nothing to attribute - you haven't used their designs, but a commercial product as a component.
> 1 votes

---
Tags: library
---


# Question
Title: character on 16X2 LCD is not visible properly
i am using 16x2 LCD with arduino nano for my project.

when i connect arduino nano with usb power supply from pc or any mobile changer adapter then all the character on LCD is visible properly. But when i connect it with 5V regulated power to arduino nano than character on LCD is not visible properly (characters are visible and project is running fine but pixel which needs to be hidden are also little darker so it characters aren’t visible properly)

i have connected Vee pin of LCD with ground for maximum brightness.

# Answer
Disconnect Vee from GND and wire it up properly with a potentiometer. It doesn't set the brightness - it sets the bias point for displaying the different pixels in the matrix.
> 2 votes

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


# Question
Title: Avrdude can't connect to butterfly programmer
I'm trying to upload my exported HEX file by avrdude using this command `/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem1421 -b57600 -D -Uflash:w:/Users/user_acc/Documents/Arduino/at_command_A6/at_command_A6.ino.with_bootloader.leonardo.hex:i`

But instead of loading the file it's stuck on connecting to programmer.

Output: https://scr.hu/rYNzzm https://paste.ubuntu.com/p/74p37fGYPN/

The output from ArduinoIDE is exactly the same and it finds the programmer without the problem and loads the file.

`/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem124 -b57600 -D -Uflash:w:/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/arduino_build_78519/at_command_A6.ino.hex:i`

Output: https://scr.hu/M72NaV

Can somebody help me? :)

# Answer
> 1 votes
I found a post of somebody with a similar issue. His solution fixed my issue!

https://stackoverflow.com/questions/46813157/avrdude-command-line-cant-connect-to-programmer-for-leonardo

---
Tags: arduino-leonardo, avrdude, mac-os
---


title: What are the 5V and VIN pins for?

text:
# Question
Title: What are the 5V and VIN pins for?
I believe I can supply the Arduino with power in three different ways:

* Use USB. The design trusts the 5V to be regulated, and does not regulate it in any way.
* Use a regulated power source, trusted to be 5V, and connect it to GND and 5V.
* Connect an unregulated power source, eg a battery, to GND and VIN. This should be above 6.2V (since the dropout voltage is 1.2V) and preferably between 9V and 12V. There is a built-in regulator that will supply the Arduino with exactly 5V.

But can I use any of those pins to power other components. E.g. if the Arduino is powered with USB, can I use the 5V pin to power a diode? I thought I could, but the voltage is 4.70V, while the USB is 5.07V. The VIN is 4.26V btw.

Are the 5V and VIN only for powering the Arduino?

# Answer
> 37 votes
No. You can draw power from the 5v and VIN pins on the arduino. VIN is the completely unaltered input power before the regulator (it will be useless if regulated 5v is supplied directly). Outputting power is what the 5v pin is intended to be used for, not as a power input.

From the arduino website:

> 5V. This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

# Answer
> 6 votes
They can also be used to draw power from the barrel jack (Vin) or from USB or the on-board regulator (5V). The schematic of the board shows all exact power paths.

# Answer
> 5 votes
`5V` pin can be used to power up shields like Bluetooth, RFID, ultrasonic sensors etc..

`vin` pin is used to power up the Arduino. For example, when using shields such as L298 motor shield which is providing 5V output while operating from 12V.

# Answer
> 0 votes
The MBR0520 Schotky Power Rectifier (Surface Mount Schottky Power Rectifier) is connected in the Series path of 5v pin present on Nano which can handle maximum of 12V reverse voltage and according to datasheet 20v typical valur thus we can power ON arduino NANO using 5v pin also provided you supply proper 5v through any type of DC-DC Converter to it. https://www.onsemi.com/pub/Collateral/MBR0520LT1-D.PDF http://malylubo.sk/wp-content/uploads/2013/01/Arduino\_Nano\_Schematic-1024x676.png

---
Tags: voltage-level
---


title: Error : stray '\' in program

text:
# Question
Title: Error : stray '\' in program
I got this error in the following program:

```
#include <SoftwareSerial.h>
#include <dht.h>
dht DHT;
int a;
String temp;
String humid;
SoftwareSerial esp(0, 1);
#define SSID "abcd"
#define PASS "99999999"

void sendAT(String cmd) {
  Serial.print("SEND=");
  esp.println("cmd");
  Serial.println("cmd");
}

boolean connectwifi() {
  Serial.println("AT+CWMODE=1");
  delay(2000);
  Serial.println("AT+CWLAP");
  String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";
  sendAT(cmd);
  delay(5000);
  if (Serial.find("ERROR")){
    Serial.println("Recieved:Error could not connect");
    return false;
  }
  else{
    Serial.println("Wifi connected \n");

  }
  cmd="AT+CIPMUX=0";
  sendAT(cmd);
  if(Serial.find("Error")){
    esp.print("RECIEVED ERROR");
    return false;
  }
}

  void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  esp.begin(115200);
  send("AT");
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Recieved:OK\n ESP ready to send data\n");
    connectwifi();

  }

}

  void loop() {
  // put your main code here, to run repeatedly:
  a=DHT.read11(5);
  temp=DHT.temperature;
  humid=DHT.humidity;
  Serial.println("temperature: ");
  Serial.println(temp);
  Serial.println("humidity: ");
  Serial.println(humid);
  Serial.print("\n");
  updateTS(temp,humid);
  delay(3000);

}

void updateTS(String T, String H){
  String cmd="AT+CIPSTATRT=\"TCP\",\"api.thingspeak.com\",80";
  sendAt(cmd);
  delay (2000);
  if (Serial.find("Error")){
    Serial.print("Recieved :Error\n EXIT1");
    return;
  }
  cmd="GET/update?key=CJWN3VJZCQVTJD2J&field1="+T+"&field2+"+H+"\r\n";
  Serial.println("AT+CIPSEND=");
  Serial.println(cmd length());
  if (Serial.find(">")){
    esp.print(">");
    esp.print(cmd);
    Serial.println(cmd);
    }
    else{
      sendAT("AT+CIPCLOSE");
    }
    if (Serial.find("Error")){
      Serial.println("Recieved: Error \n EXIT2");
    }
    Serial.println();
}
    }
}

```

The error message displayed is:

```
arduinoo_sketch:21: error: stray '\' in program

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

   ^

arduinoo_sketch:21: error: stray '\' in program

arduinoo_sketch:21: error: stray '\' in program

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:21:47: warning: missing terminating " character

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

                                               ^

arduinoo_sketch:21: error: missing terminating " character

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

   ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'boolean connectwifi()':

arduinoo_sketch:22: error: expected ',' or ';' before 'sendAT'

   sendAT(cmd);

   ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:24:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find("ERROR")){

                          ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:34:25: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if(Serial.find("Error")){

                         ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void setup()':

arduinoo_sketch:44: error: 'send' was not declared in this scope

   send("AT");

            ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:46:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

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

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void loop()':

arduinoo_sketch:64: error: 'updateTS' was not declared in this scope

   updateTS(temp,humid);

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void updateTS(String, String)':

arduinoo_sketch:75: error: 'sendAt' was not declared in this scope

   sendAt(cmd);

             ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:77:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find("Error")){

                          ^

arduinoo_sketch:83: error: expected ')' before 'length'

   Serial.println(cmd length());

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:84:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find(">")){

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:92:28: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     if (Serial.find("Error")){

                            ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: At global scope:

arduinoo_sketch:97: error: expected declaration before '}' token

     }

     ^

exit status 1
stray '\' in

```

# Answer
> 2 votes
By properly formatting your code (ctrl-T in the IDE), you realize what is wrong with your code... In

```
  String cmd = "AT+CWJAP="\"abcd"\",\"99999999"\";
               sendAT(cmd);

```

See how `sendAT(cmd);` is indented as if it was part of the previous line? It means you have some trouble with the quotes.

# Answer
> 1 votes
At least one example is here:

```
String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

```

You probably meant

```
String cmd="AT+CWJAP=\"abcd\",\"99999999\"";

```

This is a pretty trivial issue, you should be able to fix it simply by proofreading your sketch carefully.

---
Tags: compilation-errors
---


# Question
Title: analogRead() inside a loop always returns 0
I wrote Arduino code to receive analog input from different voltage dividers connected to four pins (A0 to A4) and analog input from a temperature sensor (LM35) to A5. `analogRead` inside the for loop always returns zero whereas `analogRead` outside the for loop returns correct values.

What has to be changed to get correct values?

```
int time=0,y=0;
float volt;
String str;
int countParallel=0;
float voltage[]={0,0,0,0};
float temperature=0;
int sensors_pin[]={A1,A2,A3,A4,A5};
String x="";

// the setup rouontine runs once when you press reset;
void setup() {
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(50);
}

// the loop routine runs over and over again forever;
void loop() {
  Serial.println(analogRead(A5)*500/1023);
  delay(1000);
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      x += (char)inChar;
    }
  }
  // Parallel Disharging
  //  Serial.println(x);
  if(x.toInt()==1) {
    digitalWrite(13,HIGH);
    if(countParallel<1) {
      digitalWrite(6, HIGH);
      digitalWrite(7, HIGH);
      countParallel++;
    }
   for(int i=1,x=14;i<=5;i++,x++) {
    if(i<4) {
      Serial.println(analogRead(x)*(5/1023));
      delay(100);
    } else if(i==5) {
      Serial.println(analogRead(x) * p(500/1023));
      delay(100);
    }
    if(volt<2.8){
     digitalWrite(i+1,HIGH);
   } else if(temperature>40) {
     digitalWrite(2,HIGH);
     digitalWrite(3,HIGH);
     digitalWrite(4,HIGH);
     digitalWrite(5,HIGH);
    }
  }
}

// Series Discharge
if(x.toInt()==2){
    for(int i=A0;i<=A4;i++){
      if(i<A4) {
        voltage[i] = analogRead(sensors_pin[i]) * (5/1023);
        Serial.println(10);
        delay(100);
      } else if(i==A4) {
        temperature = analogRead(sensors_pin[i])*(500/1023);
        Serial.println(9);
        delay(100);
      }
      if(volt<2.8) {
        digitalWrite(i, HIGH);
        delay(100);
      } else if(temperature>40) {
        digitalWrite(2,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(4,HIGH);
        digitalWrite(5,HIGH);
      }
     }
  }
}

```

# Answer
> 3 votes
```
voltage[i]=analogRead(sensors_pin[i])*(5/1023)

```

Is equivalent to

```
voltage[i]= analogRead(sensors_pin[i])*0
          = 0;

```

You are using an integer division, not a floating point divsion. `5 / 1023` evaluates to `0`, `5.0f / 1023` evalues to `0.00488..`. You have repeated this error throughout your lower loop code, which is why you're only getting `0`.

In your outer loop you printed it as

```
Serial.println(analogRead(A5)*500/1023);

```

Which will first multiply by 500, then divide by 1023, which works. But since you put the above expression in parenthesis, it was first evaluated.

---
Tags: arduino-uno, analogread
---


# Question
Title: Serial communication between PC and Arduino via RS232 using C++
I am trying to communicate with my Arduino Duemilanove via an RS232 cord. I simply want to be able to send a byte (or char) to my Arduino from a desktop application. The Arduino is plugging into USB COM5 on my computer. I have the RS232 plugged into COM1, and then I have pins 2, 3 and 5 on the other end of the RS232 connected to Arduino pins TX, RX, and GND, respectively.

I found a serial comm class for C++ at the following link: Arduino and C++ (for Windows)

I have added the .h and .cpp files from the above example as `Serial.h` and `Serial.cpp` (I think the example uses `SerialClass.h` and `SerialClass.cpp`, I just changes the names).

---

On my Arduino, I have the following code running:

```
// ARDUINO
char incomingByte = 0;

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

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, HEX);
        }
}

```

---

And my C++ program is the following:

```
// C++
#include <iostream>
#include <Windows.h>
#include "Serial.h"

using namespace std;

int main(void)
{
    Serial port("COM1");

    char* msg = "Hello Arduino!";
    int msgLen = strlen(msg);
    bool writeSuccess = port.WriteData(msg, msgLen);

    cout << "\n\n";
    system("PAUSE");
}

```

---

When I use the Arduino's serial port viewer to see what is bring printed, I'm getting very strange values that don't match what I'm sending (as far as I can tell).

When I send "Hello Arduino!", the arduino prints the following:

```
I received: FFFFFFAB
I received: 3A
I received: 3A
I received: A
I received: FFFFFFFA
I received: FFFFFFEB
I received: 6D
I received: 37
I received: 15
I received: 2D
I received: 23
I received: 21
I received: FFFFFFBD
I received: 0

```

This does not appear to be the correct hex for "Hello Arduino!", but I have no idea why it's not correct. Does anyone have any clue what I'm doing wrong?

# Answer
> 2 votes
It because that in your c++ application you haven't explicitly mentioned serial port speed. Mention the same baudrate which you have used in arduino here(c++).

Assuming that you have used rs232 to ttl converter, as you are getting some output, Which in other case wouldn't as you would have already burned your mcu.

# Answer
> 0 votes
You need some voltage converter between arduino and pc. PC uses "real" RS232 and arduino uses TTL level RS232. Check more in this site. You need something like this RS232 to TTL.

---
Tags: serial, c++
---


# Question
Title: How to get and interpret digital accelerometer data?
I am trying to connect an Arduino to a digital accelerometer. The Arduino receives commands from a mobile app and transmits over Bluetooth through hardware serial. I also posted this question here.

Code:

```
 #include < SPI.h >

const int X8 = 0x06;
const int Y8 = 0x07;
const int Z8 = 0x08;

/*
bits
1 0  mode 00: standby, 01: measurement
5     1: spi 3 wire, 0: 4 wire
4      self test
3     2 glevel: 01 2g
1 0  mode, 00 standby, 01 measurement
*/
const int MODE = 0x16;

const int STATUS = 0x09;

//7 digital filter band width, 0 62.5 Hz, 1 125 Hz
const int CONTROL = 0x18;

bool isTesting = false;

const int chipSelectPin = 7;

void setup() {
    Serial.begin(9600);
    SPI.begin();
    pinMode(chipSelectPin, OUTPUT);

    //set up standby, spi 4 wire, 2g range,
    writeRegister(MODE, 0x04);

    //set up speed
    writeRegister(CONTROL, 0x00);

    delay(100);
}
void loop() {
    if (getSerial() == 't') {
        isTesting = true;
        writeRegister(MODE, 0x05); // 0000 0101- 0001 0101 0x15
        testing();

    }

}
void testing() {
    while (isTesting) {
        if ((readRegister(STATUS) & 1) == 1) {
            Serial.print((char) readRegister(X8), DEC);
            Serial.print("x");
            Serial.print((char) readRegister(Y8), DEC);
            Serial.print("y");
            Serial.print((char) readRegisterChar(Z8), DEC);
            Serial.print("z");
        }

        if (getSerial() == 'u') {
            isTesting = false;
            writeRegister(MODE, 0x04);
        }
    }
}
char getSerial() {
    if (Serial.available()) {
        char c = Serial.read();
        return c;
    }
    return 'x';
}
byte readRegister(byte thisRegister) {
    byte inByte = 0;
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}
char readRegisterChar(byte thisRegister) {
    char inChar = 0;
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    inChar = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inChar;
}
void writeRegister(byte thisRegister, byte value) {
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(128 | thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}

```

The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data. The data received when the sensor is on a flat surface is:

> x y z
>
> 5 -11 74
>
> 4 -19 74
>
> 2 -9 69
>
> 0 -8 68
>
> 7 -16 68
>
> 7 -11 73

When the self test is run, the results are:

> -5 -20 122
>
> -4 -22 122
>
> -1 -20 123
>
> -4 -20 123
>
> -5 -21 121
>
> -3 -18 123
>
> -8 -22 127

From the data sheet: "When the self-test function is initiated through the mode control register ($16), accessing the "self-test" bit, an electrostatic force is applied to each axis to cause it to deflect. The Z-axis is trimmed to deflect 1g."

Is the data correct? How is it interpreted? If the z data during self test is 1g, shouldn't it have the same magnitude as when it is on a flat surface?

I adapted to code to get the 10 bits of data:

```
const int X10_LSB = 0x00;
const int X10_MSB = 0x01;
const int Y10_LSB = 0x02;
const int Y10_MSB = 0x03;
const int Z10_LSB = 0x04;
const int Z10_MSB = 0x05;

//[...]

void testing() {
        while (isTesting) {
            if ((readRegister(STATUS) & 1) == 1) {

                int xData = (readRegister(X10_MSB) << 8) | readRegister(X10_LSB);

                // checks if bit 9 is 1 and sign extends
                if ((xData & 512) == 512)
                    xData = (0b1111110000000000 | xData);
                int yData = (readRegister(Y10_MSB) << 8) | readRegister(Y10_LSB);
                if ((yData & 512) == 512)
                    yData = (0b1111110000000000 | yData);
                int zData = (readRegister(Z10_MSB) << 8) | readRegister(Z10_LSB);
                if ((zData & 512) == 512)
                    zData = (0b1111110000000000 | zData);

                Serial.print(xData);
                Serial.print("x");
                Serial.print(yData);
                Serial.print("y");
                Serial.print(zData);
                Serial.print("z");

            }

```

The outputs for 2g measurement is:

> 4 246 -183
>
> 5 245 -183
>
> 5 245 -182
>
> 6 245 -181

For the self test:

> 252 -20 -134
>
> 253 -21 -133
>
> 253 -21 -135
>
> 253 -20 -135

the values for 8 and 10 bits of data don't correspond. What am I doing wrong?

Update: I rewrote the code to get the 10 bits of data with the LSB bits fisrt as per a comment:

Code:

```
     int xData =(readRegister (X10_LSB));
        xData = xData | (readRegister (X10_MSB)<<8);
        xData = xData << 6;
        int yData =(readRegister (Y10_LSB));
        yData = yData | (readRegister (Y10_MSB)<<8);
        yData = yData << 6;
        int zData = (readRegister (Z10_LSB));
        zData = zData | (readRegister (Z10_MSB)<<8);
        zData = zData << 6;

        xData /= 64;
        yData /= 64;
        zData /= 64;

```

The results for the sensor when on a flat surface:

> 0 -4 71
>
> 4 -11 70
>
> 5 -13 70
>
> 2 -12 70

The results when self-test is applied:

> -2 -19 123
>
> -2 -19 122
>
> -4 -20 122
>
> -3 -21 122

Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

# Answer
> The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data

you are using it in 2g mode, so you have only 8bit of data.

> The data received when the sensor is on a flat surface is:

this is correct. You have a 8bit range (256 value, from -128 to +128) that map a range from +2g to -2g. So we have 256lsb/4g = 64lsb/g.
Motionless, the lenght of the gravity vector (sqrt(x*x+y*y+z\*z)) must be close to 64. Of corse you need some offset and non-linearity calibration but the data seems fine.
Also if you look at the piece of datasheet you posted in table "Sensitivity", you will see they call the LSB "count", and they are in the range we calculated!

> When the self test is run, the results are:

again this is correct, if your sensor is flat in way the Gravity apply on the Z; what you see is the normal gravity (64) summing up to the self-test offset (64), giving you a nice ~128

> I adapted to code to get the 10 bits of data:
>
> Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

to use 10bit, you must set the full scale range to +-8g. If you look at the piece of datasheet you posted, table "Output Signal", you see how many bit are avaiable for each range.
If you think about it, how does the sensor know if you want to read 8 or 10bit? (remeber the DS say you must read the low register BEFORE high register!) if you read only 8bit, you would be loosing the 2msb, one rapresenting the sign and the other the most important bit that can change your result by 2^9=512 btw also you first 10 bit conversion is wrong as you flip the bit for 2's complement, but does nothing to the value bit.
The solution with bit shitf of 6 follow by divising is working but a bit strange to see. I would go for something more "standard" like

```
int xData = readRegister (X10_LSB) | (readRegister (X10_MSB) << 8);
if (xData | 0b0000 0010 0000 0000){ //if negative
    //keep 9 bit raspresenting the value and multiply by -1 to keep the sign
    xData = (xData & 0b0000 0001 1111 1111) * -1;
}

```
> 2 votes

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


# Question
Title: Unable to convert string read from bluetooth to int
I am using a HC-06 and i want to read a number ending with f as a delimiter, the first three numbers as my servo position, however converting the string into int is giving an endless series of 0s. I added the Serial.print(servopos) to see that its a never ending series of 0s, and nothing seems to fix this problem. What am I doing wrong? (I tried using long for servopos instead of int, it didn't fix the issue)

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

Servo myservo; // servo name

int bluetoothTx = 10;
int bluetoothRx = 11;
int fwd = 12;
int bwd = 13;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
String content = "";
char character;

void setup()
{
  myservo.attach(9); // attach servo signal wire to pin 9
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);

  pinMode(fwd, OUTPUT);
  pinMode(bwd, OUTPUT);

}

void loop()
  {
  if(bluetooth.available()> 0 ) // receive number from bluetooth

    character = bluetooth.read();

    if (character!='f'){
        content += (char) character;
        delay(10);
      }

    else{
      int servopos = content.substring(0,3).toInt();
      Serial.print(servopos);
     // myservo.write(servopos);

      String directMvt = content.substring(3);
      if (directMvt == "00"){
            digitalWrite(fwd, LOW);
            digitalWrite(bwd, LOW);
      }
      else if (directMvt == "10"){
            digitalWrite(fwd, HIGH);
            digitalWrite(bwd, LOW);
      }
      else if (directMvt == "01"){
            digitalWrite(fwd, LOW);
            digitalWrite(bwd, HIGH);
      }
      else if (directMvt == "11"){
            digitalWrite(fwd, LOW);
            digitalWrite(bwd, LOW);
      }
      content = "";
  }
}

```

# Answer
I've found your problem: You have a missing pair of `{ }`, that should enclose the `if(bluetooth.available()>0)` statement. Without the parenthesis it only encloses the following statement, which is the serial reading.

Now follow the logic: Before you are sending something over serial, the global variable `character` should be zero. So then, since the NULL character is not equal to `f`, the NULL characters are added to the string. Then you send a string like `18000f` via bluetooth serial. The code is adding the characters to the string variable, until it find the `f` character. Now it goes directly in the `else`-statement, printing the value of `servopos` and then resetting the string variable. On the next loop iteration, there isn't something available at the SoftwareSerial, so it goes to the `if(character !='f')` statement. The `character` variable is global and it is still filled with the `f` value, that it got in the last loop iteration. So the `else` statement is executed forever very fast. But since you reseted the content of the string variable in the last iteration, there is nothing to convert to integer here. So this gives you a forever lasting series of zeros.

Enclosing the code in the first `if` statement solves your problem, since then, it only does something, when data is available at the serial interface. Also you should consider using a local variable for `character`, since you only need it there and your problem would have been obvious (through a compiler error), if you used a local variable here. Using global variables, when there is no need to, can make things more complex and error-prone.
> 0 votes

---
Tags: serial, servo, softwareserial, hc-05, hc-06
---


# Question
Title: Timer for Control Motor using Limit Switch
Im not good in arduino, but I have project that control motor using limit switch.

The rule is:

1. When switch OFF, motor ON
2. When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)
3. After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.

# Answer
> 0 votes
There is no need to do a complex thing like using extra timers for this. You can use non-blocking code with the `millis()` function, like in the `BlinkWithoutDelay` example of the Arduino IDE (You should really try it and understand how it works). The `millis()` function returns the number of milliseconds since the Arduino has powered up and it will overflow after about 50 days (and with the code from the mentioned example this wouldn't be a problem either).

Basically you save a timestamp of the last event and check, if it is time to do something. For your case I would add a boolean, indicating, that the motor should be off and that the state of the switch doesn't matter anymore. Then (I assume that you want to disable the motor again by switching to OFF and ON again) you would have to reset this variable, when the switch goes to OFF state again. Something like this:

```
boolean state=true; // on by default
unsigned long timestamp=0;

void loop(){
  if(switch_on() && state){
    state=false;
    // switch off the motor here
    timestamp = millis();
  }
  if(switch_off()){
    state=true;
  }
  if(!state && millis()-timestamp > INTERVAL){
    //switch on the motor here
  }
}

```

Be sure to have a good code for checking the switch state, since most mechanical buttons need debounce code. In the above code I replaced this with simple functions to illustrate the timing functionality.

---
Tags: motor, switch
---


title: Initializing an array within a class

text:
# Question
Title: Initializing an array within a class
I'm making a game of snake on the adafruit Neopixel shield and have run in to a problem. How do you fill out an array (in this case a 5\*8 array) with values once the class has been called. This is my code so far

H file

```
#include <Arduino.h>
#include <Adafruit_NeoMatrix.h>
#include <streaming.h>

class Snake : public Adafruit_NeoMatrix
{
    public:
    Snake();
    void drawSnake();

    private:
    int snakeBoard[5][8];
};

```

CPP file

```
#include "Snake.h"

Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800)
{
  begin(); // start the matrix
  show();

  int snakeBoard[5][8] = {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}};
}

void Snake::drawSnake()
{
  for(int y = 0; y < 5; y ++)
  {
    for(int x = 0; x < 8; x ++)
    {
      Serial << "X: " << x << " Y: " << y << " Value" << snakeBoard[x][y] << endl;
      delay(100);
    }
  }
  drawPixel(5,5,Color(0,0,255));
  show();
}

```

When I run the program random garbage is printed in the serial monitor.

# Answer
> 1 votes
As already mentioned by @chrisl, you are creating a new local variable which overshadows your class member.

An easy way to get what you want is to `memcpy` your initial values into the array:

```
Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800)
{
  begin(); // start the matrix
  show();

  int initialSnakeBoard[5][8] {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}};
  memcpy(snakeBoard, initialSnakeBoard, sizeof(initialSnakeBoard));
}

```

You can achieve the same thing by utilizing C++11 constructor lists to initialize your members (see here):

```
Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800),
  snakeBoard {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}}
{
  begin(); // start the matrix
  show();
}

```

You also have an error in your `drawSnake` routine: You confused the order of the indexes. With `snakeBoard[5][8]` you declare 2-dimensional integer array with 5 rows containing 8 elements each. Then, `snakeBoard[0]` will be a pointer to the first row (which has 8 elements). So the first index is `y` and must only range from `0` to `4` inclusive. The function must be:

```
void Snake::drawSnake() {
    for(int y = 0; y < 5; y ++)
    {
        for(int x = 0; x < 8; x ++)
        {
            Serial.println("X: " + String(x) + " Y: " + String(y) + " Value " + String(snakeBoard[y][x]));
            delay(100);
        }
    }
}

```

This then prints all the expected array elements to the the `Serial` port, as tested on my Arduino Nano.

---
Tags: programming, c++, class
---


# Question
Title: Problem uploading to ATMega using ArduinoIDE ("unbricking" "bricked" microcontroller?)
I've a SparkFun Pro Micro which is an Arduino Leonardo clone. Unfortunately my attempts to upload programs failed. I did some research in the internet and found you have to use SparkFun's configuration. There is a board manager's URL you have to use: https://raw.githubusercontent.com/sparkfun/Arduino\_Boards/master/IDE\_Board\_Manager/package\_sparkfun\_index.json

So far so good. After trying to use this I attempted to do an upload and failed. I tried it with different settings but all failed. While earlier there was a serial port named `/dev/ttyACM0` there now is no such port any more. Further research gave me the information that you might get the device running if you a) reset to boot loader mode where you should have an 8 seconds window to upload and b) actually perform the upload.

I can verify: If I pull RESET to ground I can switch into this 8 seconds mode. Then the device `/dev/ttyACM0` appears after about 1 second for about 7 seconds. As instructed I immediately try to do an upload. This is strange: I immediately (!) get the following output:

* Line 1: `Sketch uses 4140 bytes (14%) of program storage space. Maximum is 28672 bytes.`
* Line 2: `Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.`
* Line 3: `avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory`
* Line 4: `Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.`

The TTY should be there as the 7 seconds have not been passed in that case. Furthermore my user account is in `dialout` which enables it to use the tty.

If I trust this error message that means the tty is gone as soon as `avrdude` tries to access it. Which shouldn't be that way, should it?

Has anyone encountered this situation before? How can I upload a program to the mikrocontroller? Has anyone has any experience with that situation here?

--

Additional information:

* ArdunoIDE 1.8.5
* Ubuntu (Mate) Linux 16.04

# Answer
We use these a lot, and it's very easy to accidentally program the boards with the incorrect settings - particularly as the Sparkfun Pro Micro library defaults to the 3.3V/8 MHz variant instead of the more common 5V/16MHz.

I have recovered the boards with the bootloader reset method, but it is hard - you have to get the timing just right. What we do now is to simply reinstall the bootloader using an ISP programmer (instructions: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader). It works first time, and ends up being much quicker than repeated tries to get the reset timing right. Just make sure that you have the right board selected when you burn the bootloader. We use a USBASP, and it only takes a couple of minutes to set up.
> 1 votes

---
Tags: bootloader
---