title: Error in code (define a function)

text:
# Question
Title: Error in code (define a function)
I try to use this code, but it shows that I need to define again the last void turn\_mer (int direction) function. How can I fix this?

```
#include <Servo.h> //create servo object to control a servo.
Servo myservo;

//pin configuration.
const byte servoPin = 2; const byte motorLeft = 5; const byte motorRight = 6;
const byte echoPin = 12; const byte trigPin = 13; const byte echoPin2 = 8; const byte trigPin2 = 9; // LET OP DE HOOFDLETTERS: echopin en echoPin
//delay determines how long the MER turns, increase to make the turning angle larger.
const int turnDelay = 500;
//standard angle for looking straight ahead, compensate for construction errors.
const int standardAngle = 90;
//angle in degrees that controls the direction in which the sensor looks.
const int viewAngle = 40;
//delay to let servo turn, not optimized; for smaller angles smaller delay could be used.
const int servoDelay = 250;
//object distance in cm at which the MER decides to look around and turn another way.
const int lineOfSight = 40;
//pwm duty cycle of the motor, use a value from 0 (no movement) to 255 (full speed).
const int motorSpeed = 90;

//const int lineDownSight = 35;
void setup() //setup pin configuration and initialize the sensor position.

{ delay(3000); //delay to give us some time to place the MER on the ground.
  myservo.attach(servoPin); //initialize the servo and look straight ahead.
  turn_servo(standardAngle);
  pinMode(motorLeft, OUTPUT); pinMode(motorRight, OUTPUT);
  pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); drive_mer();
} //start the mer.
void drive_mer() //this function lets the MER drive forward.
{
  analogWrite(motorLeft, motorSpeed);
  analogWrite(motorRight, motorSpeed);
}
void stop_mer() //this function stops the mer.
{
  digitalWrite(motorLeft, LOW);
  digitalWrite(motorRight, LOW);
}
void turn_servo(int angle)
//turn servo to given angle, do not return until angle is reached.
//if the servo is already at the correct angle, we don't have to do anything.
{ if (angle == myservo.read()) {
    return;
  }
  else {
    myservo.write(angle);
    delay(servoDelay);
  }
}

int look1() //looking function, returns distance in the observed direction as an integer.
{ int duration, distance;
  digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1; return distance;
}
//turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
void turn_mer(int direction)

{ if (direction == 0) {
    digitalWrite(motorLeft, LOW);
    digitalWrite(motorRight, HIGH);
  }
  else {
    digitalWrite(motorLeft, HIGH);
    digitalWrite(motorRight, LOW);
  }
  delay(turnDelay); stop_mer();
}//stop the engines when the MER has turned far enough.

//this function turns the MER depending on the observed distances.
void handle_measurements(int distanceLeft, int distanceStraight, int distanceRight)// int distanceDown

{ if (distanceLeft < lineOfSight and distanceStraight < lineOfSight and
      distanceRight < lineOfSight) {
    stop_mer();
  }

  else if (distanceLeft < lineOfSight) {
    turn_mer(1);
    drive_mer();
  }

  else if (distanceStraight < lineOfSight) {
    if (distanceRight > distanceLeft)
    {
      turn_mer(1);
    } else {
      turn_mer(0);
    } drive_mer();
  }

  else if (distanceRight < lineOfSight) {
    turn_mer(0);
    drive_mer();
  }
 //if (distanceDown > lineDownSight) {
  //  stop_mer();
  }

  void loop()
  { int distanceLeft, distanceStraight, distanceRight;

    turn_servo(standardAngle + viewAngle); distanceLeft = look1();
    turn_servo(standardAngle); distanceStraight = look1();
    turn_servo(standardAngle - viewAngle); distanceRight = look1();
       handle_measurements(distanceLeft, distanceStraight, distanceRight);}

/*  void handle_measurements(lineDownSight)
   {(distanceDown > lineDownSight) {
    stop_mer();
  }*/
  //                                                                                sensor 2
  //______________________________________________________________________________________________________________________________________________________________________________________________________

 const int lineDownSight = 35;

  void handle_measurements (int distanceDown)

{if (distanceDown > lineDownSight) {
    stop_mer();}}

  int look2() //looking function, returns distance in the observed direction as an integer.
  { int duration, distance;
    digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
    distance = (duration / 2) / 29.1; return distance;
  }
  //turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
void turn_mer (int direction)

{handle_measurements(distanceDown)}

```

# Answer
> 4 votes
But the main problem is that in C, you can only define a function with the same name once.

Halfway you defined the function turn\_mer already, and again at the end.

Also, you are missing an end colon in:

```
{handle_measurements(distanceDown)}

```

It's better to align your code like:

```
{
    handle_measurements(distanceDown);
}

```

---
Tags: arduino-uno
---


# Question
Title: 'Serial1' was not declared in this scope
Trying to do serial communication between 2 Arduino Unos.

Code:

```
#include <SoftwareSerial.h>

int ledPin = 13;
int board;   // 1 = Uno. 2 = Mega.
int on_off;  // 1 = On. 0 = Off.
int buzzerPin = 9;
int Ack_tx = 2; //Acknowledgement tx.
int rec;

void setup()
{
  Serial.begin(9600);      // start serial communication at 9600bps
  Serial1.begin(9600);     // start serial1 communication at 9600bps

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  Serial.flush();
  Serial1.flush();

} // End Setup

void loop()
{

  Serial.println("Enter Uno=1/Mega=0 ...");  //Select board
  //  if(!Serial){ board = Serial.read();}
  while(Serial.available()==0) { // Wait for User to Input Data
  }
  board = Serial.parseInt();  //Read the data the user has input

  Serial.println("Enter LED On=1/Off=0 ...");  //Select On or Off
  while (Serial.available()==0) { // Wait for User to Input Data
  }
  on_off = Serial.parseInt();

  Serial.println();

  switch (board) {

  case 0:  //Mega board
    if (on_off == 1) digitalWrite(ledPin, HIGH); //Select Uno LED On
    else digitalWrite(ledPin, LOW);              //Select Uno LED Off
    break;  //End Case

  case 1:  //Uno board
    //Serial.println("Off to Uno...");
    //Send on_off info to Uno
    Serial1.write(on_off/256); //Send the Quotient or "how many times" value
    Serial1.write(on_off%256); //Send the Modulo or Remainder.
    delay(50); //Wait for the serial port.

    while(Serial1.available()<2) //Wait for 2 bytes to arrive
     {
      //do nothing
     } //End While

  byte b1=Serial1.read();  //Read Upper byte
  byte b2=Serial1.read();  //Read Lower byte
  rec=(b1*256)+b2;

    if (rec == Ack_tx) tone(buzzerPin, 300, 300); //Ack_tx from Uno
    break;
  } //End Switch Case

}

```

Error:

```
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void setup()':

sketch_mar06a:13: error: 'Serial1' was not declared in this scope

   Serial1.begin(9600);     // start serial1 communication at 9600bps

   ^

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void loop()':

sketch_mar06a:51: error: 'Serial1' was not declared in this scope

     Serial1.write(on_off/256); //Send the Quotient or "how many times" value

     ^

Multiple libraries were found for "SoftwareSerial.h"
 Used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
 Not used: C:\Program Files (x86)\Arduino\libraries\SoftwareSerial
exit status 1
'Serial1' was not declared in this scope

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

```

This is a very basic problem I know, but nothing on the internet is helping.

# Answer
The Uno has no `Serial1`. It only has one serial port, called `Serial`. To use `Serial1` you will need a bigger board such as a Mega2560, or define it as a `SoftwareSerial` port and use two other IO pins of your choice for it, though at lower baud rates than `Serial` can run at.
> 10 votes

# Answer
You import the `SoftwareSerial` library but you however never instance an object of the `SoftwareSerial` class.

You just need to add the line

```
 SoftwareSerial Serial1(10, 11); // RX, TX

```

after including the library header (taken from here)

This now creates an object `Serial1` on which the operations down there should work the same as with a real hardware serial (API-wise).

Side note: Careful with the wiring. You are using this `Serial1` emulated UART to communicate between the boards, so if you're using above pin numbers (D10 = RX, D11 =TX) then you must connected D10 (Board1) -\> D11 (Board2), D11 (Board1) -\> D10 (Board2), i.e. RX-\>TX, TX-\>RX.
> 7 votes

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


# Question
Title: Standalone Arduino with ATMEGA328P / Serial working, but serial programming not (only once after buning bootloader)
For my master thesis I've designed a board with an ATMEGA328P-AU as micro controller.  As I want to use some libraries and I like the simplicity, I want to use "Arduino" to program it.

Everything works fine to a point: I took an Arduino Uno and uploaded the "ArduinoISP" sketch. I connected the ISP pins and burned the bootloader with board set to "Arduino Duemilanove / Diecimila" - got the message, bootloader burned. I disconnected the ISP pins, took the ATMEGA out of its socket on the UNO board and connected the serial pins.

Here comes the problem I cant figure out:

Once I have done a above procedure I can upload a sketch and Serial communication is working. But I can only upload it once! The second time (no matter if during the same power-up or at another time) I push the upload sketch button, I get no response for several minutes (I once waited up to 10min to confirm there is nothing coming anymore :)). If I unplug either USB or the TX/RX cables I get the error (or for the USB cable something similar):

> avrdude: stk500v2\_ReceiveMessage(): timeout
>
> avrdude: stk500v2\_getsync(): timeout communicating with programmer

When I upload the bootloader again I can once again upload a sketch same as before. Then the same problem happens again.

I checked several question on Stackexchange already (specially all points in this one here) and googled the problem, but until now I am not able to find a solution.

As you can imagine it is quite annoying to always unplug the RX/TX cable and hook up the ISP cable again and burn the bootloader.

**So my question: What could cause this problem and how can I solve it?**

Btw. I am using the Arduino software version I'm using is 1.6.9

# Answer
There is a problem with your circuit and the way you have it wired when programming. You have failed to use the RTS line for Serial programming. You need to have that line connected to the RESET of the ATMega328, this is as the bootloader for programming ove rserial will not start if the IC is not reset. Also you should burn the Arduino UNO bootloader rather than the one you chosen.

Seems you clarified you were using the diode as ESD protection, thank you. It is the recommended arrangement if you have a capacitor attached to the reset line in noisy environments.

The circuit between the RTS signal and the Arduino RESET pin needs to be this:

```
            C
 RTS >>----||------->> RESET(PIN1)
           0.1µF

```

From the same "Have I bricked my Arduino" that you linked, about 3/4 down Nicks post he mentions the use of serial programming of an Arduino

```
FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

```

What you can do if you don't have the proper serial programmer with an RTS output, you will have to manually reset the microcontroller to enter the bootloader just as the IDE says "Uploading...".
> 4 votes

# Answer
Replying to an old post: The Reset diode is not really ESD protection, it is there to shunt any high voltage spikes to Vcc to keep the chip from reacting to a high voltage and going into High Voltage programming mode, and then acting hung when there are further control signals to complete the sequence.
> 0 votes

---
Tags: serial, programming, atmega328, bootloader
---


# Question
Title: Trouble uploading sketch / error in sketch
I am following this tutorial of a very basic serial communication between 2 arduino unos.

I have made the connections as given and connected the arduino unos to 2 separate laptops via USB.

Code1:

```
char mystr[3] = "Hello"; //String data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.write(mystr,5); //Write the serial data
  delay(1000);
}

```

Code 2:

```
char mystr[5]; //Initialized variable to store recieved data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.readBytes(mystr,5); //Read the serial data and store in var
  delay(1000);
}

```

Error on arduino following code 1:

```
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 1602 bytes (4%) of program storage space. Maximum is 32256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1860 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

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

```

Arduino running code 2 is stuck on the uploading and does not fininsh uploading.

The solutions on the internet only talk of the scenarios where the arduino is having trouble communication with the computer and so the solutions given are:

1. check com port
2. check that correct board is selected
3. do not insert the arduinos in usb 3
4. press reset button

None of these is my problem as I have checked them all. The arduinos themselves are working fine. I have a very strong feeling that there is a problem with the pins 0 and 1, i.e. with serial comm.

Please help.

# Answer
> 1 votes
I am guessing you have connected 2 arduinos together using their hardware serial ports while uploading. This cause uploading to fail as those ports are getting two signals at the same time.

Break this connection before upload and then it should work. You can reconnect them after upload.

If you want to avoid this you can use different pins with software serials for communication.

Also consider using Serial.available() on the reading end to see if there is data to be read.

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


# Question
Title: Is a variable declaration inside a loop static declaration or dynamic?
```
while(condition){
    Object object = new Object();
}

```

So my question is, will each iteration would create a different object in different memory location or it will overwrite the once created object every iteration.

# Answer
It will be created every iteration.

Assuming, you are not using it to add to a list (e.g. to use in later loops), what you better can do is make it in a global, you also don't need to use 'new', thus:

```
Object object;

```

Also, if you do not delete/remove the object at the end of each while condition (with the *delete* keyword), you will lose the memory (and this is a memory leak). Also, you run the risk of memory shortage (the Uno has only a few KB of memory).

What I also miss in your code is the pointer (\*, because the *new* keyword creates a pointer), and also Obj and Object are inconsistent types (they should be equal), so:

```
Object* object = new Object();

```

If you only need the object within the condition and it can be removed in the next while, than you don't need to use new, so just declare it as a vaiable

```
Object object;

```

This also has the benefit that the (local) variable will be destroyed at the end of scope (which is at the end of the while).
> 2 votes

# Answer
**Dynamic** object creation is using operator `new`. Operator `new` creates object on *heap* and the object exits until you delete it with operator `delete`.

`Object object` creates object on *stack*. It will be removed from stack when the variable goes out of scope on the end of the block.

**Some classes have copy constructors. If your `Object object = new Object()` compiles, then the class Object has copy constructor. The code creates an object on stack, then creates an object on heap and then copies it's content into object on stack. The object on heap stays and you have no pointer to it to delete it. The program soon crashes on low memory.**

**Static** variables have keyword static. If you would have `static Object* object = new Object()`, then the pointer is created on global level and the object on heap is created and assigned only ones.

EDIT: I tested this. Class String has a copy constructor, but the Arduino compiler doesn't allow `String s = new String(a)`. It can be misleaded with `String s = *(new String(a))` (`a` is some variable).
> 1 votes

---
Tags: programming, loop
---


# Question
Title: Arduino 2560 as an Interface to 4 Serial Hardwares
I am writing a software that runs on the PC that has a Arduino 2560 connected to it via USB. This PC needs to communicate with multiple devices through RS232.

Is it possible to use the Arduino's 4 UARTs to communicate with 4 different hardware that uses RS232 serial communication, using just 1 USB connection between the PC and the Arduino 2560?

The Arduino 2560 will basically act as an interface for 1 USB to talk to 4 RS232 devices.

# Answer
No, but it is possible to use 3 of them. The reason being that one of them is the connection to the computer.

The hard part is in the programming. You will need not only a suitable sketch on the Arduino (the easy part), but also some software on your computer that presents three COM ports to the operating system and forwards the data through to the Arduino in a suitably packeted format, and receive data back and sent it on to the right COM port. Depending on your operating system that may be a very easy task (on Linux and OS X) or a complete and utter nightmare (Windows).
> 1 votes

# Answer
In Arduino terms:

Serial will be committed to receiving data from the PC.

Connecting Serial1, Serial2, and Serial3 via RS232 will be easy.

Adding a 4th Software Serial (or NewSoft Serial or AltSoft Serial) via RS232 will also be straightforward. If you need high speeds for the 4th port, than a UART with SPI (or I2C) interface to the Mega might be a better idea.

The only tricky part is putting in some info in the data from the PC so the Mega can re-send it to the correct port.
> 1 votes

---
Tags: serial, arduino-mega, uart, rs232
---


# Question
Title: Not getting pure color while using the FastLED with WS2812b
I am working with the LED strip **WS2812b** and **FastLED** library, currently I have only 3 LEDs connected in such a way that the first 2 receive a color *(say green)* and the last one receives another one *(say blue)*.

The problem is that by putting the color *(blue)* on the last LED, the other two (currently only in *green*) also take a portion of *blue*, preventing it from being a pure (*green*) color. It happens with any combination of color.

I leave the piece of my code referring to the LED strip:

```
#include "FastLED.h"
#define NUM_LEDS 3
#define DATA_PIN 2

//Variables declaration...
....

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
.....

  }

void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
      if (digitalRead(pinNo+3) == HIGH){
        leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
           FastLED.show();
            }
        }

  }

```

I already change the pin for where I put the signal for the LED strip, I try to change the type of LED strip

* `FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS)`
* `FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS)`
* `FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)`

without any success...

Can anyone point me in the rigth direction?

Edit: actually, the first LED of the strip is flashing, not in the way of the **Blinking** example, but I can see a little flashing.

# Answer
I can see what the problem is, I put `FastLED.show();` where it should not, that's also why I saw the flash ... fix it and here's the result:

```
void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
    if (digitalRead(pinNo+3) == HIGH){
      leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
    }
  }

  FastLED.show(); //NOW IS IN THE RIGHT POSITION
}

```
> 1 votes

---
Tags: library, ws2812
---


# Question
Title: How can Arduino source code be tested automatically (continuous integration)?
I'd like manage my Arduino source code (projects and libraries) under source control with continuous testing. How can I automatically compile the code with continuous integration tools, to make sure each version compiles cleanly? In the best case one should be able to configure builds for multiple processors, optionally run unit tests and check for maximum binary size.

# Answer
> 6 votes
Newest version of Arduino ide has a command line interface to build and upload code. But you can obviously do it by makefile and avrdude. Now, you have compiled your code BUT you need testing. As simulator are complex,incomplete, expansive and.. Just a simulation, and because the chip are relatively cheap, building a board witch will make HW interaction AND check the results its the fastest and easiest way. On that "special" board you may upload something like an interpreter witch take a test from the PC and execute it, something similar to firmata for arduino. At least that is how I would build it. And as far as I know there are no know implementation of this, even if I'm quite sure many industries should and probably do that.

# Answer
> 4 votes
As the creator of PlatformIO I would recommend you to look into it. It's a cross-platform code builder and missing library manager. It can build the same code for the many popular embedded development platforms and boards.

PlatformIO can be be integrated with many popular Continuous Integration (CI) systems (or your own). See documentation with examples.

Let's look into `.travis.yml` config/template for Travis CI:

```
language: python
python:
    - "2.7"

env:
    - PLATFORMIO_CI_SRC=path/to/source/file.c
    - PLATFORMIO_CI_SRC=path/to/source/file.ino
    - PLATFORMIO_CI_SRC=path/to/source/directory

install:
    - python -c "$(curl -fsSL https://raw.githubusercontent.com/platformio/platformio/master/scripts/get-platformio.py)"

script:
    - platformio ci --board=TYPE_1 --board=TYPE_2 --board=TYPE_N

```

## Example

Integration for `USB_Host_Shield_2.0` project. The `.travis.yml` configuration file:

```
language: python
python:
    - "2.7"

env:
    - PLATFORMIO_CI_SRC=examples/acm/acm_terminal
    - PLATFORMIO_CI_SRC=examples/Bluetooth/WiiIRCamera PLATFORMIO_BUILD_FLAGS="-DWIICAMERA"
    - PLATFORMIO_CI_SRC=examples/ftdi/USBFTDILoopback
    - PLATFORMIO_CI_SRC=examples/Xbox/XBOXUSB
    # - ...

install:
    - python -c "$(curl -fsSL https://raw.githubusercontent.com/platformio/platformio/master/scripts/get-platformio.py)"

    # Libraries from PlatformIO Library Registry
    # http://platformio.org/#!/lib/show/416/TinyGPS
    # http://platformio.org/#!/lib/show/417/SPI4Teensy3
    - platformio lib install 416 417

script:
    - platformio ci --board=uno --board=teensy31 --board=due --lib="."

```

# Answer
> 3 votes
One example of setting up Jenkins continuous integration for Arduino project can be found here: Continuous integration for embedded systems

The example shows how to build and upload image to Arduino and execute Selenium web tests (the system under test is Arduino-based web-server).

# Answer
> 3 votes
I wrote this test unittest framework for Arduino, since i could not find proper existing. While i did not write it for CI, it would be good fit for CI job, since it requires no hardware but can be ran on PC.

Running the CI jobs without the hardware has good sides and bad sides, good sides beeing that

* No flashing, no hardware needed -\> can be runned in parallel -\> fast to check for example for every commit
* No hardware issues influencing the tests -\> no need to worry did this test just fail because my XYZ-hardware component is not stable

On the downside there is:

* Its not testing the actual target code, for example your 'int' is 32 bits in your PC and 16bits in AVR.

# Answer
> 3 votes
I've just put together a decent size writeup as an answer to this related question about an Arduino CI/unit testing framework I wrote that's finally mature enough to start talking publicly about.

The `arduino_ci` ruby gem supports both local testing and Travis CI integration (e.g. this build job for the Adafruit FONA library).

Some examples of how it integrates:

I have an issue created for reporting sketch size but no work has been done on that. It's also possible that I could parallelize the builds someday, but at the moment I'm not precisely sure how I'd do that. Right now, the most time consuming build step on Travis CI is downloading the Arduino IDE... parallel testing won't put much of a dent in that if every job needs to do that step.

# Answer
> 1 votes
I would advice to use the arduino eclipse plugin named sloeber sloeber.io of which I'm the project lead.
It integrates with version control and allows building on multiple platforms as it supports multiple configurations.
Though it is not yet idiot proof I have documented and demonstrated using unit testing of arduino code on the local pc using the google test framework.
Here is a link to a blog containing a presentation of how you can do it. http://blog.baeyens.it/#post25

---
Tags: programming, version-control
---


# Question
Title: How to wire an analog IR sensor for digital input?
How do you wire a phototransistor so that it outputs a clean digital signal in response to certain light levels?

I've wired a QRD1114 to an Arduino analog pin to detect a white or black surface. However, I want to use this sensor to detect fast movement of a black/white color strip, and since `analogRead()` can take up to 100µs and I'd rather use the ADC pin for other sensors, I want to rewire this so I can read the same signal with `digitalRead()`.

In order to do this, the sensor needs to output less than 2.3V for white and more than 2.5V for black. I'm pretty close, but I'm having trouble with black. For white, the voltage drops to 0.7V, so that reads perfectly, but black still reflects a lot of IR, so it typically reads 2.3V, which still translates as a LOW value.

My sensor's circuit is a pretty basic voltage divider:

R1 is the Arduino's built-in 20k pullup. R2 is a variable resistor I've tried using to "shift" the voltage level up for the black case. Unfortunately, I've found this very difficult to calibrate. The larger I make R2, the higher the black-case voltage gets...but so does the white-case voltage. By the time I make R2 large enough so that black registers as HIGH, white also registers as high. Through trial and error, I found 25.7k ohms is the sweet spot, but the difference in voltage between the two is about 0.5V, which makes me nervous about getting false readings.

I've measured the phototransistor's resistance in each case, and for black it reads as 12.5k ohms while for white it reads as 9.7k ohms.

Given my 25.7k calibration resistance, the voltage divider should output for black:

```
Vout = Vin * R2/(R1 + R2)

5 * (12500+25700)/(20000 + 12500+25700) = 3.2V

```

and for white:

```
5 * (9700+25700)/(20000 + 9700+25700) = 3.1V

```

However, for black, my meter reads 2.3V for black and 2.0V for white.

Why do my meter measurements not match the voltage divider formula? Am I wiring this voltage divider correctly?

What can I do to get a cleaner digital output without complicating the circuit too much?

# Answer
Near the bottom of:

https://learn.sparkfun.com/tutorials/qrd1114-optical-detector-hookup-guide

shows a graph of the voltage for a white surface and a black surface. If I understand your question correctly, I think you can get your desired results by controlling the distance between the sensor and the surface. For example, at 0.5mm white reads about 0.1V while black reads about 3.2V
A 330Ω current-limiting resistor and a 10kΩ pull-up resistor were used in their circuit.
Hope this helps.
> 1 votes

# Answer
First if you just want a faster analog read look at this article(http://www.microsmart.co.za/technical/2014/03/01/advanced-arduino-adc/). Second is that your approach to determining resistor values is incorrect. The sensor acts as a phototransistor so it passes different amount of current, upto 1 mA. so you only need a single resistor and the sensor to make an analog output. If you really want to digital read you can use an op amp as a voltage comparator.
> 0 votes

---
Tags: sensors, analogread, ir, digital
---


# Question
Title: Only getting error from ESP8266 AT commands
I am trying to get the ESP8266 work with Arduino AT commands. I am using the due. How do I get the ESP8266 to respond with anything other than ERROR?

Here is the current serial output:

```
AT
ERROR

```

Here is my code:

```
void setup() {
    Serial.begin(9600);
    Serial3.begin(115200); //Manufacture said this is the correct baud rate
}

void loop() {
    if ( Serial3.available() ) {  Serial.write( Serial3.read() );  }

    if ( Serial.available() )  {  Serial3.write( Serial.read() );  }
}

```

Here are my pin connections:

```
RX3  -> ESP TX
TX3  -> ESP RX
GND  -> GND
3.3V -> CH_PD + VCC

```

# Answer
The AT firmware responded with ERROR because it received data, but timed out waiting for the CR/LF line ending.

AT commands must be terminated with Carriage Return '\r' and Line Feed '\n' control bytes/characters.
> 7 votes

---
Tags: esp8266, arduino-due
---


# Question
Title: How to count the voltage pulses of a digital temperature sensor using Arduino Mega Atmega2560?
I have a digital temperature sensor which gives digital output in the form of current pulses. The number of pulses corresponds to a particular temperature.

I have converted the current pulses to voltage pulses using transistor as a level shifter. I want to count the number of pulses for a time interval of 50ms each time.

Please help me with the algo and the code.

# Answer
> 3 votes
There are function called pulseIn which probably need exactly what you want.

Just set a variable with the current 'time' (millis, start counting until the current time reaches 50 ms later.

So something like (not checked):

```
unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  pulses++;
}

```

PIN is a constant or variable that defines the pin number to check, LOW is to check low pulses, you also can use high, and optionally you can add a timeout. For example, you can use the timeout to check the last timeout is within the 50 ms region. Or to be more precise, check if the pulse was within the same 50 ms:

```
unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  if (timer + 50 < millis())
  {
    pulses++;
  }
}

```

---
Tags: arduino-mega
---


# Question
Title: Arduino command line vs. Arduino builder
I'm working on adding my Arduino to continuous integration and I came across two different possible ways of doing this, Arduino command line, and arduino-builder. Can someone explain why the arduino-builder tool exists separately from calling Arduino from the command line? And what are the advantages of using one over the other?

# Answer
> 9 votes
The Arduino IDE command line predates arduino-builder and was made available when the source pre-processing and compiling was implemented by a Java class (deeply) embedded in the IDE.

The current IDE uses arduino-builder behind the scenes to process and compile the code so if you use arduino-builder you avoid having to load the whole Java IDE. Try it out it does some pretty cool stuff

# Answer
> 1 votes
I've written a new option for Arduino CI/unit testing and put together a decent size writeup about it as an answer to this related question.

I ended up using the Arduino command line instead of arduino-builder, because it worked better cross-platform for me. It assumes a graphical display though, even if you just use the CLI features. In the case of Travis CI, I needed to spin up a fake X display to handle the initial splash screen and other graphical error messages. (Fortunately, you can tell based on how long a command takes to complete whether it's waiting for you to acknowledge a graphical error message.)

Some examples of how to enable CI on your own project:

---
Tags: programming, build, command-line
---


title: Less hardware dependent development?

text:
# Question
Title: Less hardware dependent development?
I'm working on a little Arduino game project that uses neopixel strips as a display. Uploading every code change to the Arduino and testing it on the LEDs is slow and drains hardware lifetime.

Usually I test as much I can using the Serial Monitor, but I can't get it to clear from code which I learned is only possible e.g. when using a terminal. I did that, but it comes with other issues.

Is there a better way to test code on the dev machine instead of the Arduino? Is there a best practice to have a Serial Monitor (or anything else) act like a display that I can actually refresh/clear? Serial.println() empty lines to scroll the content is not very practical.

# Answer
You can unit test your code by creating stubs of the functions you are calling, like replacing a couple of includes with their dumb counterparts. My friend Jan Beayens did something very valuable on that front and he is also the main author of a good replacement for the Arduino IDE when you start needing some more advanced capabilities: Sloeber is the product name and it also contains an improved version of the serial monitor with clear and scroll lock capabilities.

Go check it out.

Disclaimer : I'm a contributor of the project
> 1 votes

# Answer
As you've probably noticed, trying to run tests over the serial port is frustrating. Worse, the relatively large delays associated with writing serial data can affect the accuracy of your measurements.

To cope with this, I wrote my own unit testing framework for Arduino, which lets you fully mock (simulate) the hardware so that you can verify the operation of the software.

There are some examples of how my library accomplishes that, in the project README. Here is one for pins:

```
unittest(pin_history)
{
  GodmodeState* state = GODMODE();
  int myPin = 3;
  state->reset();            // pin will start LOW
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, HIGH);

  assertEqual(6, state->digitalPin[1].size());
  bool expected[6] = {LOW, HIGH, LOW, LOW, HIGH, HIGH};
  bool actual[6];

  // convert pin history to an array, and verify expected results
  int numMoved = state->digitalPin[myPin].toArray(actual, 6);
  assertEqual(6, numMoved);

  // verify each element
  for (int i = 0; i < 6; ++i) {
    assertEqual(expected[i], actual[i]);
  }
}

```

You may also like the example for mocking Serial port data, although I probably need to improve that documentation.

The beauty of all this is that I was able to develop this framework and all these tests without ever plugging an Arduino board into my computer.
> 1 votes

---
Tags: serial, display
---


# Question
Title: Forwarding serial output from a Nano to Uno that's used as the ISP
I'm trying to program a Nano by using an Uno as the ISP. So far, I've followed along with the example project for getting the Uno running as the ISP on https://www.arduino.cc/en/Tutorial/ArduinoISP.

After a bit of tinkering, it works, but the serial monitor won't work correctly. I'm uploading a super simple program that delays for 500 ms and prints to the log.

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

void loop() {
  Serial.println("test");
  delay(500);
}

```

I've wired the TX pin on the Nano to the RX pin on the uno. The monitor updates every 500 ms as expected after doing so, but displays ��� instead of the word test. When I tried wiring TX -\> TX, the serial monitor does not update. Does anyone have any insight what's missing here?

# Answer
As Chris Stratton suggests in his comment above:

> You can't really connect an ordinary Arduino's serial pins to both another device and the on-board USB serial converter at the same time.

To solve your serial monitor problem use a separate USB serial converter and connect that to your Arduino Nano.

If you don't have access to a dedicated USB serial converter you could use software serial on the Arduino Nano. This allows you to connect the Arduino Uno Rx pin to the software serial Tx pin. You will also need to program the Arduino Uno with a program that re-transmits the data it receives back out to the PC serial monitor.
> 1 votes

---
Tags: arduino-uno, serial, arduino-nano, isp
---


# Question
Title: What is a safe way to power arduino nano with 7.4V Lipo battery?
I'm trying to power Arduino Nano with 7.4V LiPo battery and use it to run 2 DC motor using L293D. I have figured out how power it with the connection just like in the figure below(the diagram uses Uno and the battery is 9V but try to imagine it as Nano and 7.4V). I also found another way to power it by connecting the red wire from battery to Vin on the Arduino instead of connecting it to the positive power rail.

So, my question is which is a safer way to power it and what is the difference and risk of one the way I mention.

# Answer
> 2 votes
Connect it via the Vin pin. That way the 6-8.4 volt of the battery will go through the voltage regulator on the Nano, giving you a stable 5v.

What you show in your diagram is the wrong way of connecting the battery. The absolute maximum you can supply to the Arduino's 5V pin is 6 Volt. Atmel recommends no more than 5.5V. So your battery exceeds this when it's full.

---
Tags: arduino-nano, battery, safety
---


title: Can not connect with Bluetooth hc-05

text:
# Question
Title: Can not connect with Bluetooth hc-05
I connect my Bluetooth hc-05. But the blind led in the Bluetooth module is not stable when I connect with my Android phone. Help help me to solve this.

# Answer
> 1 votes
It is very simple really.

Initially the Bluetooth got paired automatically with my Android, but apparently the variable transmission was not complete.

**If this is the case with your module,it will be blinking with high frequency.**

So here is what I did:

1. Hit the RESET button on HC-05 once
2. Go to Android Bluetooth Settings and UNPAIR HC-05
3. Now Pair it again by clicking on it
4. You will be prompted to enter password- '1234'
5. Open your Bluetooth Terminal and you will find your data appearing on Android

**P.S.-A 2 Hz blinking frequency on HC-05 should signify proper connection**

# Answer
> 0 votes
Through which android app you are connecting because normally android only pair and will connect to device if you are sharing some data or files or you can connect to android device using any bluetooth app like bluetooth terminal or dual bluetooth chat

---
Tags: bluetooth
---


# Question
Title: How to measure water turbidity with arduino
I would like to measure water turbidity in the sea. The sensor does not need to measure it in an accurate way, I just need to know if water is clear or very turbided. I know that there could be used a light scatter but I do not know what kind of sensor should I use. Could anyone help how to measure turbidity?

# Answer
> 2 votes
http://uk.farnell.com/ams/tsl257-lf/sensor-light-voltage-converter/dp/1226886 is a good one according to http://forum.arduino.cc/index.php?topic=299993.0

But it might be easier to buy a COTS sensor, its a bit more expensive but much easier. http://www.aliexpress.com/item/Turbidity-Testing-Sensor-Module-Suite/1903197650.html?spm=2114.01010208.3.17.OSVwdj&ws\_ab\_test=searchweb201556\_9,searchweb201602\_2\_10017\_9868\_10005\_10006\_10034\_10021\_507\_10022\_10020\_1000020\_10018\_10019,searchweb201603\_8&btsid=6dbcca61-3e0a-4e34-9359-a6c26b268509

BTW for everyone else Turbidity is the amount of muck in the water, so it would be no good looking at the crystal clear waters off the UK coast :)

# Answer
> 1 votes
I used an array of cheap light dependent resistors hermetically sealed and used a torch. For dark water, it clearly shows a lower value than for cristal water. It is kind of a binary sensor, but I was proud of my basic invention!

---
Tags: sensors
---


# Question
Title: Trying to make sense of the coding style in Arduino libraries. (Particularly the Radiohead library)
I've been using the Arduino IDE for some time now, and I want to shift to coding for the bare AVR microcontroller. So I wanted to begin by porting required arduino libraries to C/C++. I started with the Radiohead library, but I've noticed a lot of variables/tokens that are directly used without a definition for them. For example:

```
    // path :RadioHead/RH_ASK.cpp
#if (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
 #ifdef RH_ASK_PTT_PIN
    RH_ASK_PTT_DDR  |=  (1<<RH_ASK_PTT_PIN);
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #else
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #endif
#else
    // Set up digital IO pins for arduino
    pinMode(_txPin, OUTPUT);
    pinMode(_rxPin, INPUT);
    pinMode(_pttPin, OUTPUT);
#endif

```

None of the tokens in this snippet like "RH\_ASK\_PTT\_PIN" or "RH\_ASK\_TX\_PIN" were mentioned anywhere in the code before or any other file that was included.

I understand what the code does, but how does the compiler know what these tokens mean? I tried to compile this code using Atmel Studio but it gives me an error (As it should): `"RH_ASK_PTT_PIN" not declared in this scope` So how does this library work with the Arduino IDE?

Link to the library : https://github.com/PaulStoffregen/RadioHead

Also can someone suggest tags for this post? Its my first post here.

# Answer
They're not defined. If you notice that whole block is wrapped in a `#ifdef` which will be false unless you're on some specific platform, where the platform defines those macros.

Everything else uses the last little bit:

```
pinMode(_txPin, OUTPUT);
pinMode(_rxPin, INPUT);
pinMode(_pttPin, OUTPUT);

```

You only need to care about that bit - nothing else is of any concern unless you're using a "RH\_PLATFORM\_GENERIC\_AVR8" (whatever that is).
> 3 votes

---
Tags: c++, library, avr
---


# Question
Title: What is better approach for non blocking pid algorithm?
I'm developing software side for 3 axes robot where are 360° continuous rotating servos used Documentation here

these servos have its own feedback system so it's possible to control it's position via pid system, when im using only one PID algorithm in clear sketch just for this pid everything working OK but when I want to use multiple PIDs there are problem with delays and every next function that is used in the sketch will result in bigger delays that make these servos flicking because it's executed in main function

```
int pinFeedback = pin_comes_here;

float tHigh = 0;
float tLow = 0;
int tCycle = 0;
float dc = 0;
float angle = 0;
float dcMin = 2.9;
float dcMax = 97.1;

void setup() {
  pinMode(pinFeedback, INPUT);
}

void loop() {
    while(1) //From Parallax spec sheet
    {                                       //There is core of the problem
      tHigh = pulseIn(pinFeedback, HIGH);
      tLow = pulseIn(pinFeedback, LOW);
      tCycle = tHigh + tLow;
      if ( tCycle > 1000 && tCycle < 1200)
        {
          break; //valid tCycle;
        }
    }

  dc = (100 * tHigh) / tCycle; //From Parallax spec sheet, determine the percentage of the HIGH in the pulse

  angle = ((dc - dcMin) * 360) / (dcMax - dcMin + 1); //From Parallax spec sheet

  if (angle < 0)
  {
    angle = 0;
  }
  else if(angle > 359)
  {
    angle = 359;
  }

    //This is just angle calculation part, we have angle as output value from this algorithm so its possible to calculate error how much to left or right value from out target angle value and adjust servo position via standard servo library

}

```

Reason why i need non blocking angle calculating is that because with everything this, i need to be able to control angles from firmata protocol and not just firmata but there can't be anything else done in sketch and i mentioned everything else causing bigger delays between reading signal, calculating angle, adjusting position, and every next function that could be placed in main loop.

So i came to the point that i need to use timer and interrupts like servo library uses by creating something like basic servo library wraper where i create PID class that inherit Servo class members for sake of accesing servo members from one object (attach, write) and two different approaches came to my mind

1. This PID class could instead of waiting in while loop for pulseIn sacrifices another one Timer that could divide feedback signal period which is long 1,1millisecond (see documentation, heading: feedback signal) by checking if it's up or down every several microseconds and counting total signal uptime for period and then calculate angle and error and adjust position with inherited write() member for every object from one timer
2. Using attachInterrupt that could behave similar like pulseIn but outside of main loop for every object(with same approach with PID class with inherted servo class)

# Answer
The main issue you have is that `pulseIn()` is completely blocking - and your `while` loop doesn't help much either.

The "proper" (or what I would consider the "proper") way of dealing with this is to use a timer in *gated* mode. Actually you need two timers, but the Arduino already provides you `micros()` that will do for one of them.

Basically your pulsed signal is input into the gate input of a timer. That timer, when the gate input is HIGH, will count the number of ticks from whatever clock source you configure it for (system clock, etc, with or without prescaler, etc). It also needs to be configured so that the timer triggers an interrupt at the falling edge of the gate.

That interrupt reads the count from the timer and resets the count to 0 ready for the next pulse. It also uses `micros()` to work out the time between successive falling edges (should be about 1100us). A little bit of maths is needed to calculate the time from the count.

It's not something I have ever done with an Arduino - I have only used a PIC32 for it - though I assume that AVR timers have a gated mode (they should have; they are fairly comprehensive timers). Check the datasheet to be sure - as well as for how to configure it. On the PIC32 I used two timers both running at the same speed from the same clock source - one in gated mode to count the HIGH time and one in free-running mode to count the full period time. The duty % is then the ratio of the two counts and you don't care about the actual time in human-created units.

Of course, it goes without saying that you need a gated timer for each servo you want to sense...
> 1 votes

---
Tags: arduino-mega, interrupt, servo, timers, pid
---


title: Splitting SCL and SDA pins

text:
# Question
Title: Splitting SCL and SDA pins
For a robotics project I am using an MCP23017 I/O Port Expander in order to have more pins available, and I am also using a PS2 controller for input. Both of these require pins 4 and 5 (because these are the data and clock pins). I was wondering if I can use a breadboard to simply connect these two pins to both devices in order to provide both of them with data and clock pins.

I am using an Arduino UNO and a playstation 2 controller with the following guide: http://www.techmonkeybusiness.com/using-a-playstation-2-controller-with-your-arduino-project.html

# Answer
You are confusing pins here. In the library you mention there is a function call to set up the gamepad:

```
 ps2x.config_gamepad(5,4,3,2, false, false);
 //setup pins and settings: GamePad(clock, command, attention, data, Pressures, Rumble)

```

That is **digital** pins 5, 4, 3 and 2.

I2C uses **analog** input pins A4 and A5 on the other side of your Uno board.
> 1 votes

# Answer
An I2C bus can be connected to many slaves at the same time, since in the I2C protocol every slave has an address.

But, as Majenko wrote in the comments, the library for the PS2 controller doesn't use I2C. The communication with the controller is bit banged, meaning that every part of the communication is done by software. This can be done with every digital pin on the Arduino. In your setup you have to usw the function `ps2x.config_gamepad()`. In it's parameters you can set the pins that the library will use.
> 0 votes

---
Tags: arduino-uno, i2c
---


# Question
Title: What do I have to change to make this code functional?
I have a joystick, an I2C 16x2 character display, and an Arduino. I want to move the joystick and get an on-screen character (specifically, the letter h) to move in the direction that I pushed the joystick. Here is the Arduino code.

```
#include <LiquidCrystal_I2C.h>
int xVal;
LiquidCrystal_I2C lcd(0x27, 16, 2);
int yVal;

int blockPos[]= {8, 0};
int blockPosBack[]= {8, 0};

int ycal;
int xcal;
void setup() {

    lcd.begin();
    lcd.clear();
    lcd.backlight();
Serial.begin(9600);

pinMode(A0, INPUT);

pinMode(A2, INPUT);
lcd.setCursor(blockPos[0], blockPos[1]);
//lcd.print("h");

ycal = 500;
xcal = 514;
}

void loop() {

xVal = analogRead(A0);

yVal = analogRead(A2);

Serial.print(" Y is...");

Serial.print(yVal);

Serial.print(" X is...");

Serial.println(xVal);

blockPosBack[0] = blockPos[0];
blockPosBack[1] = blockPos[1];

if(xVal < (xcal - 150)){
  if(blockPos[0] > 0){
    blockPos[0] - 1;
    }
  }

  if(xVal > (xcal + 150)){
  if(blockPos[0] < 15){
    blockPos[0] + 1;
    }
  }

  if(yVal < (ycal - 150)){
  if(blockPos[1] > 0){
    blockPos[1] -1;
    }
  }

  if(yVal > (ycal + 150)){
  if(blockPos[1] < 1){
    blockPos[0] +1;
    }
  }
if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
  lcd.clear();}
  lcd.setCursor(blockPos[0], blockPos[1]);
  lcd.print("h");
}

```

The problem is, I get a message saying that "expected ')' before '!' token". How do I solve this, and how do I change the code to make it functional?

Edit: I learnt that '!' is not the same as 'not equal to', which is '!='. I tried this, but now the h just sits at the initial position but doesn't move when I move the joystick. What do I have to change in the code to make it work?

# Answer
> 1 votes
Like stated in my comment, to have proper condition for clearing the display, the condition you should want to meet are:

`if ( (newX != previousX) OR (newY != previousY)) {
 clearLCD()
}`

EDIT: Or else, what you're saying is that you're only clearing the display when you have changed both X and Y *at the same time*

And to adress your problem with the 'h' not moving, you need to change the lines `blockPos[0] - 1;` etc

into

`blockPos[0] = blockPos[0] -1;`

or

`blockPos[0]--;`

or else, you're not really assigning the new value to the variable containing the position to use in the display.

# Answer
> 1 votes
!! is not a valid logical operator, you probably meant || for locical OR?

Did you verify that the condition to change the blockpos value is actually fulfilled? Means are you sure one of your if blocks is actually executed?

# Answer
> -1 votes
First of all you should have edited the code way better, if you want help and want us to understand you must edit it properly.

```
if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
  lcd.clear();}
  lcd.setCursor(blockPos[0], blockPos[1]);
  lcd.print("h");
}

```

I took some time to understand that lcd.setCursor and lcd.print wansn't part of the if. When you are using 2 different sensors or components, you must try them separatly first, and when you got them both working fine that's when you use them together. https://www.arduino.cc/en/Tutorial/JoyStick

This is an example pretty much more simple than yours, so i just think you must try lcd first, and when you understand how lcd works, and how joystick works, you can easly interact them.

---
Tags: i2c, lcd
---


# Question
Title: Lag in fetching serial data from Arduino
I am working on a project based on **Arduino** and **python3.6**,two HC-SR04 sense the distance of palms and process the data using Arduino and send it through serial port to python3.6 ,python3.6 with the help of **pyserial** ,**pyautogui** based on data from arduino controls a game named **supertuxcart**,a racing game,basically the thought behind this is controlling game with palms instead of keyboard or mouse .But the problem am facing is Arduino takes the distance measurement data from two HC-SR04(one for each hand) ultrasonic sensors, processes according and sends processed data through serial port to python3.6 ,there while running the my python script i open the game to check if its working ,it works, but there is lag in data received from arduino thus turn the game messy.

here is **arduino** code am using with **NewPing** library

```
#include <NewPing.h>
int trig1=9;
int echo1=6;
int trig2=7;
int echo2=5;
int R;
int L;
NewPing right(9,6,100);
NewPing left(7,5,100);
void setup() {

  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(6,INPUT);
  pinMode(5,INPUT);

}

void loop() {
  Serial.begin(9600);
  //Serial.println("hi,am arduino");
  R=right.ping_cm();
  L=left.ping_cm();
  //Serial.println(R);
  //Serial.println(L);
  delay(0000);
 if (R==0 && L==0){
    Serial.println('0');
  }
  else if(R<L&&L-R>5){
    Serial.println('1');
  }
  else if(R>L&&R-L>5){
    Serial.println('2');

delay(3000);

  }

}

```

Here is **python3.6** code am using

```
import serial
import pyautogui
import time

Arduino = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(0)
print(Arduino.readline())
pyautogui.keyDown('up')
while 1:
    Data = Arduino.readline()
    print(Arduino.readline())

    if Data == b'0\r\n':
        pyautogui.keyUp('up')
        pyautogui.keyUp('right')
        pyautogui.keyUp('left')
        break
    elif Data == b'1\r\n':
        pyautogui.keyUp('left')
        pyautogui.keyDown('right')
    elif Data == b'2\r\n':
        pyautogui.keyUp('right')
        pyautogui.keyDown('left')

```

# Answer
> 1 votes
A couple of things jump out at me:

1. You only need to run `Serial.begin(9600)` once in `setup()` \- never in `loop()` like that.
2. Your `delay(3000)` will be causing a 3 second delay when `R>L&&R-L>5`.
3. You don't need to constantly send the data over and over again. You just need to send it once and once only when the state changes.

At the moment you're sending something like:

```
0000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000002222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222200000000000000000000000000000000000000000000000000000000000000

```

when all you really need to do is send `01020`. Remember what the state is and only send anything when that state changes from one iteration to the next. And never ever use `delay()`.

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


title: Scan IP address of ESP8266

text:
# Question
Title: Scan IP address of ESP8266
I am working on a project in which, the mobile app/browser sends HTTP command to ESP8266 in AP mode. The default IP address of ESP is 192.168.4.1. Therefore in order to connect the ESP to WiFi, the command goes like this :- 192.168.4.1/SSID=XYZ/Pass=XYZ.

On connecting to router, the ESP goes into STA mode and Doesn't create AP until WiFi is not found to which it was connected earlier. Now when ESP is connected to router, the router assigns the IP to ESP through which HTTP command will be sent. On Serial monitor, it does show the IP address to which it is assigned, but what if app controls the ESP, there is no serial communication. How will app know the IP address assigned to particular ESP8266? Is there any way app can scan the router? Or any other way to do this? If there are multiple ESP connected to router, how can I identify the IP of particular ESP.

# Answer
> 3 votes
The de-facto standard way for devices to broadcast their IP address to clients is through the Multicast DNS system (mDNS). In this system the server sends a UDP message to a specific multicast group address and clients listen for it so they can work out what is where.

mDNS is also known as Zeroconf or Bonjour depending on who you talk to.

The ESP8266 Arduino core (if you are programming the ESP8266 directly) has mDNS examples with it. If you are using the AT command interface instead, then you will need to read the manual to find how to send UDP packets to multicast addresses.

# Answer
> 1 votes
Have the app send a broadcast UDP packet, and have the ESP listen for such broadcasts. Now the ESP knows the IP address of the device on which the app is running, and it can somehow let it know its own IP address: perhaps connecting to a particular socket on which the app will listen, or sending a UDP broadcast of its own.

# Answer
> 0 votes
You can hard-code the required IP address for ESP8266. (That may not be possible all the times). There's a sample code :https://www.arduino.cc/en/Reference/WiFiConfig

If you are not hard-coding IP address, you can read IP address of ESP by using WiFi.localIP() function in Arduino.

# Answer
> 0 votes
Regarding mDNS is the solution but unfortunately it has limitation just like currently not supported with Android Platform.

My Suggestion is to keep listen the UDP port on all range of IP address of network as of token and on when you found right reply of UPD packet along with that device IP/MAC/port inside of that replayed packet then you will good to go.

No doubt this will take bit time to done but its only one time or until the IP has been changed.

---
Tags: esp8266, wifi, tcpip, http
---


# Question
Title: IO with port manipulation while not interfering with i2c
I'm using an Attiny84 with the Tiny Core. I'm try to use port manipulation to write the lower four bits of port A. I'm using i2c which occupies bits 5 and 7.

How can I write only to the lower 4 bits to avoid interfering with the i2c?

# Answer
I don't think you need to worry. A simple piece of code:

```
void setup()
{
 PORTA |= bit (0);
}

void loop() { }

```

Generates:

```
00000044 <setup>:
  44:   d8 9a           sbi 0x1b, 0 ; 27
  46:   08 95           ret

```

In other words, the compiler generates code to set that bit, ignoring all the other bits.
> 1 votes

---
Tags: i2c, attiny
---


title: Getting 3.3v on 5v pin in Arduino Uno

text:
# Question
Title: Getting 3.3v on 5v pin in Arduino Uno
When interfacing my Arduino Uno with a relay I was facing reliability issues, and while investigating it with a multimeter, I found something strange.

I noticed that in the 5V power pin (with which I was powering my circuit) is producing only 3.3V when using the power adapter. However, when connected via the USB-A port, the 5V pin was producing the expected 5V voltage.

I tried powering it in many ways - computer-to-USB-A, computer-to-barrel-jack, phone-charger-to-USB-A, phone-charger-to-barrel-jack and an external 5V DC power supply. In all cases, the above observation held true - powering the board through the barrel jack made the 5V power pins produce only 3.3V.

Question: Why is this happening? Does that mean my board is faulty? Is there any way to fix this?

# Answer
> and an external 5V DC power supply

OK, assuming you are putting 5V into the barrel jack this is exactly what you expect to happen.

From the Arduino Uno specifications you are supposed to supply a *recommended* 7V to 12V. Your supply of 5V is too low.

The barrel jack first goes through a M7 protection diode which would have about a 0.7V forward voltage drop, and then through a NCP1117ST50T3G voltage regulator which has a dropout voltage of (typically) 0.95V at 100 mA.

Thus you have:

```
5V input - 0.7V - 0.95V = 3.35V

```

That is what you are finding.

---

## Solutions

* If you have a proper, regulated, 5V DC supply you can put that directly onto the 5V pin of the Arduino. Better get the wires around the right way because you are bypassing the protection diode!
* Get a DC supply in the range 7V to 12V and put that into the barrel jack.
* Another simple idea is to just get a wall-wart that is used for charging phones via USB and run a USB cable into the Arduino USB port.

---

## Empirical test

I put 5V into the barrel jack of my Uno and read 3.33V on the 5V pin, which is pretty-much what you got. I measured a 0.77V drop over the M7 diode.
> 7 votes

# Answer
While Nick's answer is 100% (technically) correct. Functionally, it's a much easier story (given you feed 5V into the barrel jack).

Check the Arduino's product page.

```
Microcontroller ATmega328P
Operating Voltage   5V
Input Voltage (recommended) 7-12V

```

So yes, while the Arduino runs on 5V (and does so over USB). The recommended input voltage is 7-12V. You're simply not supplying a high enough voltage.

The difference, as per Nick's answer, is the protection circuit and regulator snooping off a few volts (which is bypassed when using USB).
> 1 votes

---
Tags: arduino-uno, voltage-level
---


title: Arduino + SIM808 HTTP GET POST headers

text:
# Question
Title: Arduino + SIM808 HTTP GET POST headers
I am trying to get working SIM808 with Arduino. Can GET and POST GPRS HTTP request but only what cames on it's just body from server side `{"error":true,"message":"Unauthorized"}` but I need header as it brings cookie for session.

```
+CREG: 0,1

AT+SAPBR=3,1,"Contype","GPRS"

OK

AT+SAPBR=3,1,"APN","giffgaff.com"

OK

AT+SAPBR=3,1,"USER","giffgaff"

OK

AT+SAPBR=3,1,"PWD",""

OK

AT+SAPBR=1,1

AT+SAPBR=2,1

+SAPBR: 1,1,"xx.xxx.xxx.xxx"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","http://www.xxx.co.uk/index.php"

OK
AT+HTTPPARA="UA","MH Tracker"

OK
AT+HTTPPARA="CONTENT","Content-Length: 42"

OK
AT+HTTPPARA="CONTENT","Content-Type: application/x-www-form-urlencoded"

OK
AT+HTTPSSL=0

OK
AT+HTTPDATA=41,30000

pass=xxxx&user=xxxx&action=xxxx

OK

AT+HTTPACTION=1

OK

+HTTPACTION: 1,401,39

AT+HTTPREAD

+HTTPREAD: 39

{"error":true,"message":"Unauthorized"}

OK

AT+HTTPTERM

```

I got some results, but with error, looks like my code have some junk characters

any advice

```
POST /client/index.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.mhprojects.co.uk
Content-Length: 41

pass=xxx6&user=xxx&action=xxx

SEND OK
HTTP/1.1 400 Bad Request
Date: Thu, 01 Feb 2018 00:38:56 GMT
Server: Apache
Content-Length: 357
Connection: close
Content-Type: text/html; charset=iso-8859-1

400 Bad Request

# Bad Request

Your browser sent a request that this server could not understand.

Additionally, a 500 Internal Server Error
error was encountered while trying to use an ErrorDocument to handle the request.

```

Arduino code

```
    char data[350]="POST /client/index.php HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: www.mhprojects.co.uk\r\nContent-Length: 41\r\n\r\npass=xxx&user=xxx&action=xxx";
int PowerOn = 12;//Power on pin
int Reset = 11;//Reset pin
char aux_str[50];
//////////////
void setup() {

  pinMode(PowerOn, OUTPUT);
  pinMode(Reset, OUTPUT);
  Serial.begin(9600);// UART baud rate

  power_on();

  Serial.println(F("Powering ON"));
  Serial.println();
  Serial.println(F("Connecting to the network..."));

  while( send_command("AT+CREG?", "+CREG: 0,1", 1000)== 0 );

}

/////////////
void loop() {

char buffer[200];

if (send_command("AT+CIPMUX=0", "OK", 2000) == 1)// Selects Single-connection mode
  {
  if (send_command("AT+CSTT=\"giffgaff.com\",\"giffgaff\",\"\"", "OK", 2000) == 1)// Sets the APN, user name and password
    {
      if (send_command("AT+CIICR", "OK", 10000) == 1)// Brings Up Wireless Connection
        {
          if (send_command("AT+CIFSR", ".", 3000) == 1)// Gets Local IP Address
            {
              if (send_command("AT+CIPSTART=\"TCP\",\"www.mhprojects.co.uk\",\"80\"","CONNECT OK", 10000) == 1)// Opens a TCP socket
                  {
                     sprintf(aux_str,"AT+CIPSEND=%d", strlen(data));
                     if (send_command(aux_str, ">", 1000) == 1) {

                     send_command(data, "SEND OK", 1000);

                     while (true)  {

                     read_UART_buffer(buffer,sizeof(buffer), 0);

                     }
                     Serial.println(buffer);
                     }
                                }
                                else
                               {
                             Serial.println(F("Error setup TCP connection\r\n\r\n"));
                           }
                        }
                      else
                    {
                  Serial.println(F("Error getting the IP address\r\n\r\n"));
                }
              }
             else
           {
         Serial.println(F("Error bring up wireless connection\r\n\r\n"));
        }
      }
    else
  {
Serial.print(F("Error setting the APN\r\n\r\n"));
    }
      }
        else
        {
          Serial.print(F("Error setting the single connection\r\n\r\n"));
         }

    send_command("AT+CIPCLOSE", "CLOSE OK", 1000);

    send_command("AT+CIPSHUT", "SHUT OK", 1000);

}

////////////////
void power_on() {

        // power on pulse
        digitalWrite(PowerOn,LOW);
        delay(500);
        digitalWrite(PowerOn,HIGH);
        delay(3000);
        digitalWrite(PowerOn,LOW);
        delay(3000);
}

///////////////
void reset()  {
  digitalWrite(Reset,LOW);
  delay(500);
  digitalWrite(Reset,HIGH);
  delay(3000);
  digitalWrite(PowerOn,LOW);
  delay(500);
}

///////////////////////////////////////////////////////////////////////////////////
int8_t send_command(char* ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0,  answer = 0;
  char response[50];
  unsigned long previous;

  memset(response, '\0', 50);    // Initialice the string

  delay(100);

  while ( Serial.available() > 0) Serial.read();   // Clean the input buffer

    Serial.println();
    Serial.println();
    Serial.println(ATcommand);    // Send the AT command

  x = 0;
  previous = millis();

  // this loop waits for the answer
  do {
    if (Serial.available() != 0) {  // if there are data in the UART input buffer, reads it and checks for the asnwer
      response[x] = Serial.read();
      Serial.print(response[x]);
      x++;
      if (strstr(response, expected_answer) != NULL)    // check if the desired answer (OK) is in the response of the module
      {
        answer = 1;
      }
    }
  }

  while ((answer == 0) && ((millis() - previous)  0) Serial.read();   // Clean the input buffer
}

////////////////////////////////////////////////////////////
void read_UART_buffer(char *buffer,int count, unsigned int timeOut) {
  int i = 0;
  unsigned long timerStart;
  timerStart = millis();

 while(1) {
  while  (Serial.available()!=0){
    Serial.write(Serial.read());
    char c = Serial.read();
    buffer[i++] = c;

  }
  //buffer[i]='\0';
    if((unsigned long) (millis() - timerStart)  > timeOut * 1000UL) {
            break;
        }
 }
}

```

# Answer
Are you sure the Content length is 41? Doesn't seem like it, make sure it's the same length as your message body.

This depends from server to server, but I think you should also put a CRLF after your message body.
> 1 votes

---
Tags: arduino-uno
---


title: Arduino UNO reset using SIM800L

text:
# Question
Title: Arduino UNO reset using SIM800L
I'm using the **SIM800L** module but i've problems. I'm triying to connect it to the **Elegoo UNO** i've, but it restarts at all times. Also the led of signal strengh blink every second, so i dont get signal.

I also upload a video to Youtube to explain the problem, this is the link.

Thanks in advance!

# Answer
When the reset pin of Uno is connected to ground, the Uno resets. That is what the reset button does.

You connected the reset pin of Uno to other device's reset pin. If the reset pin of the other device grounds the reset pin of Uno (grounds or has lower then required voltage), then Uno resets.

The reset pin of a peripheral device is intended to reinitialize the device by program running in microcontroler by setting a connected GPIO pin to required state.

If you have a library for the device, that library will take care of the GPIO pin controlling the reset of the device.

If you plan to use the device without library, then you should take care of the reset pin in your sketch. Setting the selected pin to OUTPUT and initializing it to required state.

The usual required state for reset is LOW so the output must be HIGH for the device to work.

Some tutorials and libraries require connecting the reset pin of gsm800l to a selected Uno GPIO pin with a transistor, and then reset is HIGH and LOW is for normal operation.
> 1 votes

# Answer
Besides the RST pin situation that the others pointed out, you're not going to do much with the way you're powering the module. It might turn on, but you will never be able to register on the network. You have to power the module with an external power source and common the ground.

Also, if the module you're using is the one on the image, you might need a logic level shifter to use the Tx-Rx connection.
> 1 votes

---
Tags: arduino-uno, electronics, wireless
---


title: SIM800L not registering to network

text:
# Question
Title: SIM800L not registering to network
I am using SIM800L module. I am new to GSM modules. I have searched in many web sites about SIM800L, every where they mentioned baud rate 9600 for `SoftwareSerial` but it is not working at all in my case. So I started a trail and error method to match baud rate. Finally I found that its baud rate is 38400. With baud rate of 9600 for Arduino and 38400 I am able to communicate with SIM800L.

The problem is that I am unable to register to network. `AT+COPS=?` shows all available networks. Using `AT+COPS="value"` I am able to select network. But after that the SIM800L module still blinks every second.

In `loop()` I am continuously reading software serial and it's printing the following:

```
RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready
RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready

```

The above data is continuously printing on console.

# Answer
> 3 votes
I am 90% sure it's a power issue. Not sure on what board/module you're using but the SIM800L/SIM900 needs a burst of current of 2 A during 577 µS (See the manual).

Try using 4700 µF and a 10 µF capacitor in parallel with the module. Powering it with a proper power source instead of the Arduino wouldn't hurt too.

# Answer
> 0 votes
Might be some power issues, but I fixed mine by just trying some AT command

```
AT+CBAND?

```

Then, `AT+CBAND="DCS_MODE"`

That works for me. Give it a try man.

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


title: Connection Problems with GPRS Shield

text:
# Question
Title: Connection Problems with GPRS Shield
I recently bought a GPRS shield from Seeed Studio but was having issues running the programs described in their documentation. Here is everything you need to know about my shield:

Documentation for GPRS Shield V2.0

Website to purchase GPRS Shield V2.0

I assumed that there was a connection problem. I used the following code to try to debug my SIM900 and its connections to the sim card and the cellular network:

```
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(7,8);

void setup(){
  gprsSerial.begin(19200); // GPRS shield baud rate
  Serial.begin(19200);
  delay(500);
}

void loop(){
  if(Serial.available()) {
    switch(Serial.read()) {
      case '0': testSIM900(); break;
        // AT OK
      case '1': testSIMCARD(); break;
        // +CPIN: READY
        // +CREG: 0,1
      case '2': testNETWORK(); break;
        // +CGATT: 1
    }
  }

  if(gprsSerial.available()) Serial.write(gprsSerial.read());
}

void testSIM900() {
  gprsSerial.println("AT");
  // AT OK
  delay(100);

}

void testSIMCARD() {
  gprsSerial.println("AT+CPIN?");
  // +CPIN: READY
  delay(100);
  gprsSerial.println("AT+CREG?");
  // +CREG: 0,1
  delay(100);
}

void testNETWORK() {
  gprsSerial.println("AT+CGATT?");
  // +CGATT: 1
  delay(100);
}

```

When I entered 0, 1, and 2 into the serial monitor, I got the following response:

```
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CREG?

+CREG: 1,2

OK

+CREG: 0

+CGREG: 0
AT+CGATT?

+CGATT: 0

OK

```

What does this tell me about the current state of my shield, sim card, and network connection? Is there anything else I can do to isolate issues?

# Answer
> 1 votes
It seems it can't register on the network, GSM modems are power hungry, are you sure you're powering it up with the external power source (through Vin)? Pretty sure the Arduino isn't enough, but I could be wrong, that's a shield that has those issues in mind.

Also try to see the signal strength using AT+CSQ.

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


# Question
Title: powering arduino with a voltage divider to increase lifespan
I have a chinese arduino nano that I'm planning to use to open a door using a numeric keypad.

My power source is 12V and I want it running 24/7. I have read that the first thing to fail on an arduino is the voltage regulator due to the heat of lowering the voltage to something the arduino can use.

I have think of buying two big resistors of around 1W each to build a voltage divider and only feed 7V to the Vin pin of the arduino, so it will increase its lifespan.

Is this a good idea?

# Answer
Terminating voltage by dropping it over large power resistors is a bad idea, efficiency wise. There are better options.

Switch-mode Buck (=step down) converters are usually far more efficient than linear regulators. A linear regulator dumps the excess voltage in a resistor which converts the energy mainly into heat. A switch-mode converter works by switching on/off an inductance at the right time, which is far more efficient.

For step-up/step-down DC-DC converter theory look here, here and here. For a comparison for switch-mode against linear regulators look here.

A step-down converter module like the ones with a LM2596 should be good enough for you. See here on ebay.
> 2 votes

---
Tags: power, arduino-nano, voltage-level
---


# Question
Title: How to identify Adafruit Feather 32u4 via mac id/UUID/etc
I'm working with a couple Feather 32u4 devices and I've had success so far in setting them up as transmitters and receivers as well as hooking up one of them to a Featherwing Ethernet and talking over MQTT. My problem is that I'm trying to find out how I can implement some sort of identification system among them so that I can send packets to a specific radio. The approach I'd like to avoid is that of writing different versions of the code with different IDs hardcoded in each and uploading them to a radio (so ideally I'm wondering if there's a way to access an inherent mac ID/UUID of each radio). Each radio did come with what appears to be a mac ID printed on a piece of paper but I don't know how to access that directly from the device.

Thanks!

# Answer
I'm quite sure the reason they print a mac address on a sticker and put it in the package is that they have no way of storing the address in the the feather wing, or at least don't bother to do so if there is a place to store it.

It's up to you to get that address to your Ethernet.begin() call.

FYI, I have been trying to use EEPROM to store the mac address, but the bootloader appears to blow away EEPROM with every reboot. If I figure that one out I'll update.
> 0 votes

---
Tags: adafruit
---


title: Weird multiplication result

text:
# Question
Title: Weird multiplication result
Here's come Arduino code.

```
#define M(x, y) x * y;
void setup() {
  Serial.begin(9600);
  Serial.println(M(3 + 2, 4 + 2));
}
void loop() {
}

```

Why is the result 13?

# Answer
> 16 votes
Because `M(3 + 2, 4 + 2)` gets replaced to `3 + 2 * 4 + 2` and then the normal priority of operations does the multiply before the addition.

This is one of the many reasons why you should prefer functions over macros. The inliner of the compiler will negate any call overhead.

If you truly want to use a macro then surround each use of the macro arguments in parenthesis, surround the macro itself in parenthesis as well.

```
#define M(x, y) ((x) * (y))

```

---
Tags: arduino-uno
---


# Question
Title: LMT84 temperature sensor measurement error
I want to measure atmospheric temperature with an Arduino. The sensor I am using is an LMT84.

After uploading the following code to the Arduino board I am getting very high temperatures in the serial window.

I am unable to understand what the error in my code is. I've connected a 0.1 μF cap between Vcc and ground, and the data pin is connected to A1 on the Arduino.

Please check the following code:

```
const int sensor = A1; // assigning analog pin A1 to variable 'sensor'
float tempc;  // variable to store temperature in degree Celsius
float vout;   // temporary variable to hold sensor reading
float vout1;  // temporary variable to hold sensor reading

void setup()
{
  Serial.begin(9600);
  pinMode(sensor, INPUT); // configuring pin A1 as input
}

void loop()
{
  vout = analogRead(sensor);
  vout1 = (vout * 500) / 1023;
  tempc = vout1; // storing value in degrees Celsius
  Serial.print("LMT84 temp=");
  Serial.print(tempc);
  Serial.println();

  delay(1000);
}

```

The serial window shows these values:

```
LMT84 temp=168.13
LMT84 temp=168.13
LMT84 temp=168.64
LMT84 temp=168.89
LMT84 temp=168.13

```

# Answer
The Arduino uses an analog voltage as reference. It is default set to the Vcc of the microcontroller, which is about 5 V for an Arduino Uno. The function analogReference can be used to set something else as reference.

When that reference is not precisely 5.0 V, it is impossible to measure a voltage in a accurate way. It is almost never precisely 5.0 V. When using the USB connector to power the Arduino board, it might be somewhere between 4.5 and 5.0 V.

The Arduino Uno has an internal voltage reference of 1.1 V. That is better than using the default 5 V. The actual voltage can be 1.0 to 1.2 V, you have to put the actual value in your sketch.

The LMT84 has an output of 1034 mV at 0°C and 476 mV at 100°C. That means your calculation is not correct. In the datasheet are two ways to calculate the temperature, an accurate formula and a simple calculation.

You can avoid all these problems with a temperature sensor that has a digital interface to the Arduino board. For example the DS18B20. That is a cheap and accurate temperature sensor.
> 2 votes

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


title: State machine doesn't function

text:
# Question
Title: State machine doesn't function
My goal is to make a logic controller for a cassette tape mechanism, right now I'm simply trying to get the mechanism to engage and disengage the pinchroller arm which is motorized, spin the reels/capstan to advance the tape for playback; and stop the process by stopping the capstan motor, and retracting the pinchroller arm.

Currently this code doesn't respond to any of the button inputs, and I'm unsure as to why that is. I have another program that allows manual control of the motors, and that works fine, this however does not.

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

Here is my current full code:

```
const int motor1Pin = 5; //If motor1 is HIGH and motor2 is LOW,  the motor will spin one way, if motor1 is LOW and motor2 HIGH then the motor will spin in the opposite direction.
const int motor2Pin = 4;
const int motor3Pin = 2;
const int motor4Pin = 1;
const int enablePin = 6; //turns pinch roller arm motor on or off
const int enablePin2 = 3; //turns capstan motor on or off
const int limitswitch1Pin = 7; // end of top travel limit switch
const int limitswitch2Pin = 9; // end of bottom travel limit switch
const int cyclePin = 8; //switch that cycles the pinch roller arm depending on limit switches
const int reversePin = 10;
const int forwardPin = 11;
const int stopPin = 12;

int state;
int buttonState;
int limit1State;
int lastlimit1State;
int limit2State;
int lastlimit2State;
int reverseState;
int forwardState;
int stopState;

enum State_enum {STOP,PLAY};

bool enableState = false;
bool enable2State = false;

void setup() {

  pinMode(motor1Pin, OUTPUT);
  pinMode(motor2Pin, OUTPUT);
  pinMode(motor3Pin, OUTPUT);
  pinMode(motor4Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);
  pinMode(enablePin2, OUTPUT);
  pinMode(reversePin, INPUT_PULLUP);
  pinMode(forwardPin, INPUT_PULLUP);
  pinMode(stopPin, INPUT_PULLUP);
  pinMode(limitswitch1Pin, INPUT_PULLUP);
  pinMode(limitswitch2Pin, INPUT_PULLUP);
  pinMode(cyclePin, INPUT_PULLUP);
  pinMode(A0, INPUT);

  buttonState = digitalRead(cyclePin);
  limit1State = digitalRead(limitswitch1Pin);
  limit2State = digitalRead(limitswitch2Pin);
  reverseState = digitalRead(reversePin);
  forwardState = digitalRead(forwardPin);
  stopState = digitalRead(stopPin);

}

void loop() {

  if (buttonState == LOW) int state = PLAY;
  if (stopState == LOW) int state = STOP;

  switch (state) {
  case PLAY: //Plays the cassette
    if (stopState == LOW) {
      state = STOP;
    }
    if (limit1State == LOW) { //running the pinchroller arm clockwise from the top to bottom

      digitalWrite(motor1Pin, HIGH); // set leg 1 of the pinchroller motor H-bridge high
      digitalWrite(motor2Pin, LOW); // set leg 2 of the pinchrooler motor H-bridge low
      analogWrite(enablePin, 176); //set pinchroller motor speed

    } else if (limit2State == LOW) { //pinchroller arm is fully down (at bottom)
      digitalWrite(enablePin, LOW); //disable pinch roller motor
      digitalWrite(motor3Pin, LOW); // set leg 3 of the capstan motor H-bridge low
      digitalWrite(motor4Pin, HIGH); // set leg 4 of the capstan motor H-bridge high
      analogWrite(enablePin2, 200); // set capstan motor speed
      digitalWrite(enable2State, true);
    }
    break;

  case STOP: //Stops the cassette
    if (enable2State == true && limit2State == LOW) {
      digitalWrite(enablePin2, LOW);
      digitalWrite(enable2State, false);

    } else if (enable2State == false && limit2State == LOW) {
      //running the pinchroller arm counter-clockwise from the bottom to top

      digitalWrite(motor1Pin, LOW); // set leg 1 of the motor H-bridge high
      digitalWrite(motor2Pin, HIGH); // set leg 2 of the motor H-bridge low
      analogWrite(enablePin, 176); //set pincroller motor speed

      if (limit1State == LOW) {
        digitalWrite(enablePin, LOW);
      }
    }
    break;

  }
}

```

# Answer
I don't know enough about how tapes work to comment on the sense of what you're doing, but some problems with the code:

You are reading the input and setting `buttonstate` once only in `setup()`. You need to read it repeatedly, by putting it in `loop()`.

You also have three variables called `state`: one global which is never set, and two with very restricted scope which are set but never used - they go out of scope immediately. Remove the `int`s where you set `state` in your `loop()`.

This part is useless because you've already done it just above, but probably not hurting anything:

```
if (stopState == LOW) {
    state = STOP;
}

```

That's as far as I got. If that doesn't fix it, consider adding trace: you'd have found these two problems pretty quickly if you'd printed out the variables to check your assumptions.
> 4 votes

---
Tags: arduino-uno, motor, l293d
---


# Question
Title: Unknown USB Device (Device Descriptor Request Failed) - Win 10
I am posting a possible solution here for any online searches happening upon this exact issue.

So I have a third party board (Mega 2560) and I was plagued with my board intermittently working, on some rare occasions it worked but in most cases it just threw me the "USB device not recognized" after plugging it into my pc.

Upon closer inspection I have noticed the following

The one coupling capacitor (Blocks DC but allows AC and signal to pass) was poorly soldered, barely making contact!

So if your pc intermittently connects to your arduino, maybe check what the physical signal path looks like, you might find something like this.

# Answer
SMD soldering is not easy but here is the fix. Continuity achieved!
> 3 votes

---
Tags: usb, windows
---


# Question
Title: Adadfruit Trinket software not running on ATtiny85
I have an application that uses a pair of nRF24L01+ as a simple RF link between a camera PC sync output and a set of LED flashes. The important factors are power and low latency - hence the 2.4GHz.

I developed both ends using UNOs and then moved to Trinket 3 V. The system works very well with Trinkets. My next step was to strip this down further to ATtiny85 at least at the receiver end. I overcame the programming challenges and a day's worth of board installation in Arduino IDE and can not now program the ATtiny85 as well as the Trinket.

I will share the code lower down, but let me explain the difference in result.

With the Trinket the trigger output from the receiver is a simple pulse the width of the transmitted pulse (as is the goal.

```
               __________________________________
 _____________|                                  |__________________________
```

The pulse is anywhere from 5 ms to 50 ms.

On the ATtiny85 the link is clearly operational from transmitter to receiver but the output is ugly. Something like this:

```
                 _____      _____            _____
________________|     |____|     |__________|     |___________
```

The pulses appear (not always the same number) for the duration of the transmitted pulse and the interval is variable. The pulses themselves are of 8 MHz duration.

**The code:**

```
#include "RF24.h"

// Note: these includes looked necessary when I started but during debugging I
// removed them with not change in functionality - strange!
//#include <Mirf85.h>
//#include <MirfHardwareSpiDriver85.h>
//#include <MirfSpiDriver85.h>
//#include <nRF24L0185.h>
//#include <SPI85.h>

/*    **ATtiny25/45/85 Pin map with CE_PIN 3 and CSN_PIN 4**
      nRF24L01 CE oins is tied high and pin3 is used as the trigger output.

                                   +-\/-+
                     NC      PB5  1|o   |8  Vcc --- nRF24L01  VCC, pin2 --- LED --- 5V
      nRF24L01  CE, pin3 --- PB3  2|    |7  PB2 --- nRF24L01  SCK, pin5
      nRF24L01 CSN, pin4 --- PB4  3|    |6  PB1 --- nRF24L01 MOSI, pin6
      nRF24L01 GND, pin1 --- GND  4|    |5  PB0 --- nRF24L01 MISO, pin7
                                   +----+
*/
*    **Trinket 3V Pin map with CE_PIN 3 and CSN_PIN 4 **
* @code
*                                 + -\ / - +
*                   NC      PB5  1 | o   | 8  Vcc -- - nRF24L01  VCC, pin2 -- - LED -- - 5V
*    nRF24L01  CE, pin3 -- - PB3  2 |    | 7  PB2 -- - nRF24L01  SCK, pin5
*    nRF24L01 CSN, pin4 -- - PB4  3 |    | 6  PB1 -- - nRF24L01 MOSI, pin6
*    nRF24L01 GND, pin1 -- - GND  4 |    | 5  PB0 -- - nRF24L01 MISO, pin7
*                                 +---- +

// (Create an instance of a radio, specifying the CE and CS pins. )
RF24 myRadio (3, 4); // "myRadio" is the identifier you will use in following methods
/*-----( Declare Variables )-----*/
byte addresses[][6] = {"1Node"}; // Create address for 1 pipe.
int dataReceived;  // Data that will be received from the transmitter
int flashPin = 3;
int flashValue = 0;
long flashStartMicros = micros();

void setup()
{
  pinMode (flashPin, OUTPUT);

  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MIN);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power

  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  myRadio.startListening();

  digitalWrite(flashPin, 0);
}//--(end setup )---

void loop()
{
  if ( myRadio.available()) // Check for incoming data from transmitter
  {
    flashStartMicros = micros();
    while (myRadio.available())  // While there is data ready
    {
      myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload (You must have defined that already!)
    }
    if (dataReceived == 8) {
      flashValue = 1;
      digitalWrite(flashPin, flashValue);
    }
  }
  if ( micros() - flashStartMicros > 1500) {
    flashValue = 0;
    digitalWrite(flashPin, flashValue);
  } //END Radio available
}//--(end main loop )---

```

Simply - I send a character, received it and set trigger high. Then time out and set it low. There is only one statement setting pin 3 (`flashPin`) low.

I have spent 2 days trying to find the difference.

# Answer
> 0 votes
My debugging effort was in an endless DO loop because I was trying to see why the ATtiny was not acting on the received data like the Trinket. Thanks to some simple questions from #jsotola I looked at what the Trinket signals looked like to compare. Turns out, my transmitted was broken and that both receivers were dealing with the same garbage. Now I do not have a difference between the 2 receivers and I can go back and make the TX do what I need it to do. “When you eliminate the impossible, whatever remains, however improbable, must be the truth.”

---
Tags: adafruit, nrf24l01+, attiny85
---


title: Problems bluetoothing float values

text:
# Question
Title: Problems bluetoothing float values
I have two Arduino Unos, one of which is connected to a HC-05 bluetooth device and a temperature reader, the other has just a HC-05 bluetooth and is expected to output temperature readings in serial monitor.

This is first device:

```
#include <SoftwareSerial.h>
const int tempPin = 1;
SoftwareSerial BTSerial(10, 11);

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

}

void loop() {
int value = analogRead(tempPin);
float mv = value * (3300/1024);
float x = (mv - 500)/100;
Serial.print("Temperature is: ");
Serial.println(x);
BTSerial.print(x);
delay(5000);
}

```

This is the second device:

```
#include<SoftwareSerial.h>
void setup() {
BTSerial.begin(38400);
Serial.begin(9600);
}
void loop() {
if(BTSerial.available())
{
float x = BTSerial.read();
Serial.println(x);
}
}

```

The first program is able to give me accurate readings (around (15 degress Celsius) but the second program gives readings between 40 - 60 \*C (as well as that it spits out 5 different readings between delay intervals). Why is that? How should I change this so both devices output the same readings

# Answer
> 2 votes
Two problems:

Your first program sends an ASCII representation of the temperature with no line ending. So after a few readings you get something like:

```
20.2520.2520.5021.0021.25

```

etc. You need some line endings in there to break them up.

Secondly your second program reads one byte at a time as a number (float) and prints it - so would get something like:

```
50.00
48.00
46.00
50.00
53.00
50.00
48.00
... etc ...

```

You need to, in association with sending line endings in your first program, read each character of a single line either into a string and then parse that as a float (with `dtostrf()`) or directly into a float using a state machine.

You can read more about working with serial here and working with a number reading state machine here.

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


title: Missing arduino bootloader problem?

text:
# Question
Title: Missing arduino bootloader problem?
I have a arduino clone that is not being assigned a /dev/tty by Debian Stretch (Stable). It does have the ch340g chip. I have tried the driver from the manufactures site with no joy. Would the lack of a bootloader cause this problem?

Thanks.

# Answer
> 2 votes
No. On Arduino-style boards which use distinct chips for the main processor (ATmega328p) and Serial interface (CH34x/ATmega8u2/ATmega16u2/FT2232 etc) the presence or absence of a bootloader on the main processor has no bearing on the recognition of a USB/Virtual Serial device by a host.

However on ATmega32u4 and some ARM-based boards it can.

Since you are describing a classic board with distinct chips, whatever your actual issue is, it is something else.

---
Tags: bootloader
---


# Question
Title: PIR with Arduino - detects only first motion
The following is an Arduino sketch for 3 PIR sensors. Two PIRs can activate 1 buzzer and show status in an LCD. The third PIR activates a relay.

The problem is only the first motion gets detected and the "L" indicator stays on. After that there is no activity.

The same Arduino Uno board is working fine with other sketches. PIR sensors are also working. The sketch seems to be working on simulation as well.

Link to simulation

"L" LED is the LED close to the 13th pin. above the TX,RX LEDs. The PIRs are set for the lowest time, sensitivity medium. The issue exists even without connecting the PIRs/relay. There is one beep from the buzzer, it happens 4-5 seconds after turning the board on, with that the "L" led goes on - forever.

The LCD also has an issue, it shows filled blocks on the first row, nothing else.

I tried connecting only one PIR and 1 buzzer to the board.

What is wrong?

```
#include <LiquidCrystal.h>

unsigned long time;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
int pir1Pin =9;
int pir2Pin =10;
int pir3Pin =11;
int buzzerPin =8;
int relayPin = 12;
int backlightPin = 13;
long previousMillis = 0;
long interval = 1000;

void setup() {
  lcd.begin(16, 2);
  pinMode(pir1Pin, INPUT);
  pinMode(pir2Pin, INPUT);
  pinMode(pir3Pin, INPUT);
  pinMode(relayPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(backlightPin, OUTPUT);
  digitalWrite(relayPin,HIGH);
  delay(1000);
  digitalWrite(relayPin,LOW);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(pir1Pin)== HIGH) {
    digitalWrite(backlightPin,HIGH);
    lcd.setCursor(0, 0);
    lcd.print("Pir 1 Active");
    beep();
  } else {
    lcd.setCursor(0, 0);
    lcd.print("Pir 1 is off");
    digitalWrite(backlightPin,LOW);
  }
   if(digitalRead(pir2Pin)== HIGH) {
     digitalWrite(backlightPin,HIGH);
     lcd.setCursor(0, 1);
     lcd.print("Pir 2 Active ");
     beep();
   } else {
     lcd.setCursor(0, 1);
     lcd.print("Pir 2 is off");
     digitalWrite(backlightPin,LOW);
  }
  if(digitalRead(pir3Pin)== HIGH) {
     while(digitalRead(pir3Pin)==HIGH) {
       digitalWrite(relayPin,HIGH);
     }
   } else {
     digitalWrite(relayPin,LOW);
   }
 }

void beep() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    for (int i=0; i<500; i++) {
      digitalWrite(buzzerPin, HIGH);
      delayMicroseconds(500);
      digitalWrite(buzzerPin, LOW);
      delayMicroseconds(500);
    }
  }
}

```

# Answer
Make sure that all the PIR sensors and the LCD display are effectively powered. this might fix your problem.

i'm saying this because the same thing seems to work in the simulation. Powering 3 PIR sensors and a LCD display with a USB is not a good idea.
> 1 votes

# Answer
I don't really know what the problem is with your setup, but here are a few suggestions to try:

1. Several PIR guides (,,,) recommend using a pullup resistor on the open-collector signal pin of some models of PIR sensors. You could also (or instead) say `pinMode(pir1Pin, INPUT_PULLUP);` (and so forth) rather than `pinMode(pir1Pin, INPUT);`. Note, for each PIR, attach a voltmeter to its output (or, to its input on the Uno). Trigger the PIR and verify that the signal acts as you expect it to.
2. Use a different pin number than 13 for your `backlightPin`. The Uno's digital pin 13 corresponds to the on-board LED (presumably the LED your question calls 'L'). If you use separate pins for the backlight and the on-board LED, you can then use the on-board LED as a debugging aid.
3. Your code arrangement `if(digitalRead(pir1Pin)== HIGH){ ...` `lcd.print(...); ... beep(); }else { ...` `lcd.print(...); ... }` (and similarly for `pir2Pin`) will print stuff to the LCD on every pass through `loop()`, that is, every few milliseconds. It might make sense to have variables that record previous readings on those pins, and only update the LCD when a pin reading changes. (Without other changes, this change would lead to only one beep when the PIR triggers, rather than a train of beeps at one-second intervals. In this case if you want a train of beeps, you would need a beep-status variable.)
> 1 votes

# Answer
To supplement, use an I2C backpack for the LCD and fmalpartida's newLiquidCrystal library. Set the jumper to autoreset the trigger.

Wire VCC to 5V

Wire S+ (outputs 3V3 when tripped) to D2 (INT0) - or whatever you use...

Wire GND to GND
> 0 votes

# Answer
This is not a complete answer because I couldn't figure out why the beep only happens once. But if I'm not mistaken, if your code would work as you intend the first motion gets detected and the code jumps to beep. There it will be stuck for 500x(500+500) ms. You would never get results for pir2 or pir3 if the setup is in a way that you can't trigger pir2 independently from the others.

Therefore:

Use pulldown resistors as mentioned by others.

Read all the pir states and save them, and afterwards run the LCD code and then the beep code.

Your system will be unresponsive for as long as the beep code runs.
> 0 votes

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