# Question
Title: How to send data from an Arduino to PC, without using the Serial Monitor?
I have an analog sensor which I want to send data from my Arduino Certified Intel Edison to PC, without using a Serial Monitor and preferably putting the data into a text file.

# Answer
> 1 votes
I believe you are looking for something like the Telemetry library.

*Full disclaismer : I am the author*

It allows you to send string, numbers, arrays, sparse arrays through the serial port for instance. Each sent data has a label, called topic, that is used to identify it.

The Pytelemety command line interface then allows you to connect to the serial port, plot received data in real time, write parameters to reconfigure the arduino from the computer, etc.

Example of arduino code thats send an incrementing counter

```
#include <Telemetry.h>

Telemetry TM;
int8_t counter;

void setup() {
  TM.begin(115200);
  counter = 0;
}

void loop() {
  TM.pub_i8("count",counter);
  counter++;
  delay(10);
}

```

Overview of the CLI (Command-Line Interface)

Overview of a graph (not produced by the arduino program above)

Output to file is not implemented yet, although all received data is logged to a file (but this log also contains system information). However, this is an interesting feature, quite straightforward to implement, that I might add in coming days if you are interested.

Central documentation is available here.

# Answer
> 0 votes
There are a couple of ways you can communicate between a "Arduino' and a "PC"\*.

**1)Serial communication.**

A serial port on your system is created and a program that reads and writes to the serial port is used as communication.
A program that does this is the "serial monitor" which comes in many flavours.
In linux dumping serial monitor incoming data to a file is as easy as:

```
cat /dev/ttyS0> myFile

```

**2)Bluetooth (LE)**
Bluetooth is a low energy consuming protocol that is commonly used for communication between a PC and a "device". The LE uses even less energy. I'm not aware of any "official Arduino" boards that contain the hardware for Bluetooth on board.

**3) Network**
Today network equals to WIFI of tcpip. These methods allow for huge distances between the pc and the device.

Of these methods the serial communication over USB is the best know because -in Arduino world- this method is most commonly used to upload the "sketch" to the "Arduino". As such all hardware is commonly available.

\*I put quotes around Arduino and PC because in perspective of this answer both arduino and PC are to be interpreted as a device containing a cpu.

# Answer
> 0 votes
I know, I'm late, but I recommend, using python, as I most always do. The `serial` module is part of the basic python installation

```
import serial

S = serial.Serial('/dev/tty/USB0', 115200, timeout=1)

S.write("Hello")
print S.readline()

```

Should echo `Hello`, if the arduino sketch replies all incoming data.

Very handy in combination with `ipython`, where one can interactively poke around with the serial connection object.

---
Tags: serial, programming, edison
---


# Question
Title: Fastest way to test if two integers differ by 4 or equal to each other
I'm searching for the fastest way to test if two integers are equal or differ by 4. The integers can be positive, negative and equal to zero. They are between -1000 and 1000 and are exclusively multiples of 4.

The simplest approach to test this should be this:

```
if(x == y || x - y == 4 || x - y == -4)
{
     //do something...
}

```

But since I want to do this 4 times inside of a interrupt sub routine I wanted to know if there is a faster way to do this.

# Answer
If you need to do the same comparison 4 times you can just put the result into a boolean variable.

```
boolean b = (x == y || x - y == 4 || x - y == -4)

if( b )
{
     //do something...
}

```

If you are talking about optimizing the actual code, I shouldn't worry about it. The compiler is already pretty good at this. Here is the assembler code for it.

```
void test(int x, int y)
{
    if(x == y || x - y == 4 || x - y == -4)
  a8:   86 17           cp  r24, r22
  aa:   97 07           cpc r25, r23
  ac:   39 f0           breq    .+14        ; 0xbc <_Z4testii+0x14>
  ae:   86 1b           sub r24, r22
  b0:   97 0b           sbc r25, r23
  b2:   84 30           cpi r24, 0x04   ; 4
  b4:   91 05           cpc r25, r1
  b6:   11 f0           breq    .+4         ; 0xbc <_Z4testii+0x14>
  b8:   04 96           adiw    r24, 0x04   ; 4
  ba:   09 f4           brne    .+2         ; 0xbe <_Z4testii+0x16>
    {
        asm ("wdr");
  bc:   a8 95           wdr
  be:   08 95           ret

```

first it compare the two values x and y. Then is subtract y from x and compares it with 4. After that it gets the subtracted value from the previous step; adds 4; and check if it is `0`.

**EDIT**

As to Dave X's suggestion; using `if(abs(x-y)<=4)`

```
void test(int x, int y)
{
    if(abs(x-y)<=4)
  a8:   86 1b           sub r24, r22
  aa:   97 0b           sbc r25, r23
  ac:   04 96           adiw    r24, 0x04   ; 4
  ae:   09 97           sbiw    r24, 0x09   ; 9
  b0:   08 f4           brcc    .+2         ; 0xb4 <_Z4testii+0xc>
    {
         asm("wdr");
  b2:   a8 95           wdr
  b4:   08 95           ret

```

So half the number of instructions needed. But as Paul said, this might not the fastest. This code always takes 5 instructions, while the previous code will only take 3 instructions if `x==y`. So if 90% of the time x==y, the previous code will be faster 90% of the time.

As to the assembler code, you can see how clever the compiler is. It first subtracts y from x. Then it adds 4. If `-4 <= x-y < 0` the carry bit is set. Then it subtracts 9 (so it's like `(x-y)-5` because of the previous `+4`). If `0<= x-y <= 4` the carry bit is set. It then check if the carry bits is set by either of the last to instructions. Pretty clever.
> 3 votes

# Answer
> test if two integers are equal or differ by 4

And

> are exclusively multiples of 4.

That would mean that when a=20, b should be 16, 20 or 24. (But can't be 17, 18, 19, 21, 22 or 23)

But you should check the most unlikely statement first. If it's likely to be well above x+4, check that first, if it's false, it'll just stop.

Ultimately you only have to check if it's less than x=y+4 or higher as x=y-4, this automatically includes x=y. So checking if it's the same (which might be unlikely, might be redundant. Unless there is a very high chance of that being true.
> 2 votes

---
Tags: arduino-uno, c
---


# Question
Title: How to Serial read two consecutive chars sent by computer to Arduino?
My program reads the input and plays the appropriate note for 500 milliseconds. If I type in 'a', tone(8, 440, 500) will be called. I now want to add different note lengths so that in the future, I can play songs by sending code to Arduino. I was thinking that if 'a' is typed in, the program checks the next character. If it's a 1, it's a whole note. If it's a 2, it's a half note. My code doesn't work. What is wrong with it?

```
    if(Serial.available()>0){
    char character=Serial.read();
    if(character=='a'){
    char leng=Serial.read();
    if(leng=='1'){
    tone(8, 440, 1000);
    delay(1000);
    }
    else if(leng=='2'){
    tone(8, 440, 500);
    delay(500);
    }

    }
    }

```

# Answer
Presuming that code is the interior of `loop()`, your Arduino will spin until a character arrives, that is, until `Serial.available()>0` becomes true.

It then reads the character with `Serial.read()` and if it's an `'a'` immediately does another `Serial.read()`. In general, some delay occurs between characters arriving via a serial interface. Whenever the serial buffer is empty, an immediate `Serial.read()` will return -1 instead of an ASCII character.

To fix this problem, test for availability of a character before doing the second read. For example, you could add

```
while (!Serial.available()){}

```

before the read, to delay until a character is available.
> 3 votes

---
Tags: serial, sound, piezo
---


title: Speed sensors for sport

text:
# Question
Title: Speed sensors for sport
Fair warning: I'm a newbie when it comes to Arduino, so if I'm not too great at describing things, let me know so I can learn!

I have recently built a fairly accurate laser timer to time sprinters through a section of a soccer pitch, giving a nice reading of their average speed through the zone.

The limitation is that we would love to be able to see their speed as a progressive measurement throughout the sprint.

My problem? I have NO idea where to start. Google has so far come up empty...

All I have is the following link, Best of the 2015 NHL All-Star Skills Competition, illustrating the sort of thing we would like to accomplish. The bit in question starts at around 0:35 when they are talking about sensors in the players' jerseys.

Any one able to point me in the right direction?

# Answer
Kinovea is good but this would be post processing not live. You need record video and then you can track each runner on time. Another one is Typhon program but it involves programming and calibrating (then you can track live).
> 1 votes

# Answer
You can use photo cells. Just get some light sensors and direct lasers on to them. I got 100 lasers for £10 from eBay. You don't need to connect them to any controller, just connect them to a power supply to provide light for sensors. The sensors I got from eBay were, I think, 100 for about £5 or £10, then you can use an Arduino Mega and connect sensors to it.

When you cross the sensor, light will trigger and send a signal to Excel (you can use parallax program) and use Arduino code for interrupts when the sensor is triggered, you will get data to Excel (time and triggered sensor). If you call sensors like: first one 1 millisecond, 2 milliseconds, and so on, so you know what distance and what speed. But I think would be tricky if you need to measure a few guys simultaneously. It should work for single one though.
> 1 votes

# Answer
I would use an ultrasonic sensor pointed at them it will give you a list of distanced at the rate that the sensor collects information (e.g. 5Hz) this could be used to plot a graph of distance over time then a graph of speed over time, then acceleration over time ect.
> 0 votes

# Answer
An option would be to use a GPS module which would give you actual speed accurately, this data can be logged to EEPROM or SD and downloaded later or it can be sent wirelessly to a base station.

There is a wearable GPS module from adafruit, there are a few tutorials on getting started with it. You can the make a jacket or something light that can go onto the sprinters with the system attached.

---

You could use an IMU(Inertial measurement unit), this uses an Accelerometer, Gyro and Magnetometer. There is an article on using IMUs for measuring velocity of an object with basic modules and not using the expensive systems.

This article by CH Robotics covers a starting point, also googling this should give a whole load more of links. As the article says:

> It depends entirely on how much accuracy is needed. In general, accelerometer-based position and velocity estimates from low-cost sensors ... are very poor and are simply unusable.
> 0 votes

# Answer
You will likely need to buy a relativly high quality GPS for each runner. Alternatly, if you could get a camera mounted so it could see large portions on track from a good angle it could probably perform pretty well with the right optical recoginition code.

IMU's are not going to be capable of tracking a runners velocity. Even constrained to linear motion the position and velocity measurements from integrating a consumer accelerometer become garbage in a few seconds because of accumulated error. Once you add the fact that the sensor will not be level all the time and your angle estimation is at best within 1 degree, I'd estimate the velocity and position of a runner recorded by a normal 9-dof IMU would be irrelevent after at most 5 seconds.

Have a look at the table on this page for a detailed analysis of orientation based errors:http://www.chrobotics.com/library/accel-position-velocity
> 0 votes

# Answer
Your best bet would be to use a module of Gyro, Accelerometer and Magnetometer much like MPU-9150. These devices communicate using I2C and you can log in data about the direction and the change in direction as well as acceleration. Using this data you can easily find out the speed in a particular direction and even overall data like the average speed, distance travelled, etc.

Another idea is using the accelerometer to measure a jerk.A jerk can be taken as a footstep and using appropriate calculations you can find out how much a person has moved throughout the sprint.

You can use ultrasonic sensors too which would tell you the position of the sprinter from a point but they have their disadvantages like small pressure changes due to air will affect the readings and you won't get accurate reading.
> -1 votes

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


title: "Return" Code Not Working

text:
# Question
Title: "Return" Code Not Working
I'm trying to experiment with a "return" function. Yet each time I try to run my program, there happens to be an error, like "expected declaration before '}' token."

Can someone explain the basics of a return function, and look at my code below to possibly see what the problem could be?

```
{
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;
else{

return 0;
 }
}

```

# Answer
> 3 votes
It has nothing to do with the retun statements. You have to close each { with a }. you are missing one.

```
   {
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;}
else{

return 0;
 }
}

```

# Answer
> 3 votes
That piece of "code" is, I am afraid to say, complete gibberish.

Passed through Artistic Style to reformat it ends up with:

```
{
    int index;

    pinMode(10, INPUT); //button input

    int checkInput();

    if (digitalRead(10) == 0) {
        return 1;
        else {
            return 0;
        }
    }

```

Starting from the top of the program the errors are:

1. You have a bracket hanging at the front of the snippet for some reason
2. `int checkInput();` is a function prototype (forward declaration) and doesn't do anything other than tell the compiler that you will define this function somewhere else in your sketch.
3. You are lacking the balancing bracket for the first portion of your `if` statement, so your `else { return 0; }` never runs.
4. There is no balancing bracket for the strange one by itself at the start of the snippet.

In short, I have a feeling you need to learn the basics of C syntax.

---
Tags: arduino-uno, programming, code-review
---


# Question
Title: Potentiometer with switch wiring question. Not reading correctly
I have a potentiometer with switch, that seems to be working a little wonky (Keep in mind I have tried this with a few different pots and they all behave the same way which leads me to believe I am wiring them wrong).

I can easily hookup the potentiometer and it's three terminals on the side, 1 being ground, 2 being output, 3 being input power. I can monitor it's value on a serial port with Arduino. However when I try and test the switch, which are two terminals on the bottom of the pot. I get an on signal when the pot is on, but when it is clicked off I get a random on/off signal. As in it reads that it is sort of on but never truly reads off.

Right now I am simply giving it 5v from the Arduino to both the switch and the third terminal. Should I be giving the switch power via a capacitor? Not sure, have not tried that yet but that may smooth out my readings.

Any suggestions?

# Answer
> 3 votes
From your description of switch wiring, it sounds like you have one of the switch leads attached to +5 V and the other switch lead to an input.

As noted in comments and answers to “Why all unset pins of my Arduino Uno are outputting 2 volts?”, such an input will read high when the switch is closed, and will read randomly when it is open, because an input is a high-impedance device that can accumulate charge:

> ... input impedance typically can be taken as 100 MΩ for design purposes. ... Each pin has a few pF (5-10?) of capacitance ... which in general is small compared to stray capacitances of attached wiring.
>
> When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin. You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the \[voltage\] you are seeing.

The easy fix for the problem is to attach one switch-lead to ground, one to an input pin, and initialize the pin with `INPUT_PULLUP` pinmode instead of just `INPUT`.

---
Tags: potentiometer
---


# Question
Title: Can the servo pulse width range be changed?
I recently found that standard servos only rotate 90deg total rotation for a pulse width range of 1-2 usec. To rotate 180deg total rotation they need a .5-2.5 usec pulse range. The arduino is programmed to only output the 1-2 usec range for 0-180 deg rotation. Is there a way to make the arduino output the .5-2.5 usec pulse range to get full 180deg rotation?

Thanks

# Answer
The Servo Attach method has two forms,

```
servo.attach(pin)
servo.attach(pin, min, max)

```

In the latter form, you can specify values for the min and max microseconds that `servo.write()` will use to represent 0° and 180° respectively.

Note, default values are 544 μs and 2400 μs, which is not so different than the range you say you want, so perhaps some other problem is afflicting your setup.

Also, as explained in my answer to question “Change Servo Speed With RedBearLabs BLE Shield”, you can issue `servo.write(value)` calls with value in microseconds instead of in degrees, which may allow more precise control.
> 2 votes

---
Tags: servo
---


# Question
Title: What is the equivalent of this old SPI code using the current SPI library?
I see some old library code that initializes SPI this way:

```
    SPI.begin();
    SPI.setClockDivider(2);

```

It does not use `beginTransaction`/`endTransaction` blocks, and `setClockDivider` is now deprecated. The current way to use SPI is to use transaction blocks where you pass the settings in.

What is the equivalent to this code using transaction blocks? Also, since the other settings (max speed, data order, data mode) aren't specified in the above code, there must be defaults. What are these defaults?

# Answer
The default is:

* Mode 0
* MSBFIRST

Not sure on the default speed. But:

`setClockDivider()` sets a speed relative to the system clock. So it's impossible to say what speed that will be since it'll be different on 8MHz boards compared to 16MHz.

`setClockDivider(2)` would be the same as using F\_CPU/2 as a speed.
> 0 votes

# Answer
I have example code here.

The code is:

```
#if SPI_HAS_TRANSACTION
  SPI.usingInterrupt (0);  // I am using external interrupt 0
  SPI.usingInterrupt (1);  // I am also using external interrupt 1
  SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock
#else
  SPI.setClockDivider(SPI_CLOCK_DIV8);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
#endif // SPI_HAS_TRANSACTION

digitalWrite (SS, LOW);        // assert Slave Select
byte foo = SPI.transfer (42);  // do a transfer
digitalWrite (SS, HIGH);       // de-assert Slave Select

#if SPI_HAS_TRANSACTION
  SPI.endTransaction ();   // allow external interrupts to fire now
#endif // SPI_HAS_TRANSACTION

```

The default setting for SPI is to use the system clock speed divided by four.
> 0 votes

---
Tags: spi
---


# Question
Title: Issues with connecting XBee to Arduino Uno R3
I have an Arduino Uno R3, Wireless Proto Shield and a XBee XB24-AWI-001 all hooked together. I'm using X-CTU software to access the XBee and change the properties of it. I did a little research and found out that if I want to access the XBee, I have to connect the GND to the RST pin (on the Proto Shield) or hold the RESET button on the board. This method works and when I do that, I can find the XBee on X-CTU.

The question is - why do I have to do that? I'm probably wrong, but as far as I understand, if I have my Arduino connected to the computer, I'm accessing the ATmega microprocessor and that's the reason I can't access the XBee, but when I do the reset, I'm constantly resetting the microcontroller and that's the reason why I can access the XBee? Hopefully someone can explain this...

The link where I found the information about resetting (or removing) the ATmega microproccesor, Using Arduino to Connect Xbee Serial to Computer.

# Answer
I am slightly surprised that you can actually talk to the XBee from your PC over USB with the XBee in the shield. XBee shields are generally designed for the XBee to be used by the Arduino *only*. The fact that you can actually talk to the XBee from the PC using X\_CTU with the XBee in the Arduino shield, by holding down reset, seems to either be a quirk or a *feature* of the shield1.

Generally to use X-CTU to talk to the XBee, one would use an XBee explorer board or a Development board. One would configure the XBee completely in the Explorer dongle and then transfer the XBee to the shield for the Arduino to use it.

See the thread on the Digi forums, xbee s1 xctu arduino:

> The shield is not design for writing and reading firmware to and from the XBee module. It is only designed for basic two way communications. If you want to read or write firmware to the module, you need to use a board that is designed for it such as the XBIB boards from Digi.

See also Can an XBee be programmed with an XBee Shield.

However, hopefully someone with more knowledge of the internals of an Uno and XBee shield than I, could explain the actual electrical reasoning behind this issue. I have attempted to explain it below in the footnote.

---

1 Having said all of that, looking at some of my XBee shields, a couple have a microswitch, that enables the XBee to talk to *either* the Arduino *or* the USB, but *not both* at the same time. So, I guess that the need to hold the reset on your shield is because you do not have such a microswitch.

So the reason being, is that the Arduino and the USB can not talk to the XBee at the same time, as there would be conflict on the Rx and Tx serial lines - see this thread, UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal which hints at the same thing. Two comments of note from that thread are:

> It would be a lot simpler to debug the issue if you put the switch in the other position, and used SoftwareSerial to talk to the XBee and Serial to talk to the PC. Using one port to talk to two devices IS going to frustrate you no end.

and

> Note that a communication application connected to an arduino that opens a com port, sends data, then closes may cause the arduino to reset.

As a (really wild) guess, I would imagine that the **USB-to-TTL IC**'s DTR line, or equivalent (?), is \[logically\] tied to the Arduino's RST line, so that if the PC tries to communicate to the XBee, it ends up resetting it, rather than signalling to the XBee that it is ready to communicate.

Note: The **USB-to-TTL IC** could be a FTDI, ATmega 4U2/8U2/16U2 or an FTDI clone, depending on the variety of Uno that you possess.

### Addendum

I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of USB-TTL interface devices on OS X. That explorer, XBee USB Adapter Bluetooth Bee FT232RL USB to Serial Port Module for PC Arduino, is good value for money and compatible with WinTel, LinTel and OS X machines:
> 0 votes

---
Tags: arduino-uno, xbee
---


# Question
Title: Using two ultrasonic sensors for counting cars when they enter to a garage
I want to use two ultrasonic sensors for counting incoming cars to a garage. What I want is: When both sensors detect the object then the counter should increase.

Can anyone help me and give me an example?

# Answer
> 2 votes
If you have two sensors, you use analogRead.

```
int sensor1 = A0;
int sensor2 = A1;
int distance = 50; // or whatever you want here
bool car_passing = false;

void setup(){
    int counter = 0;
}

void loop(){
    if(analogRead(sensor1) < distance &&
       analogRead(sensor2) < distance &&
       !car_passing)
    {
        car_passing = true;
        counter++;
    }

    if(analogRead(sensor1) > distance){
        car_passing = false;
    }
}

```

To prevent the counter keep counting while the car is passing by, we need to make a boolean, so the counter does not wait for count again, before the car has passed.

---
Tags: arduino-mega, sensors
---


# Question
Title: Arduino join multiple strings and numbers and then seperate them
OK, I'm working on a remote controlled robot. Both the robot and the remote use Arduino with a Bluetooth shield. The Bluetooth is working and I need to send something similar to this over Bluetooth:

`X:1026,Y:1026,Button:1`

There may be more buttons added and `X,Y` can be between `1026` and `0`. How can I build that string from:

`xPosition = 1026;
 yPosition = 1026;
 buttonState = 0;`

I also need to be able to separate that string back into variables on the 2nd Arduino.

EDIT: I have seen other questions similar to this but they involved Serial. I am using Bluetooth.

EDIT AGAIN: I am sending the data over Bluetooth with the `BlueToothSerial.print` command from the `SoftwareSerial.h` library. (`BlueToothSerial` is `SoftwareSerial BlueToothSerial(RxD,TxD);`)

# Answer
> 0 votes
To make the string you can:

```
char outstring[30];
sprintf(outstring, "X:%d,Y:%d,Button:%d", xPosition, yPosition, buttonState);

```

Be sure to make the `outstring` big enough to store it all.

That is, of course, if you actually *need* to have the whole thing in one string all the time. You haven't said how you are sending it (yes, I know, bluetooth, but there is bluetooth and there is bluetooth, and there are different ways of it working.)

Splitting a string like that can be done with `strtok()` then looking for the location of the colon in each returned token. Or, depending on how the string data actually arrives, could be parsed on a character-by-character basis, which would be better. Again, because you haven't told us how the data is actually being transferred it's impossible to elaborate on that.

---
Tags: arduino-uno, programming, string, variables
---


# Question
Title: How to read long value sent by Arduino in C
I have a quick question regarding this code below in Arduino:

```
Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.print(5);
Serial.print("0");
Serial.print(1);
Serial.print("0");
Serial.println(5);

```

In C code, currently I'm receiving the message using this method below:

```
int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
{
    char b[1];  // read expects an array, so we give it a 1-byte array
    int i=0;
    do {
        int n = read(fd, b, 1);  // read a char at a time
        if( n==-1) return -1;    // couldn't read
        if( n==0 ) {
            usleep( 1 * 1000 );  // wait 1 msec try again
            timeout--;
            if( timeout==0 ) return -2;
            continue;
        }
        buf[i] = b[0];
        i++;
    } while( b[0] != until && i+1 < buf_max && timeout>0 );

    buf[i] = 0;  // null terminate the string
    return 0;
}

```

In C i defined:

```
char message[13];
uint32_t num;
char until = '\n';

serialport_read_until(fd, message, newLine, sizeof message, 20000);
// the 20000 is timeout in millisec
// this method stores the data in serial buffer into message array

printf("message is %d\n", num);

```

I am expecting a raw value of **0501050105** first. Then I convert this raw string into **501050105** using:

```
sscanf(message, "%d", &num);

```

Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

In addition, when i use serialport\_read\_until() method above, even though i specify the char until as '\n', the method terminates after reading '\r' (leaving the \n in the serial buffer), and the '\n' is only captured in the next method call.

**Q1:** Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

**Q2:** Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

Thank you very much.

# Answer
> 0 votes
> char b\[1\]; // read expects an array, so we give it a 1-byte array

No, it expects a *pointer* to a destination to store the data. You don't need a 1-entry array - you can simplify your code with:

```
char b;
...
int n = read(fd, &b, 1);  // read a char at a time
...
buf[i] = b;
... etc ...

```

> Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

C has the function `strtoul()` which is far more efficient that sscanf.

```
uint32_t val = strtoul(buf, NULL, 10);

```

The `10` is the base to convert from, so you could convert hexadecimal (base 16), octal (base 8), etc using it.

> Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

You're defining the variable `until` to contain `\n`, yet passing the variable `newLine` to your function. Maybe that has something to do with it?

> Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

You can send a 32-bit value using just 4 bytes. However it's not reliable without implementing a whole protocol around those 4 bytes which, for just 4 bytes, is a bit of a waste. Simplest just to stick to ASCII encoding your data.

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


title: LEDs instruction code does not loop

text:
# Question
Title: LEDs instruction code does not loop
I am using Neopixel Library and a Trinket Pro 5V Microcontroller to chase first three LEDs on a strip and then burst the last 2 (could be modified based on the number of LEDs). The LEDs chase only once. See the code below. I am not sure why, even though the logic is inside the loop function, it only executes once. Any suggestions?

```
#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6

// How many NeoPixels are attached to the Arduino? How many Neopixels do you want to chase (starting from the first in address 0. How many do you want to burst at the end?
#define NUMPIXELS      5
#define NUMPIXELSCHASE 3
#define NUMPIXELSBURST 2

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
  // End of trinket special code

  pixels.begin(); // This initializes the NeoPixel library.
  clearLEDs();
  pixels.show();
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
  for(int i=0;i<NUMPIXELSCHASE;i++){

   pixels.setPixelColor(i, INDIGO);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay (200);
  }

  for(int i=NUMPIXELS-NUMPIXELSBURST;i<NUMPIXELS;i++){

   pixels.setPixelColor(i, AQUA);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay(0);
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<NUMPIXELS; i++)
  {
    pixels.setPixelColor(i, 0);
  }
}

```

Thank you.

# Answer
> 1 votes
Your 1st pixel should go indigo & stay there, & the other 2 very briefly show Aqua before going back to Indigo. Try a longer delay than 0 at the end, and then clear them down for the next loop.

---
Tags: arduino-uno, programming, adafruit, rgb-led, neopixel
---


# Question
Title: Is this function subject to memory fragmentation?
I'm trying to understand if the following bit of code is subject to memory fragmentation.

Let's say I incrementally build a string within a function and I don't know how large the string should be.

```
String f() {
    String s = String("");
    s += "a"; // ...
    s += "bc"; // ...
    return s;
}

```

The `String` object does dynamic memory allocation internally, but `s` is on the stack, so once the function returns, the `s` object presumably deallocates and dynamically allocated memory is freed.

Before this happens, the `String` object to be returned must be copied from `s`. Since `String` objects hold internal data in dynamically allocated buffers, this means that the `s` internal buffer is allocated, then the return object internal buffer is allocated, then the `s` internal buffer is deallocated.

The return object internal buffer allocation is sandwiched between the `s` object alloc and dealloc.

To me, this implies that this will cause memory fragmentation. Am I reading this properly, or is this not the case? If so, does this also imply that functions like `Serial.readString` are also subject to memory fragmentation?

# Answer
> 3 votes
Pretty much every use of the String object can lead to memory fragmentation. Especially concatenating and copying objects.

I cover it here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

You are much better off never using the String class and instead sticking to basic C strings (char arrays).

# Answer
> 1 votes
Memory fragmentation is hard to predict, as it depends on how your different allocation patters interact. This single pattern, *per se*, looks safe. By safe I mean that *if*

1. your heap is not fragmented when you enter this function, and
2. you do no dynamic allocation inside the function other than growing the string,

then the string will be allocated to the top of the heap and grow from there without moving or making holes. You can check this is the case by looking at the address of the string's internal buffer, which is given by the `c_str()` method. It should not change inside the function:

```
String f() {
    String s = String("");
    const char * p = s.c_str();
    s += "a"; // ...
    s += "bc"; // ...
    if (p != s.c_str())
        Serial.println(F("Warning: memory fragmentation."));
    return s;
}

```

---

**Edit**: I wrote this small test program to show the behaviour of the heap when you use string concatenation this way:

```
extern uintptr_t __brkval;

String f() {
    String s("");
    const char * p = s.c_str();
    Serial.print(F("  f(): string buffer @ 0x"));
    Serial.println((uintptr_t) p, 16);
    for (int i = 0; i < random(8) + 1; i++)
        s += random(2) ? "a": "bc";
    if (p != s.c_str())
        Serial.println(F("Warning: memory fragmentation."));
    Serial.print(F("        top of heap at 0x"));
    Serial.println(__brkval, 16);
    return s;
}

void setup() {
    Serial.begin(9600);
    Serial.print(F("***     heap starts at 0x"));
    Serial.println((uintptr_t) __malloc_heap_start, 16);
}

void loop() {
    Serial.print(F("loop(): top of heap at 0x"));
    Serial.println(__brkval, 16);
    String s = f();
    Serial.print(F("  f() returned "));
    Serial.println(s);
    Serial.print(F("        with buffer at 0x"));
    Serial.println((uintptr_t) s.c_str(), 16);
    delay(1000);
}

```

The output of the program is:

```
***     heap starts at 0x1D7
loop(): top of heap at 0x0
  f(): string buffer @ 0x1D9
        top of heap at 0x1DF
  f() returned abcbc
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1DF
  f() returned abcbc
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1DC
  f() returned aa
        with buffer at 0x1D9
loop(): top of heap at 0x1D7
  f(): string buffer @ 0x1D9
        top of heap at 0x1E2
  f() returned aabcabca
        with buffer at 0x1D9
[...]

```

The very first “top of heap at” is bogus because at this point the malloc library has not been initialized. Besides that, you can see here that:

* the heap is always empty (top = bottom) at the beginning of `loop()`
* the string is always allocated at the same place
* the heap size inside `f()` varies depending on the string's length
* the string is not copied when returned to the caller, as the internal buffer is still at the same address.

However, if the statement `String s = f();` is replaced by `String s; s = f();`, then the string is copied when returned to the caller, which doubles the amount of RAM required to handle it. This is presumably because only the first form allows copy elision optimization. (This paragraph was added after reading Nick Gammon's answer, which made me realize the copy elision issue).

Keep in mind that this works so nicely only because there is nothing else doing dynamic allocation in this small program. This usage pattern is safe, but once you start doing dynamic allocation in different parts of the program, it becomes difficult to ensure that the allocation/deallocation pattern is still safe vs. memory fragmentation.

# Answer
> 1 votes
The worst line in your example is this:

```
s += "a"; // ...

```

Any sort of loop that adds one byte to a String is potentially going to fragment memory. First the String class allocates zero bytes for the string, then when you add a byte, it has to allocate one byte, then when you add another byte it has to deallocate (free) that byte and allocate two bytes, and so on.

The allocator *tries* to be efficient, so eventually when you get up to three bytes you will, with luck, actually get the memory previously allocated to the one-byte string followed by the two-byte string.

But if other allocations have occurred (eg. another use of String elsewhere in the program) this might not be possible. Eventually you have lots of small gaps of maybe one or two bytes, with other stuff inbetween. Unless they are adjacent they cannot be recombined into a bigger block. This is your "fragmentation".

---

> When you += "a", it does not free the previously allocated space: it calls realloc() to grow the buffer, and realloc() tries to grow it in place. This works fine, without fragmentation, as long as your buffer is at the top of the heap.

Good point, however if you have multiple String instances, this may not work.

Edgar Bonet is right, however there is certainly the potential, with multiple String instances, for each of them to prevent the others from growing their buffer size neatly. In the example in the question, you will probably find that when `f()` returns, it returns a *copy* of the String allocated on the stack, thus we now have 2 x String instances.

---

While Edgar was writing some test code, so was I. :)

```
#include <memdebug.h>

String foo;

String f() {
  String s = String("");
  s += "a"; // ...
  s += "bc"; // ...
  return s;
}  // end of f

void showMemoryUsage ()
{
  Serial.println (F("---------------"));
  Serial.print (F("Largest block in freelist: "));
  Serial.println (getLargestBlockInFreeList ());
  Serial.print (F("Largest available memory: "));
  Serial.println (getLargestAvailableMemoryBlock ());
  Serial.print (F("Free memory: "));
  Serial.println (getFreeMemory ());
  Serial.print (F("address of foo data = "));
  Serial.println ((int) foo.c_str ());
} // end of showMemoryUsage

void setup()
{
  Serial.begin (115200);
  Serial.println ();
  showMemoryUsage ();
  Serial.println (F("Calling f() ..."));
  foo = f ();
  showMemoryUsage ();
  Serial.println (F("Calling f() ..."));
  foo = f ();
  showMemoryUsage ();
  Serial.print (F("foo = "));
  Serial.println (foo);
}  // end of setup

void loop ()
{
}  // end of loop

```

Memory debug library from http://andybrown.me.uk/wk/2011/01/01/debugging-avr-dynamic-memory-allocation/

Output:

```
---------------
Largest block in freelist: 0
Largest available memory: 1675
Free memory: 1677
address of foo data = 478
Calling f() ...
---------------
Largest block in freelist: 2
Largest available memory: 1669
Free memory: 1675
address of foo data = 482
Calling f() ...
---------------
Largest block in freelist: 2
Largest available memory: 1669
Free memory: 1675
address of foo data = 482
foo = abc

```

The address of the data in `foo` has changed from 478 to 482, so my prediction above was right. The function `f()` made a String, but a second *copy* was returned, hence we have now "lost" 4 bytes in the heap. Well, not lost, but there is a gap.

Calling `f()` a second time did not make the fragmentation worse.

---

BTW, this is unnecessary:

```
  String s = String("");

```

Just write:

```
  String s;

```

You are invoking a second String just to provide something to copy into the first String. Strings start off empty so this is just wasted time.

---
Tags: c++, memory-usage
---


# Question
Title: Why does DHT-library (and others) only allow one object instance?
I came across the problem to handle two DHT22 devices.

I use the Adafruit DHT Sensor library.

Since my Arduino sketch works as a "relay" for Serial commands on a host, I tried to wire up and dynamically instantiate DHT22. With no luck.

I checked the source and found, that the DHT object only gets constructed **before** `setup()` as a constant in the examples, because the library is written that way.

I did a quick hack, which works, but seems ugly to me:

**DHT.cpp**

```
DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
-  _pin = pin;
-  _type = type;
-  #ifdef __AVR
-    _bit = digitalPinToBitMask(pin);
-    _port = digitalPinToPort(pin);
-  #endif
+  //_pin = pin;
+  //_type = type;
+  //#ifdef __AVR
+  //  _bit = digitalPinToBitMask(pin);
+  //  _port = digitalPinToPort(pin);
+  //#endif

...

-void DHT::begin(void) {
+void DHT::begin(uint8_t pin, uint8_t type, uint8_t count) {
+  _pin = pin;
+  _type = type;
+  #ifdef __AVR
+    _bit = digitalPinToBitMask(pin);
+    _port = digitalPinToPort(pin);
+  #endif

```

**DHT.h\***

```
-   void begin(void);
+   void begin(uint8_t pin, uint8_t type, uint8_t count=6);

```

Basically, I moved a few lines from the constructor to the `begin()` method. The whole thing works. I can even rewire & change the data-pin dynamically while the Arduino runs.

Here are my questions:

* Is the hacked away behavior a bug or feature?
* Would my solution be good enough for a pull request to Adafruit? I would clean it up beforehand.

# Answer
There is nothing wrong with the library. It does not allow just one object instance.

What is wrong is your way of using it.

It, and many other libraries, specify the pin numbers and other (under normal usage) static data in the constructor. You want to have two objects then create two objects.

But it seems you want to change that static data. So you need to construct differently. Instead of statically declaring your objects you need to be dynamic. Use new and delete.

```
DHT *myDHT = NULL;

myDHT = new DHT(4,5);
// do something
// change pins
delete myDHT;
myDHT = new DHT(6,7);

```
> 3 votes

# Answer
Changing the pins sounds like a reasonable requirement, and you shouldn't have to delete/new to achieve it.

I would leave the library alone (for backwards compatibility) except to add a `changePins` function which you may choose whether or not to call, to assign new pins to the class structure. (Effectively it would be your rewritten `begin` function with a different name).
> 1 votes

---
Tags: programming, library, adafruit
---


# Question
Title: What happens if I try to draw power from the VIN port while under USB power on an Uno?
I would like to have a shield permanently attached that use the VIN (not 5v) for it's power - the problem comes in when I want to program the arduino (via the USB port), do I need to also have the barrel connector plugged in, or can I just expect the shield to not work (no, it won't be damaged from not getting enough/any power), but have the arduino itself be fine - or am I somehow damaging the power regulator by attempting to use it in reverse?

# Answer
> 3 votes
You do run the risk of damaging the 5V regulator, yes.

Power will attempt to flow from the 5V rail (USB port) through the voltage regulator (backwards) and into the shield to power it.

As your shield doesn't mind being under-powered from 5V while you're programming the Arduino you can add a diode between 5V (anode) and Vin (cathode). This will bypass the regulator when the voltage of the 5V rail is higher than the Vin rail, and your shield will be supplied with about 4.3V (slightly higher for a schottky diode).

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


title: Expected Initializer?

text:
# Question
Title: Expected Initializer?
I keep getting the error "Expected initializer" at different points in my code whenever I try to verify it. Currently, the error exists before "void setup." How can I fix this error and not allow it to happen in the future?

```
int ledPins[] = {9, 8, 7, 6};
int index;
int currentLED

void setup();
  {
  pinMode(Led1Pin, OUTPUT);
  pinMode(Led2Pin, OUTPUT);
  pinMode(Led3Pin, OUTPUT);
  pinMode(Led4Pin, OUTPUT);
  pinMode(Led5Pin, OUTPUT);
  pinMode(ButtonPin, INPUT);

  Serial.begin(9600);

  //Start a new game.

 for(index = 0; index <= 4; index++)
  {
    pinMode(ledPins[index],OUTPUT);
    // ledPins[index] is replaced by the value in the array.
    // For example, ledPins[0] is 2
  }
}

void loop()
{

  oneAfterAnotherNoLoop();  // Light up all the LEDs in turn

}

void oneAfterAnotherNoLoop()
{
  int delayTime = 200; // time (milliseconds) to pause between LEDs
                   // make this smaller for faster switching
  // turn all the LEDs on:
  int Index;

for (Index = 0; Index <=3; Index++) {
  digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
for (Index = 3; Index >= 0; Index--) {
    digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
}

void loop();
{
    // Check if the button is pressed at the right moment

   if (digitalRead(10) == 0)
   {
    if (currentLED == 8)
    {
      // Blink the orrect (green) LED
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
      delay(200);
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
    }
    }
  }

```

# Answer
> 2 votes
```
int currentLED

```

You are missing a semicolon there.

---

```
void setup();

```

There should *not* be a semicolon here.

---

Do some tutorials on the C or C++ language. They will help you.

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


# Question
Title: Integrating 2 push buttons to toggle the LED ON and OFF
Hey guys need your help in verifying out this program about toggling the LED ON and OFF using 2 push buttons.What i actually want is to let my LED stay ON when i press and even leave the push button-1 , and on pressing and leaving the push button-2 i want the led to turn off and no matter how many times i press the push button-1 i want it to turn ON the LED and the push button-2 should only turn off the LED.but with my program i am only able to see the LED to be at HIGH state,It is not shifting to LOW state on clicking push button-2.

This is my sketch :-

```
    /* LED CONTROLLED WITH 2 PUSH BUTTON PROJECT
       BY ARSH BANSAL

 CIRCUIT :-
 i) LEDPIN CONNECTED PIN 13.
 ii) PUSHBUTTON1 CONNECTED TO PIN 8.
 iii) PUSHBUTTON2 CONNECTED TO PIN 7.
 iv) BOTH THE PUSH BUTTONS CONNECTED PARALLELY, EACH WITH A 1K PULLUP RESISTOR AND BOTH THE PUSH BUTTONS CONNECTED TO 5V SUPPLY.
   */

 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

 void setup()
 {
   pinMode(ledpin,OUTPUT);
   pinMode(pushbutton1,INPUT);
   pinMode(pushbutton2,INPUT);
 }

 void loop()
 {
   if ( digitalRead(pushbutton1)== HIGH && digitalRead(pushbutton2) == LOW && lastbuttonstate1 == LOW )
    { digitalWrite (ledpin,HIGH) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW && lastbuttonstate1 == HIGH)
    ; { digitalWrite (ledpin,HIGH) ; }

    if ( digitalRead(pushbutton1)== LOW && digitalRead(pushbutton2) == HIGH  && lastbuttonstate2 == LOW)
    { digitalWrite (ledpin,LOW) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW  && lastbuttonstate2 == HIGH)
    ; { digitalWrite (ledpin,LOW) ; }
    }

```

# Answer
You are better off, in this case, remembering the state of the LED not the state of the buttons:

* If the LED is OFF and BUTTON1 is PRESSED then turn the LED on.
* If the LED is ON and BUTTON2 is PRESSED then turn the LED off.

For example:

```
void loop() {
    static bool ledState = false; // LED is off by default
    if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
        digitalWrite(ledpin, HIGH);
        ledState = true;
    }
    if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
        digitalWrite(ledpin, LOW);
        ledState = false;
    }
}

```
> 1 votes

---
Tags: arduino-uno, led, button
---


# Question
Title: Can an L293D motor driver shield do microstepping?
I bought a L293D motor driver shield and have used it with a pre-made sketch for driving a pair of stepper motors, but I'm not familiar with its capabilities.

The sketch I've used so far doesn't use microstepping when it's set up for this shield (though it does use it with the Adafruit shield).

I've done some searching, and it's not clear if the L293D chips on the shield can do microstepping, and if so, how.

Are L293D chips (and thus the motor driver shield that uses them) capable of microstepping? If so, how can I add this capability into my sketch?

# Answer
> 4 votes
It would be more accurate to say that it can be used as part of a microstepping system, though it's probably not a good choice for *any use* today.

The L293D is merely an (effectively obsolete implementation of an) H-bridge, not a stepper motor *sequencer*, hence it is no more capable of autonomously driving a motor in full or half step mode than it is of microstepping - it can only do any of these when it is controlled by a sequencer, such as an L297 chip, or software running on an Arduino's processor.

Microstepping requires partially actuating the coils to interpolate between the angular positions which would be achieved by activating each in turn fully. It can be thought of as a proportional extension of how half-stepping uses actuating both coils at the same power to achieve a halfway in between position, only now the coils are actuated at different power levels to achieve finer gradations of position, though achieving accurate interpolation requires care as the relationship is not linear.

Modern power electronics no longer use variable analog drivers, as these convert the unused power to heat. Instead, the goal is to use switches which come as close as possible to only ever being fully on or fully off. Reduced driver power is achieved by pulse width modulating the switch, varying the average amount of power delivered to the load over a short period of time. In a stepper motor setting, this on-off modulation can be done to achieve microstepping and or also to achieve current regulation when a many-times-rated-voltage supply is used to allow overcoming winding inductance at high step rates.

The L293D (and its larger cousin the L298) are quite inefficient bipolar transistor bridges (they aren't very good switches compared to MOSFETs), and should probably not be chosen for new designs today. They are, however, capable of being used to microstep a motor when actuated by a sequencer which pulse width modulates the phase signals. Adafruit, who appear to be the original creators of this shield design, have in fact published microstepping driver code for their L293D board on github.

https://github.com/adafruit/Adafruit-Motor-Shield-library

Given that the ebay seller you link to as the source of the board is using Adafruit's own schematic on their product page, it's a bit unclear why your software is differentiating between this board vs an Adafruit one, unless by the the Adafruit board you mean their V2 shield. The V2 design uses a more efficient TB6612FNG FET bridge, but of more relevance to microstepping offloads the sequencing task from Arduino software to a PCA9685 chip which is apparently capable of microstepping (as well as simpler modes) by itself. Depending on the computational load and/or your level of determination, you may be able to get the ATmega microstepping the L293D in the context of your overall project.

# Answer
> 1 votes
Not directly. The L293D is a digital H-bridge chip. L293 series devices allow you to supply enough power for small motors, and the "D" model has internal protection diodes. There are other ICs and breakout boards that are designed specifically for microstepping. Here are a few options...

* The SparkFun EasyDriver ($14.95) will probably be the quickest solution.
* There are a variety of stepper driver ICs on the market with a wide range of power ratings. For instance, ST makes the L6219 ($4.86) and ON also makes several versions of the LB1847 ($4.19-$6.90). TI also makes a few.

Datasheets will typically say whether a driver is capable of microstepping at the beginning. Just make sure the driver you choose is capable of handling the stall current of your stepper.

Are your steppers unipolar (6+ wires) or bipolar (4 wires)? That may make a difference in how you wire them, although some unipolar motors can be driven as if they were bipolar.

---
Tags: arduino-motor-shield, stepper
---


# Question
Title: How to merge two arduino sketches, one for relay's and one for Servo motor?
Recently I uploaded individual codes for relay's and Servo motor seperately, it all worked fine. But when I combined these two codes and dumped in to the loop there is a delay in functioning of the relay's but the Servo motor is working fine.

I have to control these devices through Bluetooth HC-05 module. Could you please help me with the code?

```
/*
simple LED test
*/
#include <Servo.h>
char val;         // variable to receive data from the serial port
int ledpin = 2; // LED connected to pin 2 (on-board LED)
Servo myservo;
int pos = 0;    // variable to store the servo position
int motor = 0;

void setup()
{
  pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.print("Arduino control Servo Motor Connected OK");
  Serial.print('\n');
  Serial.begin(9600);       // start serial communication at 115200bps
  digitalWrite(ledpin = 2 ,HIGH);
  digitalWrite(ledpin = 3 ,HIGH);

}

void loop()
{

      if( Serial.read() == 'a' )    // if 'a' was received led 2 is switched off
  {
    digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2

  }

  if( Serial.read() == 'A' )               // if 'A' was received led 2 on
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2

  }

  if( Serial.read() == 'b' )        // if 'b' was received led 3 is switched off
  {
    digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3

  }

  if( Serial.read() == 'B' )               // if 'B' was received led 3 on
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3

  }

  if (Serial.read() == '\n')
    {

   motor = Serial.parseInt();
    pos = Serial.parseInt();
      myservo.write(pos);
      delay(15);
      Serial.print("Data Response : ");
      Serial.print(motor, DEC);
      Serial.print(pos, DEC);

    }

    }

```

# Answer
A couple of things stand out in your code.

1. Whenever you perform a digital write you assign a value to ledpin:

```
digitalWrite(ledpin = 3, LOW);

```

This is not necessary as you do not do anything with the ledpin variable. Instead, just have the digital I/O pin number:

```
digitalWrite(3, LOW);

```

Or simply have 2 variables, one for pin 2 and another for pin 3. Eg.

```
redledpin = 2;
greenledpin = 3;

```

This also applies to the pinMode function calls in the setup function.
2. Each one of your `if( Serial.read() == xx)` statements will read a serial character off of the serial buffer. Instead store the read character in a local variable:

```
readChar = Serial.read()
if( readchar == 'a')
...
if( readchar == 'A')
...
if( readchar == 'b')
...
if( readchar == 'B')
...

```
3. I would encase all of the code inside `loop()` with:

```
if ( Serial.available() )
{
    ...
}

```
4. The delay function is blocking and this will cause issues. I suggest deleting the delay altogether.
5. Due to the fact that you are sending commands to turn digital outputs on and off as well as sending an integer for motor and another for pos, I suggest that you define a packet structure and make your code follow that (with the necessary error handling). As the code currently stands you will miss information, depending on what character it sees first on the serial buffer.

I suggest something like:

```
A, B, 142, 090

```

Starting the packet off with a know character is a good idea. So is having a timeout period - in case only a portion of your packet is received.
> 1 votes

---
Tags: arduino-uno, servo, relay, hc-05
---


# Question
Title: How to approach an complex Arduino Uno project (Serial, SPI, Ethernet) in pure C, without libraries?
I have a college assignment where I need to get serial output, the Ethernet shield and SPI communication with other boards to work. We are not allowed to use any existing libraries, though we can use them as strong inspiration, as long as we are able to explain every line we have in our final code.

Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries but I am hopelessly overwhelmed by anything beyond getting a pure C blinky to run.

Do you have any idea how I should approach this? Are there C resources about the Ethernet shield and Arduino SPI?

# Answer
> 1 votes
As Hans Neve wrote, you should really refer to the docs.

This is how it works in real life, when you want to write a driver for a new piece of HW.

You have to at least understand the block diagram, programming models and register sets of the device you want to control.

*Then* read whatever existing code you might find. In the practical case you have the driver for the version N-1 of the HW. Or maybe for something close enough.

As generic programming advice goes:

* avoid any dynamic memory allocation, you will thank yourself later on, when you do not have to debug unexplained memory issues
* if you want to write a driver, consider making it reentrant, should the same code be shared across multiple IP blocks
* if you want to use OOP, avoid anything that requires runtime lookup. The compiler should have enough information to resolve everything statically.

WRT debugging: both device drivers might suffer from interference if you try to use the serial port. Consider using some ICD tools, like the AVR Dragon. Alternatively, you might find that debugging over I2C is less penalizing. But you have to define your debugging messages.

# Answer
> 0 votes
SPI is pretty trivial (see the existing SPI library). Serial is easy enough. As for the Ethernet shield you would need to look at either the existing library or the manufacturer's datasheet. Some Ethernet chips are *much* easier to work with than others.

---

If you look at the datasheet for the Atmega328P (as used in the Uno) they have example code (in C) for SPI - along with comments. That should let you knock off the SPI part in an hour.

They also have example code for serial. Add in a ring buffer and you should be able to get serial going in half a day.

After all, the assignment doesn't tell you to not use the *datasheet*.

Depending on the Ethernet chip, you should be able to dig up (possibly in the chip datasheet) example code for that as well.

---

You could always use existing libraries (eg. Serial.print) for *debugging*, and then pull that code out once you are happy your own code works.

---
Tags: arduino-uno, ethernet, spi
---


# Question
Title: Can I specify custom port names in the Arduino IDE on Linux?
On Linux, if you have more than one USB TTY device, the USB port name (`/dev/ttyUSBx`) changes every time one is plugged in, and there's no easy way to know the new name without going and looking through dmesg. It's trivial to set up a udev rule that creates a custom symlink so that my Arduino's FTDI can always be accessed through e.g., `/dev/ttyArduino`, and this is the standard procedure for persistent access to USB devices.

However, I can't make the IDE accept anything other than the `/dev/ttyUSBx` names. Even directly editing `preferences.txt` is ignored.

Is there any way to instruct the IDE to use custom port names in order to access the Arduino through a symlink or other persistent name?

# Answer
Consider using a device name of form ttyUSBnn, where nn is fairly large. For example, in /dev you could say

```
sudo ln -s ttyUSB1 ttyUSB77

```

Then, `ttyUSB77` shows up in the IDE's ports list and can be selected.

(I don't know how to set up that link using the `udev` system, but imagine it can be done.)
> 2 votes

# Answer
Think the other way.

If your device has a port name, that is not supported by the IDE, you can create an additional (static) symlink `/dev/USBx` that you can identify and select in the arduino IDE.

And yes, it is quite easy to make all of your arduinos unique to udev.
> 2 votes

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


# Question
Title: Getting RTK-precision GPS with arduino devices like NavSpark?
In trying to learn how to create a reasonably precise 3d model of my (very hilly) property, I stumbled across a product called Navspark, which appears to be a $22 arduino-compatible development board, with an RTK-capable (and RTKlib-compatible) GPS chip.

The idea with RTK is that a reference-position base-station transmits its positional error to a mobile unit, giving the mobile unit cm-level precision relative to the position of the base station. The error calculation is computationally intensive, but apparently within the capabilities of a Pi.

Is it actually possible to build an RTK-capable mobile/base pair using low-priced equipment like this? Can you link a howto or project example?

# Answer
> 1 votes
How about the http://www.navspark.com.tw/tutorial-4 tutorial? It seems to indicate you need a couple of the more capable $80 NS-RAW units with carrier-phase info rather than the less capable $22 NAV-SPARC plain GPS units.

The RTK system doesn't transmit only its positional error, (which it knows from external information) but also communicates the phase information for the particular channels, and then the RTK software re-calculates the positions of both using common sets of satellites and the phase info. With the same framework, it knows the relative positions accurately, and with assumptions about the location of the base station, it can correct mobile station

This isn't an arduino problem, unless you are asking about porting RTKlib to something arduino.

---
Tags: gps, wireless
---


# Question
Title: Convert library from using bitbanging to hardware SPI
I'm using a MCP3008 8ch 10bit ADC to expand the Analog Inputs for the project I'm working on. The only library I can find for it is here the library is ported from Adafruit's Raspberry Pi library here. From what I can tell the library uses bitbanging as opposed to hardware SPI in order to communicate. I would like to use hardware SPI, but don't have the skills to write a library to communicate with it myself. Are there any resources for how to write a library like that, or anything I can read about on how to convert a library from bitbanging to hardware SPI?

# Answer
> 1 votes
Turns out my google-fu needs work. I found this that works great using hardware SPI! Thanks everyone!

# Answer
> 4 votes
The standard AVR library has SPI handling. See, for example: http://www.gammon.com.au/spi

You don't have to write a library if you don't want, just communicate directly using SPI.

The datasheet for the MCP3008 has some tips for using an 8-bit SPI system to communicate with the device. In particular this chart:

You can see from that, that you will need 3 x SPI.transfer. I don't have one here to test with, but the code would look like this:

```
digitalWrite (SS, LOW);  // select device
int result;
SPI.transfer (0x01);  // start bit
result = SPI.transfer (0b10000000);  // single, ch0
result = (result & 0b11) << 8;  // move to high-order byte
result |= SPI.transfer (0);   // lower order byte
digitalWrite (SS, HIGH);  // deselect

```

Untested, but this should be roughly it.

---
Tags: library, spi, prototype, pcb-design
---


# Question
Title: Burn normal bootloader onto Atmega328P configured to use internal 8MHz clock
I have an Atmega328P that I have previously burned with a bootloader configured to use the 8MHz internal clock as described here. I would like to now burn the normal Duemilanove bootloader configured to use an external 16MHz clock onto the chip. However, when I try following the normal procedure, it says "Invalid device signature". I can still upload programs to the chip and they will run, but I would like it to use the 16MHz external clock. How do I do this?

# Answer
I have a sketch that will upload the Optiboot bootloader \- that will work perfectly well on the Duemilanove.

The latest version will be available on GitHub.

This particular sketch is in the "Atmega\_Board\_Programmer" subdirectory.

You need to run this sketch on another Arduino (like a Uno) and connect it up like this:
> 1 votes

---
Tags: atmega328, bootloader
---


# Question
Title: How to flush the input serial buffer in Arduino?
I am communicating with the esp8266 WiFi module using Arduino. The module returns GET requests from other clients. They will be of the form

```
GET /101011 HTTP/1.1\r\nHost...

```

I wish to extract only the `101011` from the received serial data and discard the rest. I came up with this small chunk of code to test it by sending data from my laptop.

This is the code:

```
String s;

void setup() {

  Serial.begin(9600);
}

void loop() {

  if(Serial.available())
  {
    Serial.println("Inside");
    Serial.find("/");
    s = Serial.readStringUntil(' ');
    Serial.println(s);
    // Discard the rest of the data . Snippet from Jeremy Blum's Blog

    while(Serial.available()>0) Serial.read();

  }

}

```

Jeremy's Blog

But when I run this using the input `GET /101011 HTTP/1.1\r\n` the output produced is

```
Inside
101011
Inside
1.1\r\n

```

Why is `Serial.available()` returning `true` even after reading everything? How to discard the rest of data from the serial input buffer?

# Answer
> 2 votes
One possible approach is to read and discard everything for a fixed time, like a second. For example:

```
unsigned long now = millis ();
while (millis () - now < 1000)
  Serial.read ();  // read and discard any input

```

I'm not a big fan of trying to "flush the input buffer". How do you know if a second is long enough? Or maybe it is too long? You are better off reading to some known delimiter.

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


title: How to Determine Fuse Settings

text:
# Question
Title: How to Determine Fuse Settings
I bought an arduino compatible board here: http://unsigned.io/projects/micromodem/ and am trying to flash new supported firmware onto it. The only instructions given to flash the board is to use the command avrdude -p m328p -c arduino -P /dev/ttyUSB0 -b 115200 -F -U flash:w:YourFirmwareFile.hex .

I'm trying to follow the tutorial here using an Uno as a programmer: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader#uploading-code---hard-way but I don't know what to use for the fuse settings. I've tried a few different fuse settings such as the one for the Uno, and default 328p ones using a fuse calculator but it seems like they all have unpredictable results. Some fuse settings make it so that I can't connect to the COM port at all to monitor the traffic, and others let me connect, but send a message of . I'm expecting an introduction message from the firmware that is supposed to be built in.

Thanks for the help.

# Answer
Normally you don't need to change the fuse settings, this configuration should be fine with the default arduino setting of

lowfuse=0xff

highfuse=0xde

extendedfuse=0x05

Serial should work fine.
> 1 votes

---
Tags: firmware
---


# Question
Title: Why does enabling TIMSK1 mess up serial?
I am intending to write a code where a user will send lines through serial to affect timer interrupts. I am noticing a problem with serial where as soon as I enable the timer interrupts, the serial communication becomes garbled. More specifically, as soon as I enable the timer interrupts and I open the serial monitor, the monitor gets flooded with garbage. I haven't written too much code and this is already happening. Am I making a silly mistake? I am using an Arduino Mega 2560. My code is below:

```
void setup() {
  Serial.begin(9600);
  Serial.println("Hello World!");
  timer_setup();
}

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

void timer_setup() {
  // waveform generation = 0100 = CTC
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |=  (1 << WGM12);
  TCCR1A &= ~(1 << WGM11);
  TCCR1A &= ~(1 << WGM10);
  // output mode = 00 (disconnected)
  TCCR1A &= ~(3 << COM1A0);
  TCCR1A &= ~(3 << COM1B0);
  // Set the timer pre-scaler
  TCCR1B = (TCCR1B & ~(0x07 << CS10)) | (2 << CS10);
  OCR1A = 0x4000;
  TCNT1 = 0;
  // Enable timer interrupt mask 1
  TIMSK1 |= (1<<OCIE1A);
}

```

If I comment out the `TIMSK1 |= (1<<OCIE1A)` line, serial doesn't mess up.

# Answer
You've enabled interrupts for Timer 1 Compare A interrupt. Where is the interrupt handler?

For example:

```
ISR(TIMER1_COMPA_vect)
{
  // whatever
}  // end of TIMER1_COMPA_vect

```

Without that, the processor is just restarting. No wonder serial output is messed up.
> 4 votes

---
Tags: serial, arduino-mega, c++, interrupt, timers
---


# Question
Title: Problems connecting reliably using HC-05 (as bluetooth master)
I currently try to connect an Arduino Micro/Leonardo/32u4 to an ELM327 Bluetooth dongle using a HC-05 Bluetooth shield from iTeadStudio. I also have similar problems trying to connect to a bluetooth dongle (with added serial connection) on my PC.

The basic AT-command communication works, but I haven't found out yet why AT+PAIR or AT+LINK are failing and what should be done to avoid this (I've done dozens of Serial Monitor command iterations). Until now I haven't found a command sequence that reliably connects. What I've tried so far (from different documentation and example codes):

Check general AT command set:

```
AT
> OK

```

Reset to default values:

```
AT+ORGL
> OK

```

Set master mode and check it:

```
AT+ROLE=1
> OK
AT+ROLE?
> +ROLE:1
> OK

```

Connect only to the specified bluetooth address:

```
AT+CMODE=0
> OK

```

Reset and initialize:

```
AT+RESET
> OK
AT+INIT
> OK

```

Configure inquiring mode:

```
AT+INQM=1,9,48
> OK

```

Inquire:

```
AT+INQ
> +INQ:12:34:567890:1F1F,7FFF
> OK
AT+STATE?
> +STATE:INQUIRING

```

Try to stop inquiring:

```
AT+INQC
> OK
AT+STATE?
> +STATE:INQUIRING
> OK

```

Reset and initialize again (otherwise we can't leave the inquiring state):

```
AT+RESET
> OK
AT+INIT
> OK
AT+STATE?
> +STATE:INITIALIZED
> OK

```

Try to pair with the found device (my PC asks for the 1234-password and creates a serial port):

```
AT+PAIR=12,34,567890,20
> OK
AT+STATE?
> +STATE:PAIRED

```

Try to connect

```
AT+BIND=12,34,567890
> OK
AT+LINK=12,34,567890
> FAIL
...

```

Does someone have some hints for finding the right sequence?

# Answer
> 1 votes
It looks like I now have a slight understanding of what happens and how to get the HC-05 working.

Be sure to have the CMD-DAT-switch set to CMD before turning on the HC-05.

**Command mode (configuration)**

Check general AT command set:

```
AT
> OK

```

Reset to default values (sets, among others, ROLE=0 and CMODE=1):

```
AT+ORGL
> OK

```

Set master mode and check it:

```
AT+ROLE=1
> OK
AT+ROLE?
> +ROLE:1
> OK

```

Reset and initialize (reset aborts, e.g. the inquiring state - quickly flashing LED; without initializing you would get ERROR(16)):

```
AT+RESET
> OK
AT+INIT
> OK

```

Now the LED should slowly flash. Optionally: set password of the target device:

```
AT+PSWD=1234
> OK

```

Show count of all authenticated devices in pair list:

```
AT+ADCN?
> +ADCN:7
> OK

```

If the value is larger than 0, delete all authenticated devices in pair list:

```
AT+RMAAD
> OK

```

Now pair with the desired device (the last 20 mean 20s):

```
AT+PAIR=12,34,567890,20
> OK

```

The LED starts flashing one time with a longer pause. Set the desired device:

```
AT+BIND=12,34,567890
> OK

```

Now link (e.g. when connecting to the ELM327; the PC will create another new port after having requested the password from the user):

```
AT+LINK=12,34,567890
> OK

```

The LED starts flashing two times with a longer pause. After linking, it might be that either the HC-05 switches to data-mode or continues in command-mode (haven't found out when it does one or the other).

**Command mode (auto connect)**

Now switch off the HC-05 and keep the CMD-DAT-switch to CMD. Switch it on again. It should automatically connect to the previously connected device. To switch to the data mode, first disconnect...

```
AT+DISC
> +DISC:SUCCESS
> OK

```

... and reconnect.

```
AT+LINK=12,34,567890
> OK

```

Now the connection seems to have switched to data mode.

**Data Mode**

Now switch off the HC-05 and move the CMD-DAT-switch to DAT. Turn on the HC-05. It automatically will try to connect to the previously connected device - the LED should flash two times with longer pause - and you don't have to mess with HC-05-AT commands any more.

# Answer
> 2 votes
I am using a "BIND" between the PAIR and LINK:

```
AT+PAIR=98D3,31,FC2D54,5
AT+BIND=98D3,31,FC2D54
AT+LINK=98D3,31,FC2D54

```

That seems to work for me.

See the docs here:

ftp://imall.iteadstudio.com/Modules/IM120723009/DS\_IM120723009.pdf

---
Tags: bluetooth, hc-05
---


# Question
Title: Arduino Pro Mini and Electronic Speed Controller (ESC)
I want to send servo signal to ESC and Servo with my 3.3V Arduino Pro Mini.

Can the ESC/Servo read 3.3V signal from Arduino Pro Mini? Or do I need to make some level shifter to make 5V signal?

# Answer
> 1 votes
The ESC should have no problem with 3v3 signal.

# Answer
> 0 votes
Signal can be send easily from Arduino Pro mini to ESC, Simply either use .write() or .Microseconds() function.

---
Tags: servo, arduino-pro-mini
---


# Question
Title: Code for password-activated LED via Bluetooth serial
I have this pretty simple task to light up an LED for 3 seconds when I send the right password from my Android phone to the Arduino via Bluetooth. I am using an HC-05 Bluetooth Module. My LED is connected to Pin 9 of the Arduino I/O. TX and RX of HC-05 is connected to Pins 1 and 0 of Arduino respectively. Here's the code I am using:

```
int output = 9;         //I will be using to control a DC motor(LED is just for testing).
int output2 = 10;
char final[4];
char correct[4] = {'Q','W','E','R'};
int pass_true;

void setup() {
  pinMode(output, OUTPUT);
  pinMode(output2, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  while(Serial.available()){
    for(int i=0; i<4; i++){
      final[i] = Serial.read();
    }
    for(int i=0; i<4; i++){
      if(final[i]==correct[i]){
        pass_true = 1;
      }
      else{
    pass_true = 0;
    break;
      }
    }
  }

  if(pass_true==1){
    digitalWrite(output, HIGH);
    Serial.println("ON");
    delay(3000);
    pass_true = 0;
  }
  else{
    digitalWrite(output, LOW);
  }

}

```

I am using Bluetooth SPP Pro Android App to send the 4-byte pass code ("QWER")

The problem is the LED wont light up. I tried replacing the LED thinking that it may be a dead one but it's not. The "TX" LED on the board blinks everytime I press "SEND" in the Bluetooth App, but still Pin 9 doesn't seem to produce the HIGH output at all. Is there a problem with the code?

# Answer
Try using the following code you need to use String and concatenate that

```
    String rcev_data="";
bool chk=false;
\#define output 9

\#define output2 10

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

void loop()
{
  // put your main code here, to run repeatedly:
  while(Serial.available())
  {
    char rxx = Serial.read();
    recv.concat(rxx);
    delay(10);
    if (recv == "QWER")
    {
       chk=1;
       break;
     }
    else
     chk=0;
 }

  if (chk)
  {
    digitalWrite(output,HIGH);
    Serial.println("ON");
    delay(3000);
    chk=0;
  }

  else
  {
    digitalWrite(output,LOW);
  }
  recv="";
}

```
> 1 votes

# Answer
Instead of

```
while(Serial.available()){

```

please try

```
while(Serial.available() >= 4){

```

Depending on how your transmitting application is buffering the writes, the loop()'s password check may be triggering on a single byte of input each time.

You may also want to make the code a bit more fault-tolerant. For example what if there's a bit of noise in the line, or the operator pushes \[Enter\] first before entering the code. The input buffer will fill up a few characters, then the password will not match because it spans, say input bytes 3,4,5,6. Maybe throw away any old input based on elapsed time, etc.
> 0 votes

---
Tags: bluetooth
---


title: Arduino Yun used as Wi-Fi hotspot

text:
# Question
Title: Arduino Yun used as Wi-Fi hotspot
I use for a project an Arduino Yun with Node.JS + socket.io to provide interactivity between a smartphone, driving through a webpage different devices.

I would like to enable this service for several smartphones at the same time. However I would like to work in the very same conditions that a (well configured) hotspot does:

1. I want to ensure that no user can see the other users on the network,
2. I want to have a limited number of connections on the Yun at the same time,
3. I want to force the different users when connected to the Wi-Fi to be routed to a captive portal on the first connection.

Does anyone know first if it is possible with an Arduino Yun (maybe some actions must be performed on a NodeJS virtual server as point 2). If yes, do you have a tutorial or any clues (do I have to use LuCi)?

Last question, in the same topic, I would like to use a fast granted access using NFC tag emulation to provide Wi-Fi credentials. Has anyone tried this with Arduino Yun and a shield?

# Answer
Finally, here is how I did the job. In short, I separated the two topics of getting a trace of any user using `socket.io` and giving a limitations of the number of users.

First, my Arduino Yun is on a Ethernet network where a router, acting also as the internet gateway, is a dhcp server. My Arduino Yun have a static IP address in the subnet of this router (so it is not a dhclient). This can be set either by modifying the file `/etc/init.d/network`.

Including the lines:

```
config 'interface' 'wan'
        option 'proto' 'static'
        option 'ifname' 'your_interface_name'
        ipaddr xxx.xxx.xxx.xxx

```

or by using the LuCi interface.

For more information about the way to properly configure the network in OpenWRT, see Network configuration.

Then the router is set to authorize only few IP addresses.

The last step is to bridge the Wi-Fi and the Ethernet (WAN and LAN) keeping the configuration of the Ethernet interface. This can be done using the LuCi interface. Be careful of what interface configuration you keep. How to setup an OpenWRT router as a Wi-Fi bridge to an Ethernet router gives the way to do this.

Note that this can also be done using the Arduino Yun as a DHCP server if you don't want to be connected on a network.

In the end, any connections on the Arduino Wi-Fi will get its IP address in the authorized range (up to 16 users at the same time in my case) by the router/DHCP server through the bridge.

In `socket.io`, I took the id that is given to any connected client and the IP address to ensure that I have a same user.

About the NFC dynamic tag, I developed a NFC specific board with a dynamic tag in the Arduino Yun/Uno format and its library to push through the bridge between ATmega and Atheros any new Wi-Fi code or any webpage. I think it is outside of this scope so if you need anything about this I can give you in PM.

I finally get at the end a device:

* Connected to an existing network and accessing the internet,
* Serving the webpages I want using my node serve,
* Able to push any information on any other devices on the network through my nodeJS server,
* Enabling access to people to local or network content,
* Serving some specific local information through the NFC shield.
> 0 votes

---
Tags: wifi, arduino-yun, node.js
---


# Question
Title: What are the parameters of the browseUrl() callback in the Ethercard library?
I'm reading a code that uses Arduino as a webclient and when he tries to catch the info from the site, he uses a callback with the following parameters:

```
static void response_callback (byte status, word off, word len)

```

Can anyone explain me how does each one of this parameters work exactly?

PS.: The example I got it from:

```
#include <EtherCard.h>

#define HTTP_HEADER_OFFSET 0
static byte mymac[] = {0x12,0x34,0x56,0x78,0x90,0xAB};
char website[] PROGMEM = "www.yourwebsite.com";

byte Ethernet::buffer[700];
static uint32_t timer = 0;

static void response_callback (byte status, word off, word len) {
  Serial.print((const char*) Ethernet::buffer + off + HTTP_HEADER_OFFSET);
}

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

  if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
  {
    Serial.println("Failed to access Ethernet controller");
    while(1);
  }
  else
    Serial.println("Ethernet controller initialized");
  Serial.println();

  if (!ether.dhcpSetup())
  {
    Serial.println("Failed to get configuration from DHCP");
    while(1);
  }
  else
    Serial.println("DHCP configuration done");

  if (!ether.dnsLookup(website))
  {
    Serial.println("DNS failed");
    while(1);
  }
  else
    Serial.println("DNS resolution done");

  ether.printIp("SRV IP:\t", ether.hisip);
  Serial.println();
}

void loop() {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 5000;
    ether.browseUrl("/", "yourpage.php", website, response_callback);
  }
}

```

# Answer
> 1 votes
Apparently, the callback is executed on every packet which arrives by the browseUrl call.

"off" and "len" are pointers to the Ethernet buffer holding the data. "Off" are the initial value (offset) and "len" (length) is the amount of data received.

"byte status", I am not sure what it means, but it's very likely will be some kind of error code. It's not being used in any sample I am seeing, so I am really wondering what it means...

Check this link for a fully working sample

Callback here are called browseUrlCallback1 and browseUrlCallback2.

Can't figure out a link with the detailed documentation. If someone has it, please post it.

---
Tags: arduino-mega, ethernet, callbacks
---


# Question
Title: Possible to create IP-to-USB HID (keyboard) device using Arduino?
Is it possible to create an IP-to-USB HID (keyboard) using Arduino?

I'd like to connect an Arduino to my network using Ethernet, and then send it commands using TCP/IP and have those commands translated to USB HID and sent as keystrokes to the connected PC.

I've found a few articles discussing USB HID emulation using the Arduino Uno (see http://mitchtech.net/arduino-usb-hid-keyboard) but it refers to using GPIO pins as buttons.

Am I correct that this might work if I use an Arduino Uno and then purchase an Arduino Shield Ethernet? (seems a bit expensive, but is this the cheapest option?)

Thanks in advance!

# Answer
> 2 votes
Yes, it is perfectly possible.

You ideally need an Arduino with a direct USB interface, such as the Leonardo. Then you can just access the `Keyboard` object to send the keystrokes to the PC. How your receive the data through Ethernet is entirely up to you. A simple TCP interface may be easiest - open the connection with whatever telnet-like client and whatever you type gets sent through. The trick will be getting it into character-at-a-time mode.

---
Tags: ethernet, usb, keyboard
---


# Question
Title: LM335Z temperature sensor gives very varying values
I'm trying to get consistent values from the LM335Z temperature sensor. But it behaves very strange.

I'm using an arduino nano and it's powered via USB from a Raspberry Pi. The circuit also has two little reed relays (SIP-1A05), a button and a potentiometer. It's connected like this:

Additionally I'm using `analogReference(EXTERNAL)` in an attempt to get consistent values, so I've connected the Arduinos 5V output to the reference voltage pin. Here's the code for reading the thermometer:

```
int getTemperature() {
  int rawvoltage = analogRead(0);
  float millivolts = (rawvoltage / 1024.0) * 5000;
  float kelvin = (millivolts / 10);
  float celsius = kelvin - 273.15;
  return round(celsius);
}

```

Then it just waits for me to say "get" in the serial monitor and it replies with:

```
void sendData(){
  String data = (String)getTemperature();
  data += ',';
  data += (String)map(getTablePos(), 0, 1023, 0, 100); //Potentiometer
  data += ',';
  data += (String)getTableActive(); //1 or 0
  Serial.println(data);
}

```

I also read somewhere that the first couple of readings are unreliable, and that you should read a couple of times in startup, which I do:

```
for(int i = 0; i < 10; i++){
    analogRead(0);
    delay(1);
  }

```

Yesterday the termometer reported 37 degrees. Today it started by reporting 49 degrees. After asking for the temperature a couple of times it said 56. Then now, about an hour later it says 52. And if one of they relays is active it says 77 degrees. My two other (non Arduino) thermometers have ben on a steady 25 all this time.

What should I do to get reliable values from the LM335z?

---

### Edit

Added dots to the intersections of the circuit diagram for better readability.

I've also found a way to get the thermometer to work, kind of. I removed the external analog reference and only have one 1kOhm resistor for the LM335Z.
Then I have this code instead:

```
const float cal = 4.62; //Voltage between 5V and GND, measured with multimeter

float getTemperature() {
    float input = (float) analogRead(0);
    input = (input*cal)/1024.0;
    return (input/0.01)-273.15;
}

```

It worked perfectly standalone on an Arduino Uno powered via USB3.0. When I moved it over into my project with the Nano it gave a few degrees off, but that can be combated by just subtracting the difference I guess. Then I tried switching to a USB2.0-port on my keyboard, and the values started jumping all over the place.
Here's a comparison using Arduinos rather spartan plotter:
Left: USB2.0 via keyboard hub. Right: Front panel USB3.0.

Also, the temperature dubbels when a relay is on.

How do I tackle this? I'd like keep powering it from my Raspberry pi 3, if possible.

# Answer
According to your schematic, one of the LM335Z's leads is floating. The pins are meant to be Vcc, Gnd, and output; the output should go to an Analog input.

You wrote that Aref was tied to +5 but you've drawn it as going to one end of the pot with the other end of the pot grounded. The pot's wiper goes to A1 (assuming the pin hasn't been set to some other function).

In short, check your circuit. Try wiring up the sensor to +5, Gnd, and your DVM. Then replace the DVM with A0. At that point you'll have confirmed the sensor circuit, leaving only the code and the external analog circuitry. While I only skimmed the code I don't see anything that would give flaky results. I think you're seeing analog noise, probably due to one or more of the floating sensor pin, an inconsistent or noisy Aref, and pickup in the analog input from the sensor.

Update: I based my connections description on this diagram

, from this datasheet. In all of those diagrams, the Resistor-Zener connection is shown as the output and no pins are shown floating. But I did see that pin labeled as adj, for what reason I don't know. That's really why I recommended getting the sensor working by itself first.

I see your +5V to Aref connection now. The usual convention for indicating a connection at such a crossing is to put a dot on the intersection, just as the output pin's connection is shown in the above diagram.
> 1 votes

---
Tags: arduino-nano, analogread, temperature-sensor
---


title: QuadCopter PID using MPU6050

text:
# Question
Title: QuadCopter PID using MPU6050
I am using Arduino Uno, with **PID** library and Jeff Rowberg library for MPU6050 i.e `I2Cdev.h`, `MPU6050_6Axis_MotionApps20.h`.

There is one PID for each axis i.e Pitch and Roll, I am getting output that wobbles and is unstable. I don't know whether my code is wrong or something else.

Errors which I feel are:

* I am using `Esc.write()`, I know Microseconds should be used but it feels very light, even it doesn't wobble.
* Kalman Filter not used, but I am getting the pitch, roll, yaw.
* PID library (By Brett Beauregard) not suitable for Quadcopter.
* ```
else if (mpuIntStatus & 0x02) // wait for correc available data length, should be a VERY short wait
         while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

```
This statement in loop making loop slow, it's written in its comment and maybe it making pid compute upset

Please look at code.

```
#ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        yaw = ypr[0] * 180/M_PI;
        pitch = ypr[1] * 180/M_PI;
        roll = ypr[2] * 180/M_PI;

        Input = pitch;
        RInput = roll;
        myPID.SetTunings(Kp,Ki,Kd);
        myPIDR.SetTunings(RKp,RKi,RKd);

        //Sample Time is 10 for both PID.

             myPID.Compute();
              myPIDR.Compute();

        if(armed == 1) {
          int m1 = throttle.toInt() + Output;
          int m2 = throttle.toInt() + ROutput;
          int m3 = throttle.toInt() - Output;
          int m4 = throttle.toInt() - ROutput;

 int angle1 = map(m1, 0, 100, 0, 180);
 ESC1.write(angle1); //FRONT PITCH+
 int angle2 = map(m2, 0, 100, 0, 180);
 ESC2.write(angle2); //LEFT ROLL+
 int angle3 = map(m3, 0, 100, 0, 180);
 ESC3.write(angle3); //BACK PITCH-
 int angle4 = map(m4, 0, 100, 0, 180);
 ESC4.write(angle4); //RIGHT ROLL-
        }
    #endif

```

*Kp = 0.25, Ki = 0.04, Kd = 0.05* | *RKp = 0.25, RKi = 0.04, RKd = 0.05*

*From testing: if I shake my Quadcopter fast by hand it behaves like PID is activated and works as wanted, but suddenly after a couple of seconds again feel loose, may be PID compute become upset*

# Answer
Quadcopters usually use 2-PID loops per axis, a rate loop and an angle loop.

Your quadcopter needs to be very aggressive about its rate of rotation but relatively relaxed about how quickly it returns its angle to the center so it doesn't overshoot. With a single PID it will either be too slow to correct or overshoot and oscillate with no "usable" range of tunings in-between, because in order for its outputs to be strong enough to control the quad it will necessarily be too aggressive to smoothly align with the center position. There is a lot of math that explains why this cannot be achieved with a single loop more rigorously if you care to look into it.

So try setting it up with a PitchAngle PID whose output is the setpoint of a PitchRate PID loop whose output goes to the motors, and similarly with the Roll.

That is only one possible problem though, there is a huge number of things that could be wrong. Are your pitch and roll measurements angles to the horizon or euler angles? how fast is your loop running? Are oscillations induced by the motors causing your accelerometer reading/attitude filter combo to be unusable? Are the PID parameters correct? Is the accelerometer's bias calibrated? Is the gyro drift calibrated? Are all you ESC's calibrated the same way?
> 2 votes

---
Tags: arduino-uno, mpu6050, pid
---


# Question
Title: Casting a struct member between uint8_t and char, with regard to serial transfer
Im simply trying to pass my payload to another device that has the same architecture and struct. I'm using UART to transfer, and modeling the protocol from EasyTransfer.

When I call `Serial.print((char*)mydata.data);` in Transfer it prints Hello World as expected.

Calling that same line in Receive prints a '?' to console. This may be some background behavior with Arduino, or I'm just not casting/handling the pointers correctly. How can I get this print out to function properly?

Transfer Sketch

```
#include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
SEND_DATA_STRUCTURE mydata;

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

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

  //initalize not so random number generator
  randomSeed(analogRead(0));

}

void loop()
{
  //mydata.blinks = random(5);
  //mydata.pause = random(5);

  //Create payload to transfer
  char* payload = "Hello World!";

  //Fill array with data
  strncpy((char *)mydata.data, payload, PAYLOAD_SIZE);

  //Print sample
  Serial.print((char*)mydata.data);

  //send the entire struct
  TransferObject.sendData();

  delay(5000);
}

```

Receive Sketch

```
    #include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct RECEIVE_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
RECEIVE_DATA_STRUCTURE mydata;

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

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

}

void loop()
{
  //check and see if a data packet has come in.
  if(TransferObject.receiveData())
  {
    Serial.print("active");
    //print data payload
    Serial.print((char*)mydata.data);
    }

  //you should make this delay shorter then your transmit delay or else messages could be lost
  delay(250);

```

This is an exerpt and variant from this library

# Answer
> 1 votes
You're actually falling into a common problem with pointers in structs.

This structure:

```
struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t *data;
};

```

contains three values: blinks, pause and a pointer to the data.

```
uint8_t *data;

```

That doesn't contain the data. That only contains the address that the data is stored at in memory. When you transfer the struct it's that address that you are sending - then when the other end tries to print it all it can do is look at the address it's been told about and try and print whatever is in there - and that is complete garbage.

Instead of storing a pointer to the data you need to store the actual data itself. That means that you need to decide upon a maximum size for that data and pre-allocate the memory within the struct:

```
#define DATA_SIZE 40

struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[DATA_SIZE];
};

```

Now in order to get the data into that struct you need to fill that array with your payload. For strings the simplest way is:

```
strncpy((char *)mydata.data, payload, DATA_SIZE);

```

That will copy *up to* `DATA_SIZE` characters from `payload` into `mydata.data`.

Note that if `payload` contains more than `DATA_SIZE-1` characters the data in `mydata.data` will not be NULL terminated. You can get round that by forcing NULL termination:

```
mydata.data[DATA_SIZE-1] = 0;

```

---

In your revised code your payload size is too big. The way the EasyTransfer library works is it has a single byte for the size of the payload. Your total payload size is PAYLOAD\_SIZE + 2 ints - that is 255 + 2 + 2 = 259 bytes. Placed into a single byte that gets truncated to 3. That means you are actually transferring one and a half integers and nothing else.

You need to ensure that your entire struct never exceeds 255 bytes. So you can have a maximum size of data, once you have taken your two integers into account (assuming 16-bit integers on an 8-bit Arduino), of 251 bytes.

---
Tags: serial, c++, uart, pointer, struct
---


# Question
Title: Can I apply a Kalman filter to DHT11 data?
I want to apply a Kalman Filter to the humidity data which I retrieve of the DHT11.

How can I do that?

# Answer
> 4 votes
Learn about the kalman filter and what it does. It requires a certain understanding of what it is, what it is good for and why you would eventually use it. It seems to me, that at the moment this isn't your strongest topic.

Thereafter, figure out which !multiple! sensor values you have, since only with a "model" and an "observation" a filter of this kind makes sense in the first place.

To specifically adress your question: you can apply any filter to any data. The hidden question, if it makes sense in this case is not trivial to answer, since you didn't exactly provide the vast information. My guess is, you only have this one sensor, and it would be (at this state of knowledge) a reasonable idea to use a bandpass filter of sorts instead.

---
Tags: esp8266
---