title: GET the first result in HTTP request

text:
# Question
Title: GET the first result in HTTP request
I have a `String content=""` and if I put an HTTP request like this:

```
client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();

```

the output I get is:

```
 [{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"},{"action_id":41,"action_type":"up","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:14","updated_at":"2015-08-16 20:50:14"},{"action_id":42,"action_type":"down","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:21","updated_at":"2015-08-16 20:50:21"},{"action_id":43,"action_type":"down","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-08-16 20:50:22","updated_at":"2015-08-16 20:50:22"}]

```

The little parser I created is this:

```
while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

```

Is it possible to store only the first action in JSON output, because the actions are updated, and if the number of chars extends 256 than I get errors while working with the `String content`?

# Answer
> -1 votes
Your question is not clear to me. First of all does your parser get the whole response? And second by first action do you mean "action\_id":35"? If both are true then your solution is simple.

First you separate every comma ", " and put in a string array then you further split each index by ":" so the first part is the name "action\_id" and the second is the value "35". I hope that helps . You can look up the split function, it's easy.

But if the above is not what you needed then I am afraid you *cannot* get only the first response, because that has to do with the server itself.

Here is a solution, do try it.

I found an easier solution. Follow the example and replace the content and fields with your response content and you will be done in minutes.

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


# Question
Title: Making servo spin and able to detect angle
After researching other posts I can see how to make a servo spin continually and remove the ability to set to a specific angle.

What I'm trying to do is make a small project that has a spinning 'game wheel', each segment of the wheel has a prize on it (think almost wheel of fortune). The catch is when someone has landed on a prize once it cannot be landed on again so I want to manipulate the spin slightly so it doesn't stop on the same prize. Do do this I need to be able to get the spin AND know where the needle is pointing.

Is there a component that will allow both a full rotation AND the ability to control the location of the needle at the same time? I suspect servos can do one, or the either but not both.

# Answer
The way I'd do it is the following:

* use an optical encoder with an endstop, they come @ 1€ on ebay, bought 4 today :-) - this will tell you the angular speed and incremental position
* use a photo transistor to detect a specific point on the wheel (make a small hole or paint a spot in a different colour) - this will give you the absolute position of the wheel, to calibrate the previous step.

With this solution you do not even need a step motor, a DC motor will do it and probably has better characteristics, for the same cost. So you could explore the DC option if it turns out that the stepper is not good enough.
> 1 votes

# Answer
As for Me the Best Way to To Use a Position Servo with the Feedback in it ( it comes with 6 wire ) then You put all Your Positions For the prizes in An Array and if Anytime You Land on An Index then You Should but it in an Array that Holds all the prizes angle visited Which you will use as a check Before Turning the Servo
> 0 votes

---
Tags: motor, servo
---


# Question
Title: Would Arduino Nano be good for Bluetooth + Sound
So I've been browsing around for a whole looking for a good microcontroller that's super small. So far the smallest one I found was an Arduino Nano. But before I go buying it, there are some questions I have about it.

1. Is Bluetooth compatible with it and if so where would I get the Bluetooth code?
2. Is there anything smaller than it that's Bluetooth compatible?
3. Would an Arduino Nano (Or the device in the question above) be able to play sounds?

# Answer
There are Bluetooth boards and chips that you can connect to a Nano.

You can play sounds with a Nano. Crudely with PWM and a direct connection, for finely with an external digital-to-analog converter.

But if super-smallness is what you are after, there may be better options.

The Blue Bean is a complete BLE microcontroller on a single board that is smaller than a Nano+board.

If you want even smaller, you could get something like the new Cypress EZ-BLE module...

http://www.cypress.com/products/ez-ble-module-bluetooth-smart

It is a complete programmable BLE system on a tiny module. It is hard to imagine anything smaller than that!
> 0 votes

---
Tags: bluetooth, sound
---


# Question
Title: Unexpected behaviour of blinking LED code
I'm new to Arduino so this may be a really silly doubt but I'm not finding an explanation for it anywhere online. I first uploaded this code (to blink 5 LEDs) on my Arduino Uno :

```
 void setup(){
 pinMode(12, OUTPUT);
 pinMode(11, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(9, OUTPUT);
 pinMode(8, OUTPUT);
}

void loop(){
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
delay(1000);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
delay(1000);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(1000);
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000);
digitalWrite(8, HIGH);
delay(1000);
digitalWrite(8, LOW);
delay(1000);
}

```

The 5 LEDs glowed brightly. But when I uploaded the following code (using an if statement to reduce the size of the previous one), the LEDs glowed dimly.

```
int LEDpin = 13;
void setup(){
pinMode(LEDpin, OUTPUT);
}

void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
  LEDpin = 8;
  }
}

```

Also, when I just typed the `if` statement without the `else` part, nothing happened after the LED at pin 8 had glowed on and off. Can someone please tell me why the LEDs glowed dimly in the second one and why nothing glowed after LED 8 when I skipped the `else` part?

# Answer
> 0 votes
The problem with your code is that:

**you have not initialised all the LED pins as output**. Only pin 13 is initialised as output.

So, initialise all the pins to output. A correct code would look like this:

```
int LEDpin = 13;
void setup(){
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
}

void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
  LEDpin = 12;
  }
}

```

# Answer
> 5 votes
As Abhishek mentioned in his answer is correct, but the better way is to use for loops while dealing with many led's.

Let's say you have led's connected from pin 2 to 8.

```
int pin = 2;
void setup()
{
   for (Pin = 2; Pin < 8; Pin++)
   {
     pinMode(Pin, OUTPUT);
   }
}
void loop()
{
   for (int Pin = 2; Pin < 8; Pin++)
   {
     digitalWrite(Pin, HIGH);
     delay(1000);
     digitalWrite(Pin, LOW);
     delay(1000);
    }
}

```

# Answer
> 1 votes
As Abhishek Jain explained, the pin's need to be initialised for OUTPUT.

However there is another error.

The code in `loop()` counts down to 8, once, flashing the LEDs, **but** then only lights an LED on pin 8 because it always goes through the `else` which maintains LEDpin's value as 8. LEDpin needs to be reset to 12, after it passes 8.

Better code might be

```
int LEDpin = 12;
void setup(){
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
}

void loop(){
  digitalWrite(LEDpin, HIGH);
  delay(1000);
  digitalWrite(LEDpin,LOW);
  delay(1000);
  if(LEDpin >= 8){
    LEDpin--;
  } else {
    LEDpin = 12;   // <---- start with the first LED again
  }
}

```

For what its worth, I wouldn't do the code this way. I would write something using for loops, like:

```
const int firstLED = 8;
const int lastLED = 12;
int LEDpin;

void setup() {
  for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
     pinMode(LEDpin, OUTPUT);
  }
}

void loop() {
  for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
    digitalWrite(LEDpin, HIGH);
    delay(1000);
    digitalWrite(LEDpin,LOW);
    delay(1000);
  }
}

```

---
Tags: arduino-uno
---


title: How do nested for loops work?

text:
# Question
Title: How do nested for loops work?
In the following code from an Arduino sketch will it run the first "for" statement before enacting the second "for" statement. Also how does it know go run the first stamens again? Will it continue to run till both statements are true?

```
for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

```

# Answer
A `for` statement repeats everything between `{` and `}`, (or just the next line if there is no `{` and `}` a certain number of times. It's not as simple as you might at first think, but it makes more sense if you write it out as a `while` loop explicitly.

For instance, `for (a; b; c) { ... }` could be re-written as:

```
a;
while (b) {
    c;
}

```

So if you had:

```
for (int i = 0; i < 100; i++) {
    Serial.println(i);
}

```

it could be re-written as:

```
int i = 0;
while (i < 100) {
    Serial.println(i);
    i++;
}

```

The two mean exactly the same thing. A `for` has the three elements - initializer, comparison and iterator. The initializer is run before the loop starts, the comparison is used to work out when the loop should finish, and the iterator is used to move through each iteration of the loop.

To re-write your specific example:

```
for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

```

You would end up with:

```
int r = 0;
while (r < 8) {
    int c = 0;
    while (c < 8) {
        lc.setLed(0, r, c, HIGH);
        c++;
    }
    r++;
}

```

Now, if we were to do away with the loops altogether and write it all out longhand, what would it look like? Well, let's start with the inner `c` loop. That loops from 0 to 7 (while less than 8), so replacing that loop with 8 discrete calls to the function replacing `c` each time would end up with:

```
int r = 0;
while (r < 8) {
    lc.setLed(0, r, 0, HIGH);
    lc.setLed(0, r, 1, HIGH);
    lc.setLed(0, r, 2, HIGH);
    lc.setLed(0, r, 3, HIGH);
    lc.setLed(0, r, 4, HIGH);
    lc.setLed(0, r, 5, HIGH);
    lc.setLed(0, r, 6, HIGH);
    lc.setLed(0, r, 7, HIGH);
    r++;
}

```

We could take it a step further and *unroll* the outer `r` loop. A subset of what you would end up with would be like this (note, I have skipped a lot of the middle ones):

```
lc.setLed(0, 0, 0, HIGH);
lc.setLed(0, 0, 1, HIGH);
lc.setLed(0, 0, 2, HIGH);
lc.setLed(0, 0, 3, HIGH);
lc.setLed(0, 0, 4, HIGH);
lc.setLed(0, 0, 5, HIGH);
lc.setLed(0, 0, 6, HIGH);
lc.setLed(0, 0, 7, HIGH);
lc.setLed(0, 1, 0, HIGH);
lc.setLed(0, 1, 1, HIGH);
... skipped a lot ...
lc.setLed(0, 6, 6, HIGH);
lc.setLed(0, 6, 7, HIGH);
lc.setLed(0, 7, 0, HIGH);
lc.setLed(0, 7, 1, HIGH);
lc.setLed(0, 7, 2, HIGH);
lc.setLed(0, 7, 3, HIGH);
lc.setLed(0, 7, 4, HIGH);
lc.setLed(0, 7, 5, HIGH);
lc.setLed(0, 7, 6, HIGH);
lc.setLed(0, 7, 7, HIGH);

```

There would, of course, be 8 × 8 = 64 entries in there.

`for` loops can be used in lots of other fun ways too. It's not just a simple "run this X number of times". For instance, you can loop through a C string until you reach the NULL character at the end of the string:

```
for (char *p = str; *p != 0; p++) {
    ... do something with *p
}

```

You can iterate through the entries in a linked list:

```
for (struct mylist *scan = myListHead; scan; scan = scan->next) {
    ... do something to scan->whatever ...
}

```

You can even embed functions in there:

```
for (char c = 0; c != '\n'; c = Serial.read()) {
    ... Do something with character `c` until `c` is a line feed ...
}

```

As you can see `for` is an incredibly powerful and flexible tool that is often overlooked in favour of the more explicit `while`.
> 3 votes

# Answer
What you have there is a nested loop. The first `for` statement runs 8 times, incrementing `r` from 0 to 7. For *each* of those 8 iterations the second `for` statement runs, incrementing `c` from 0 to 7. Thus the `setLed` statement is executed 64 times.

> Will it continue to run till both statements are true?

Yes. Unless you have a `break` or `return` statement somewhere in the part of the code you haven't shown.

Strictly-speaking, a *statement* does not become true. They will run while the test inside the `for` remains true (both tests).

This is standard C++ or C programming. You may wish to consult a C tutorial if you find this sort of thing puzzling.
> 2 votes

---
Tags: programming, c++, sketch
---


# Question
Title: serial communication between several arduinos to pc
Is possible the communication between several Arduinos to one serial port in the PC ?

If I have ARD\_A, ARD\_B,... ARD\_Z running with some code like this

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

void loop()
{
    while (Serial.available() > 0)
    {
       String stringID = Serial.read()
       int nFound = stringID.indexOf("@ARD_01");
                    // ---> Id is unique for each arduino
       if ( nFound > 0 )
          Serial.print("this is @ARD_01 responding sending some data");
     }
}

```

And in the pc there is an exe sending a string:

```
"@ARD_01 I want your data"
   process the data
"@ARD_02 I want your data"
   process the data
"@ARD_03 I want your data"
   process the data

```

# Answer
> 2 votes
Not directly, no. A PC's serial port - either a "real" one or a USB one, can only communicate with one device.

The Arduino, though, is a USB device, so you can just plug them all into a USB hub or a bunch of hubs - each one will get its own COM port. Managing all those COM ports can be kind of tricky though, especially when you have a lot of devices.

Another option, one that is more widely used when you want to communicate with a lot of *slave* devices from one *master* device is to use a *multidrop* network. RS-485 is the most popular of these. It allows you to connect many slave devices to one set of serial wires and the master sends instructions to a slave, and the slave may respond with data and information on request.

RS-485 requires special hardware to interface normal TTL level RS-232 (UART) ports to the bus.

You can read more about RS-485 here: https://en.wikipedia.org/wiki/RS-485

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


title: NRF24 Mixing with/without antenna

text:
# Question
Title: NRF24 Mixing with/without antenna
Is it possible to have the NRF24 module on an Arduino Mini transmitting to an NRF24 with SMA antenna on a Mega? In that case, would the antenna on the Mega help pickup the signal of the transmitting Arduino Mini?

# Answer
> 3 votes
Yes, and yes.

A module without an antenna is exactly the same as a module with an antenna, it's just that the antenna is part of the PCB. Yes, the module with the antenna will have more sensitivity (able to receive fainter signals) as well as more transmitting power.

The same is true of the modules with the power amplifier. They again have even more sensitivity and transmitting power.

It is quite common to have a single powerful transceiver with power amplifier and antenna as a base station and then smaller modules as the remote slave devices. Especially if you couple the base station with a suitable parabolic or uni-directional high gain antenna to point directly at where the slave devices are.

---
Tags: nrf24l01+
---


title: Atmega168 Watchdog timer

text:
# Question
Title: Atmega168 Watchdog timer
I'm trying to use the watchdog timer to prevent the atmel from being stuck in a loop.

Right now, I have the watchdog timer in System Reset Mode, with a 8sec timer. I reset the timer in every loop while the system is active. But when it goes to sleep, it cannot clear the timer and the whole system resets. Essentially, the system sleeps \> System Reset every 8 sec \> goes back to sleep.

While this works, I initialize a lot of other hardware with the atmel, and doing it every 8 second seems like a waste of resources.

I want to use the watchdog interrupt somehow only to wake the system up briefly and stop the full system reset. Only if it's truly stuck, it will do a full system reboot. But i'm not sure how the ISR will work or how to reset the timer or toggle.

Here a basic rundown of what I was thinking about.

```
ISR(wdt_timer)
{
    how to stop the full system reboot?
    how to make the interrupt start again?
}
ISR(button_press)
{
      gotoSleep=0;
}

void watchdog_init()
{
    /* Reset the wdt. */
  wdt_reset(); //from wdt.h

  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   */
  WDTCSR |= (1<<WDCE) | (1<<WDE);

  /* set new watchdog timeout prescaler value */
  WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */

  /* Enable the WD interrupt (note both interrupt and reset). */
  WDTCSR |= (1<<WDIE) | (1<<WDE);
}

void main ()
{
    watchdog_init();
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        reset_watchdog();

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        gotoSleep();

        //wake up here

    }

}

```

# Answer
> 3 votes
Each time the watchdog interrupt triggers, WDIE is reset. You will need to set it again in the loop if you want to continue capturing the interrupt rather than resetting the system.

Also, consider using `<avr/wdt.h>` and `<avr/sleep.h>` to handle (most of) the watchdog and sleep functionality.

```
EMPTY_INTERRUPT(WDT_vect);

void main ()
{
    watchdog_init();
    set_sleep_mode(SLEEP_MODE_STANDBY);
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        wdt_reset()

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        {
            sleep_enable();
            sleep_cpu();
            sleep_disable();
            WDTCSR |= _BV(WDIE);
        }
    }
}

```

---
Tags: interrupt, atmega328, timers, avr
---


title: What is Serial.begin(9600)?

text:
# Question
Title: What is Serial.begin(9600)?
I know that this is to initialize something:

```
Serial.begin(9600);

```

But I want to know what it really means?

# Answer
> 25 votes
`Serial.begin(9600)` doesn't actually print anything. For that you'd want to use `Serial.print("Hello world!")` to print the text "Hello world!" to the serial console. Rather it initializes the serial connection at 9600 bits per second.

Both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.

9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: `Serial.begin(57600)` would set the Arduino to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Arduino IDE's serial monitor) to the same speed in order to see the data being sent.

# Answer
> 23 votes
A picture is worth 1000 words, so they say, (1024 words if you work with computers) so I'll post some pictures ...

I set up my Uno to send "Fab" at 9600 baud and captured the results on a logic analyzer.

The parts shaded in red are the "idle" period between bytes.

From the above graphic note that the Tx (transmit) data line is normally high (1) until it drops low to indicate the start of a character (byte). This is the *start bit*. Then the 8 data bits (indicated by white dots) appear at the baud rate (9600 samples per second). After that the line is brought high again. This is the stop bit (the red part). Then we see the start bit for the next character, and so on. The "stop" portion can be indefinitely long, however it has to be at least one bit length.

---

More detail for the first character (the letter "F" or 0x46 or 0b01000110) can be seen here:

* A - no data (Tx is high)
* B - The "start bit". The line is taken low to tell the receiver that a character (byte) is commencing to be sent. The receiver waits for one and a half clock times before sampling the line.
* C - First character arrives (the letter "F" or 0x46 or 0b01000110). There is no clock bit as such, the incoming data is simply sampled at the baud (transmission) rate. In contrast to SPI communication the data arrives least-significant bit first (in case you are not sending 8 bits per byte). Thus we see 01100010 (rather than 01000110).
* D - The stop bit. This is always high, to ensure that we can distinguish between the end of this byte, and the start of the next one. Since the start bit is a zero, and the stop bit is a one, there is always a clear transition from one byte to the next.
* E - The start bit for the next character.

---

You can see from the logic analyzer capture that `T1 - T2` is 0.1041667 ms, and as it happens that is 1/9600:

```
1 / 9600 = 0.00010416666 seconds

```

Thus the rate of 9600 gives you the number of **bits per second** and the inverse is the **time interval between bits**.

---

## Other considerations

* Serial comms is not self-clocked (unlike SPI or I2C, and others) hence both sender and receiver have to agree on a clock rate.
* The clock rate is not exact on the Arduino, because the hardware has to divide the system clock down to get a serial clock, and the division is not always exact. There is almost always an error, the amount is given in the datasheet (figures quoted for a 16 MHz system clock, such as on the Uno):
* You can vary the number of data bits, you don't have to send 8 of them, in fact you can send 5 to 9 bits.
* There can optionally be a *parity* bit sent after the data bits.

+ If you specify "odd" parity, the parity bit is set in such a way that the total number of 1-bits is odd.
    + If you specify "even" parity, the parity bit is set in such a way that the total number of 1-bits is even.
    + If you specify no parity, the parity bit is omitted.

This can help the receiver detect if the data arrived correctly or not.
* The parity bit is sent before the stop bit.
* In the case of 9 data bits (as used in the SeaTalk protocol) the parity bit is re-purposed as a 9th data bit. Therefore you can't have both 9 data bits and a parity bit.
* You can also have two stop bits. This basically just lengthens the time between bytes. In the "olden days" this was so that slow electromechanical equipment could process the previous byte (eg. to print it).

---

### Possible corruption

If you start listening to serial data in the middle of a stream, it is quite possible that a 0-bit in the middle of the stream will be interpreted as a start bit, and then the receiver will interpret everything after that incorrectly.

The only real way to recover from this is to have a large enough gap, from time to time, (eg. 10 bits long) that this cannot happen.

---

### Inverted logic

The bits shown here (logic-level) are not inverted. That is, a 1-bit is HIGH and a 0-bit is LOW. If you have RS232 equipment that will probably be sending something like -12 V for a 1-bit, and +12 V for a 0-bit. This is inverted because a one is less than a zero, voltage-wise.

If you have such devices you need to do voltage conversion and logic inversion. Chips like the MAX232 will do both for you. They can also provide the -12 V needed to drive such equipment by generating it internally with the help of a few user-supplied capacitors.

---

### Speed rule-of-thumb

Since, with one start bit, 8 data bits, and one stop bit we have a total of 10 bits, as a quick rule of thumb, you can calculate the number of **bytes** you can transmit in a second by dividing the bit rate by 10.

Eg. At 9600 BPS you can send 960 bytes per second.

---

Code to reproduce:

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

void loop ()
  {
  }

```

# Answer
> 2 votes
;TLDR; It initializes the serial communication port and sets the baud rate. The device you're communicating with (or Arduino IDE Serial Monitor) have to be set to a matching baud rate. Once you've initialized the port you can begin sending or receiving characters. Arduino Serial Reference

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


# Question
Title: Control servo motors with buttons and via web application
I have this assignment and I have been tinkering a long time about it. I need to make a simulation of a parking lot where servos would represent the ramps.
I will be using 2 Arduinos running the same script, one representing the entry ramp and the other one the exit. Servos are controlled by reading a json request of an web application and manually by buttons. I have connected two LED's when the buttons are pressed. I would also need to make state when servo would be always up or always down (that would represent the off times of parking lot), should I add extra buttons for that? Any idea would be appreciated.
The problem I'm having with this project is that servos are not responding well on push buttons. They are shaking and very slow moving. And I think that it isn't a good solution to move the servos while they are sending application request because it can lead to conflict. Please help me there.
I have written pretty major piece of script, but it still needs adjusments. Any help is welcomed. Here is the code:

```
#include<Servo.h>
#include<Ethernet.h>
#include <SPI.h>

Servo myservo;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "ramp-rampcontrol.rhcloud.com";
EthernetClient client;
IPAddress ip(192,168,1,17);

int button_5 = 5;
int button_6 = 6;
const int ledPin = 3;
const int ledPinG = 2;
int time = 5*1000;
int val=0;
String content = "";
boolean begin1 = false;

void setup() {

Serial.begin(9600);
pinMode(button_5, INPUT);
pinMode(button_6, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(ledPinG, OUTPUT);
myservo.attach(9);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");

// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
 }
}

void loop()
{

val = digitalRead(button_5);
if (val == HIGH)
{
  performServoAction("up");

      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite(ledPin, LOW);
      delay(1000);

}

val = digitalRead(button_6);
if (val == HIGH)
{
  performServoAction("down");

      digitalWrite(ledPinG, HIGH);
      delay(1000);
      digitalWrite(ledPinG, LOW);
      delay(1000);
 }

 while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    performAction();
  }
  }

bool performServoAction(String action_type) {
if (action_type == "up") {
    Serial.println("doing up");
    myservo.write(95);
    delay(time);
   // lastRampStatus = action_type ;
   // notifyServerAboutAction("true", action_id);
    return true;
  }

  if (action_type == "down") {
    Serial.println("doing down");
    myservo.write(135);
    delay(time);
    //lastRampStatus = action_type;
  // notifyServerAboutAction("true", action_id);
    return true;
  }
}

 void performAction() {
  int nstart = content.indexOf("action_id") + 12;
  int nend = content.indexOf(",", nstart);
  String actionID = content.substring(nstart, nend);

    int nstart1 = content.indexOf("action_type") + 14;
   //Get position of "action_type" in a string, increment by 13
    (length of 'action_type":"')
    int nend1 = content.indexOf("\"", nstart1); // Get next position
    of '"' starting from nstart
    String actionType = content.substring(nstart1, nend1);
    //Return substring between this position
    performServoAction(actionType);
    Serial.println(nstart1);
    Serial.println(nend1);
    Serial.println(actionID);
    Serial.println(actionType);
    Serial.println(content);
}

```

# Answer
Instead of using:

`myservo.write(135);`

You should use:

`myservo.writeMicroseconds();`

https://www.arduino.cc/en/Reference/ServoWriteMicroseconds
> 1 votes

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


# Question
Title: Integrating two Arduino Ethernet libraries in one sketch
I am trying to integrate two different Arduino Ethernet libraries, EtherShield and UIPEthernet in one sketch.

EtherShield library is used to control LEDs via Android mobile application. While UIPEthernet is used to control the same LEDs via Web Server.

Both codes run perfectly when they're uploaded individually. But I need them to run in a single sketch. So I combined them in one sketch. That's where my problem is. They're not running smoothly anymore. My mobile app can only turn one LED off then the app will crash. Accessing my Arduino's web server gives me error as well (but before it is really, really working T.T)

Help me, please. This is my code

```
// ========== UIPEthernet library
#include <Dhcp.h>
#include <Dns.h>
#include <ethernet_comp.h>
#include <UIPClient.h>
#include <UIPEthernet.h>
#include <UIPServer.h>
#include <UIPUdp.h>

// ========== EtherShield library
#include "EtherShield.h"
#include "ETHER_28J60.h"

// ========== MOBILE
//static uint8_t mac[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
//static uint8_t ip[4] = {192, 168, 15, 97};
static uint16_t port = 80;

ETHER_28J60 e;

// ========== WEB
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 15, 97 };
byte gateway[] = { 192, 168, 15, 1 };
byte subnet[] = { 255, 255, 255, 0 };

String inString = String(35);

int i;  // Used for looping
String Room;

int pin[] = { 0, 2, 3, 4, 5 }; // Lock pin num 0 in array is not used
int numOfRooms = 4; // Number of rooms
String value[] = { "OPEN", "OPEN", "OPEN", "OPEN", "OPEN" }; // Startup all rooms are closed

EthernetServer server(port);
String data;

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

  // ========== MOBILE
  e.setup(mac, ip, port);

  // ========== WEB
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();

  // Set pin mode
  for (int j = 1; j < (numOfRooms + 1); j++)
  {
    pinMode(pin[j], OUTPUT);
  }

  Serial.println("\n[ WEB + MOBILE ]\n");
  Serial.println("Serial READY");
  Serial.println("Ethernet READY");
  Serial.println("Server READY\n");
}

void loop()
{
  webModule();
  mobileAppModule();
}

void mobileAppModule()
{
char* params;
if (params = e.serviceRequest())
{

  //ROOM 311
  if (strcmp(params, "?cmd=1") == 0)
  {
        digitalWrite(pin[1], HIGH);
        Serial.println("ROOM311 is OPEN\n");
  }
  if (strcmp(params, "?cmd=2") == 0)
  {
        digitalWrite(pin[1], LOW);
        Serial.println("ROOM311 is CLOSE\n");
  }

  //ROOM 312
  if (strcmp(params, "?cmd=3") == 0)
  {
        digitalWrite(pin[2], HIGH);
        Serial.println("ROOM312 is OPEN\n");
  }
  if (strcmp(params, "?cmd=4") == 0)
  {
        digitalWrite(pin[2], LOW);
        Serial.println("ROOM312 is CLOSE\n");
  }

  //ROOM 313
  if (strcmp(params, "?cmd=5") == 0)
  {
        digitalWrite(pin[3], HIGH);
        Serial.println("ROOM313 is OPEN\n");
  }
  if (strcmp(params, "?cmd=6") == 0)
  {
        digitalWrite(pin[3], LOW);
        Serial.println("ROOM313 is CLOSE\n");
  }

  //ROOM 314
  if (strcmp(params, "?cmd=7") == 0)
  {
        digitalWrite(pin[4], HIGH);
        Serial.println("ROOM314 is OPEN\n");
  }
  if (strcmp(params, "?cmd=8") == 0)
  {
        digitalWrite(pin[4], LOW);
        Serial.println("ROOM314 is CLOSE\n");
  }

  //
  if (strcmp(params, "?cmd=9") == 0)
  {
        digitalWrite(pin[1], LOW);
        digitalWrite(pin[2], LOW);
        digitalWrite(pin[3], LOW);
        digitalWrite(pin[4], LOW);
        Serial.println("All rooms are now CLOSED\n");
  }

  e.respond();
  }
}

void webModule()
{
     EthernetClient client = server.available();

 if (client)
 {
 // An HTTP request ends with a blank line
 boolean current_line_is_blank = true;

 while (client.connected())
 {
  if (client.available())
  {
    char c = client.read();
    // If users have gotten to the end of the line (received a newline
    // character) and the line is blank, the HTTP request has ended,
    // so users can send a reply

    if (inString.length() < 35)
    {
      inString.concat(c);
    }

    if (c == '\n' && current_line_is_blank)
    {

      // Send a standard HTTP response header
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();

      client.println("<html>");

      client.println("<head><title>CONTROL PANEL</title></head>");

      client.println("<body style='padding: 0; margin: 0;' onunload='window.opener.document.getElementById('controlPanel').disabled = false;'>");

      client.println("<div style='width: 100%; height: auto; background-color: #000000;'><center style='font-size: 18px; font-family: Impact; color: white;'>POLYTECHNIC UNIVERSITY OF THE PHILIPPINES<br />COLLEGE OF ENGINEERING<br />COMPUTER ENGINEERING DEPARTMENT<br /></center><center style='font-size: 30px; font-family: Impact; color: #FF9600;'>COMPUTER ENGINEERING LABORATORY</center></div>");
      client.println("<div style='width: 100%; height: 10px; background-color: gray;'></div>");
      client.println("<div style='width: 100%; height: 10px; background-color: #FF9600;'></div><br />");
      client.println("<div style='width: 80%; height: auto; background-color: #FF9600; border-radius: 20px; margin: auto; padding: 5px;'>");
      client.println("<div style='width: auto; height: auto; background-color: #FFFFFF; border-radius: 20px; margin: auto; padding: 5px;'><br /><center style='font-size: 30px; font-family: Impact;'>CONTROL PANEL</center><br /><hr /><br />");

      client.println("<form method=get>");

      for (i = 1; i < (numOfRooms + 1) ; i++)
      {
        Room = String("ROOM") + (i + 310);

        if (inString.indexOf(Room + "=OPEN") > 0 || inString.indexOf("All=OPEN") > 0)
        {
          Serial.println("\n" + Room + " is OPEN");
          digitalWrite(pin[i], HIGH);
          value[i] = "CLOSE";
        }
        else if (inString.indexOf(Room + "=CLOSE") > 0 || inString.indexOf("All=CLOSE") > 0)
        {
          Serial.println("\n" + Room + " is CLOSE");
          digitalWrite(pin[i], LOW);
          value[i] = "OPEN";
        }

        client.println("<br /><center style='font-family: Impact;'>" + Room + "     <input type='submit' name=" + Room + " value=" + value[i] + " style='height: 50px; width:100px;' /><br /><br />");
      }

      client.println("<br /><br />All <input type='submit' name='All' value='OPEN' style='height: 50px; width:100px;' />    <input type='submit' name='All' value='CLOSE' style='height: 50px; width:100px;' />");
      client.println("</center></form>");

      for (i = 1; i < (numOfRooms + 1); i++)
      {
        if (value[i] == "ON")
        {
          i = i + 310;
          client.println("<br /><br /><p>Room " + String(i + 310) + " is OPEN</p>");
        }
        else if (value[i] == "OFF")
        {
          client.println("<p><p>Room " + String(i + 310) + " is CLOSE");
        }
      }
      client.println("</div>");
      client.println("</div>");
      client.println("</body></html>");
      break;
    }

    if (c == '\n')
    {
      // we're starting a new line
      current_line_is_blank = true;
    }
    else if (c != '\r')
    {
      // we've gotten a character on the current line
      current_line_is_blank = false;
    }
  }
}

    // give the web browser time to receive the data
    delay(1);
    inString = "";
    client.stop();
    }
}

```

MOBILE means code for Arduino-Android WEB means the code for Web Server

# Answer
You can't.

1. The code has both libraries trying to run on the same port which is not allowed (in fact you couldn't even do that on a computer). You could try setting one to one port and the other to another port, but that might not work because...
2. These libraries most likely are both expecting to be the only code accessing the hardware and they will step over each other and cause problems. Sharing hardware between different pieces of code is an advanced programming topic not suited for beginners and would involve rewriting significant portions of these libraries.

The best course of action is to either re-implement your app functionality to use the UIPEthernet Library, or re-implement the webpage using the EtherShield library. You should be able to do this because your app interface is supplying parameters (e.g the "?cmd=" part) and the webpage is not. You should be able to set it up so that if it has "?cmd=" in the request, it should perform the command, otherwise it should return the webpage.
> 0 votes

---
Tags: arduino-uno, arduino-ide, ethernet, library
---


title: HC-06 data receiving

text:
# Question
Title: HC-06 data receiving
I've written a script in Python which sends data through the PC's Bluetooth to HC-06 on Arduino.

`state` is an integer from 0 to 1000 (it is controlled through the potentiometer).

```
...
gaugeSocket.send(str(state))
...

```

I can't get the right character-to-integer conversion on Arduino (from HC-06 serial).

Arduino code:

```
SoftwareSerial mySerial(10, 11); // RX, TX
char buf[2];
int i=0;
int data;
int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(57600);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    for(;i<2;){
      buf = mySerial.read();
      i++;
    }
    i = 0;
    Serial.print(buf);
    data = atoi(buf);
  }
    analogWrite(ledPin, data/10); //To see how code behaves on LED
}

```

Serial print gives me this (if I turn potentiometer from 0 to 1000):

> 0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(60(1ÿ(00(16(0ÿ(23(0ÿ(30(0ÿ(3ÿ(60(43(0ÿ(49(0ÿ(53(0ÿ(5ÿ(90(69(0ÿ(88(0ÿ(10(00(10(00(10(

What am I missing? Is it because I'm sending it as a string? Or is my buffer not the correct size?

# Answer
> 1 votes
Here is your main problem:

```
if (mySerial.available()) {
    for(;i < 2;){
        buf = mySerial.read();
        i++;
    }
....

```

There you are saying "If there is at least one character available in the buffer then read lots of characters from the buffer".

*You can't read characters that aren't there yet.*

So your stream of data is interspersed with the integer `-1` which means "I don't have any data to read!"

I explain it all here: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

By the way - character -1 looks like this: ÿ

You are sending your data as text. That means, to send the value 348 you are first sending the byte representation of the ASCII character "3", which is the decimal byte value 51. Then you send the byte representation of the ASCII character "4", which is the decimal value 52, and finally you send the byte representation of the ASCII character "8", which is the decimal value 56.

You look to see if there is one byte available (if(mySerial.available())) and then read that byte into "buf" and increment "i" (by the way, "i" is never reset to 0 - your whole loop strategy is completely wrong, but that's a completely different issue). You then read a second character and assign that to buf instead.

So if you have the character "3" in the serial buffer you then place that in "buf". You then read whatever is next in the buffer, which 9 times out of 10 will be nothing, so `read()` returns -1. So you just assign that to "buf" instead, replacing the "3" that was in there before.

But "buf" is a character array, and you are assigning a character to the whole array, which makes absolutely no sense (does the code even compile as you have shown it?).

Basically your whole reading routine is completely wrong and can never work no matter how much tweaking and advising we do.

The link I provided above describes not only how you should do the reading on the Arduino, but also how you should do the sending from the other end. It is vitally important that you send something that says "This is the end of the number I am sending" so that the Arduino knows where one number ends and the next starts. Normally that is done, when sending a textual representation of the number like this, by adding a line feed and/or carriage return at the end of your number. So instead of sending "348" you send "248\n".

The Arduino then checks to see if there is one character available, and then it adds *just that one* character to the end of the buffer. If, and only if, that character is the *delimiting* character then you can take the buffer and translate it into an actual number and reset your buffer to be empty ready to receive the next number.

The link above has good example code showing you exactly how to do that.

# Answer
> 0 votes
Use `itoa` instead of `str`.

`str` just converts the byte to an ASCII character. So `48` will become `'0'`, `195` will become `'ÿ'`, and `191` will become `'('`.

# Answer
> 0 votes
I think you should check your baud rates. A mismatch in baud rates usually makes that symbol get printed on the screen.

---
Tags: serial, c++, bluetooth, softwareserial
---


# Question
Title: How to reset Arduino Uno over BLE just like over USB?
I'm working on wireless upload to Arduino and i've succeed for Mega2560. But when trying to upload to Uno it does not wait for upload commands. I'm doing reset using GPIO and HM-10 BLE module wired with capacitor and resistor and wired to MCU's reset pin just it's done for USB. I think it remembers somehow how it was reset - by pressing hardware RESET button, by USB DTR/RTS or other way. The problem is that when resetting for USB it waits for upload commands after reset and for BLE it does not.

I've viewed optiboot bootloader code but i'm not sure i understand it correctly. Any clue on how to do it?

Update1:

```
2015-09-05 15:51:36.682 xctest[60180:7754033] [TRACE  ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 1 [0x31]
2015-09-05 15:51:36.682 xctest[60180:7754033] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-05 15:51:36.735 xctest[60180:7754033] [DEBUG  ] [OUT]: Sending 8 bytes
2015-09-05 15:51:36.736 xctest[60180:7754033] [TRACE  ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 0 [0x30]
2015-09-05 15:51:36.736 xctest[60180:7754033] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-05 15:51:36.788 xctest[60180:7754033] [DEBUG  ] [   ]: Draining for 300 ms ...
2015-09-05 15:51:36.788 xctest[60180:7754033] [TRACE  ] [IN ]: Start reading
2015-09-05 15:51:37.053 xctest[60180:7754082] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-05 15:51:37.053 xctest[60180:7754082] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-05 15:51:37.093 xctest[60180:7754033] [TRACE  ] [IN ]: Finish reading
2015-09-05 15:51:37.093 xctest[60180:7754033] [TRACE  ] [IN ]: Ble clear buffer
2015-09-05 15:51:37.093 xctest[60180:7754033] [DEBUG  ] [IN ]: Drained 18 bytes
2015-09-05 15:51:37.094 xctest[60180:7754033] [DEBUG  ] [OUT]: Sending 2 bytes
2015-09-05 15:51:37.094 xctest[60180:7754033] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
2015-09-05 15:51:37.094 xctest[60180:7754033] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-05 15:51:37.095 xctest[60180:7754033] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-05 15:51:37.096 xctest[60180:7754033] [TRACE  ] [IN ]: Start reading
2015-09-05 15:51:37.450 xctest[60180:7754084] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-05 15:51:37.450 xctest[60180:7754084] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-05 15:51:37.450 xctest[60180:7754084] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-05 15:51:37.452 xctest[60180:7754033] [TRACE  ] [IN ]: Finish reading
2015-09-05 15:51:37.452 xctest[60180:7754033] [TRACE  ] [IN ]: Receive: . [0x14]
2015-09-05 15:51:37.452 xctest[60180:7754033] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-05 15:51:37.453 xctest[60180:7754033] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-05 15:51:37.453 xctest[60180:7754033] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-05 15:51:37.454 xctest[60180:7754033] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
2015-09-05 15:51:37.454 xctest[60180:7754033] [TRACE  ] [IN ]: Start reading
2015-09-05 15:51:37.454 xctest[60180:7754033] [TRACE  ] [IN ]: Finish reading
2015-09-05 15:51:37.455 xctest[60180:7754033] [TRACE  ] [IN ]: Receive: . [0x10]
2015-09-05 15:51:37.455 xctest[60180:7754033] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-05 15:51:37.455 xctest[60180:7754033] [TRACE  ] [IN ]: Ble clear buffer
2015-09-05 15:51:37.455 xctest[60180:7754033] [DEBUG  ] [OUT]: Sending 3 bytes
2015-09-05 15:51:37.456 xctest[60180:7754033] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
2015-09-05 15:51:37.456 xctest[60180:7754033] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-05 15:51:37.457 xctest[60180:7754033] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-05 15:51:37.457 xctest[60180:7754033] [TRACE  ] [IN ]: Start reading
2015-09-05 15:51:37.701 xctest[60180:7754084] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-05 15:51:37.701 xctest[60180:7754084] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-05 15:51:38.451 xctest[60180:7754082] [TRACE  ] [IN ]: Rx value received 5 bytes: h [0x68] e [0x65] l [0x6C] l [0x6C] o [0x6F]
2015-09-05 15:51:38.452 xctest[60180:7754033] [TRACE  ] [IN ]: Finish reading

```

Update 2 (this is uploading to Uno over USB log):

```
2015-06-29 16:34:10.829 xctest[36585:3703900] [TRACE  ] [   ]: DTR/RTS supported by Serial, resetting
2015-06-29 16:34:11.140 xctest[36585:3703900] [DEBUG  ] [IN ]: Draining ...
2015-06-29 16:34:11.392 xctest[36585:3703900] [DEBUG  ] [IN ]: Drain done
2015-06-29 16:34:11.392 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 2 bytes
2015-06-29 16:34:11.392 xctest[36585:3703900] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
2015-06-29 16:34:11.393 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.531 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.531 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.532 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.532 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 3 bytes
2015-06-29 16:34:11.532 xctest[36585:3703900] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
2015-06-29 16:34:11.533 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.535 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.536 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.536 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x04]
2015-06-29 16:34:11.536 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.536 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.537 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 3 bytes
2015-06-29 16:34:11.537 xctest[36585:3703900] [TRACE  ] [OUT]: Send: A [0x41] . [0x82]   [0x20]
2015-06-29 16:34:11.537 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.540 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.540 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.540 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x04]
2015-06-29 16:34:11.540 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.541 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.541 xctest[36585:3703900] [DEBUG  ] [   ]: STK500:initialize: n_extparms = 4
2015-06-29 16:34:11.541 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 22 bytes
2015-06-29 16:34:11.542 xctest[36585:3703900] [TRACE  ] [OUT]: Send: B [0x42] . [0x86] . [0x00] . [0x01] . [0x00] . [0x01] . [0x01] . [0x01] . [0x03] . [0xFF] . [0xFF] . [0xFF] . [0xFF] . [0x00] . [0x80] . [0x04] . [0x00] . [0x00] . [0x00] . [0x80] . [0x00]   [0x20]
2015-06-29 16:34:11.542 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.548 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.548 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.548 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.548 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 7 bytes
2015-06-29 16:34:11.549 xctest[36585:3703900] [TRACE  ] [OUT]: Send: E [0x45] . [0x05] . [0x04] . [0xD7] . [0xC2] . [0x00]   [0x20]
2015-06-29 16:34:11.549 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.552 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.552 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.552 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.553 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 2 bytes
2015-06-29 16:34:11.553 xctest[36585:3703900] [TRACE  ] [OUT]: Send: P [0x50]   [0x20]
2015-06-29 16:34:11.553 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.556 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.556 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.556 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.569 xctest[36585:3703900] Reading |                                                    | 0% 0ms
2015-06-29 16:34:11.570 xctest[36585:3703900] [DEBUG  ] [OUT]: Sending 2 bytes
2015-06-29 16:34:11.571 xctest[36585:3703900] [TRACE  ] [OUT]: Send: u [0x75]   [0x20]
2015-06-29 16:34:11.571 xctest[36585:3703900] [DEBUG  ] [IN ]: Receiving 5 bytes
2015-06-29 16:34:11.572 xctest[36585:3703900] [TRACE  ] [IN ]: Received: . [0x14] . [0x1E] . [0x95] . [0x0F] . [0x10]
2015-06-29 16:34:11.572 xctest[36585:3703900] Reading | ################################################## | 100% 2ms

```

Update 3:

i've modified bootloader (optiboot) to wait 4 seconds (instead of 1 second by default) and added blinking when character 0x41 (STK\_GET\_PARAMETER) arrives. Also i've uploaded 'echo' sketch to return what back everything that is sent to the board.

bootloader modifications (part):

```
// Set up watchdog to trigger after 4s
  watchdogConfig(WATCHDOG_4S); // 4ntoine: was WATCHDOG_1s

  /* Set LED pin as output */
  LED_DDR |= _BV(LED);

#ifdef SOFT_UART
  /* Set TX pin as output */
  UART_DDR |= _BV(UART_TX_BIT);
#endif

// #if LED_START_FLASHES > 0
  /* Flash onboard LED to signal entering of bootloader */
  // flash_led(2); // 4ntoine
// #endif

  /* Forever loop */
  for (;;) {
    /* get character from UART */
    ch = getch();

    if(ch == STK_GET_PARAMETER) {
      flash_led(2); // 4ntoine

      unsigned char which = getch();
      verifySpace();

      if (which == 0x82) {
         /*
           * Send optiboot version as "minor SW version"
           */
         putch(OPTIBOOT_MINVER);
      } else if (which == 0x81) {
           putch(OPTIBOOT_MAJVER);
      } else {
    /*
     * GET PARAMETER returns a generic 0x03 reply for
         * other parameters - enough to keep Avrdude happy
     */
    putch(0x03);
      }
    }

```

uploaded arduino sketch:

```
int LED = 13;

void setup() {
  // avoid misleading blinking
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);

  // to let us know when sketch starts
  Serial.begin(115200);
  Serial.write("hello");
}

void loop() {
  while (Serial.available()) {
    int incomingByte = Serial.read();
    Serial.write(incomingByte);
  }

}

```

log:

```
2015-09-13 20:52:57.011 xctest[55099:2968978] [INFO   ] [   ]: Found peripheral: <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = disconnected>
2015-09-13 20:52:57.011 xctest[55099:2968978] [DEBUG  ] [   ]: Stop scanning
2015-09-13 20:52:57.012 xctest[55099:2968978] [INFO   ] [   ]: Connecting to <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = disconnected>
2015-09-13 20:52:57.236 xctest[55099:2968989] [DEBUG  ] [   ]: Connected to peripheral <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = connected>
2015-09-13 20:52:57.238 xctest[55099:2968989] [TRACE  ] [   ]: Discovered services for peripheral <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = connected>
2015-09-13 20:52:57.238 xctest[55099:2968989] [DEBUG  ] [   ]: Discovered service <CBService: 0x10010d950>
2015-09-13 20:52:57.381 xctest[55099:2968989] [TRACE  ] [   ]: Discovered characteristics for service <CBService: 0x10010d950>
2015-09-13 20:52:57.381 xctest[55099:2968989] [TRACE  ] [   ]: Discovered characteristic <CBCharacteristic: 0x100304d10>
2015-09-13 20:52:57.382 xctest[55099:2968989] [DEBUG  ] [   ]: Tx characteristic supports WriteWithResponse: NO
2015-09-13 20:52:57.382 xctest[55099:2968989] [TRACE  ] [   ]: Subscribing to Rx value
2015-09-13 20:52:57.392 xctest[55099:2968940] [INFO   ] [   ]: Connected successfully
2015-09-13 20:52:57.392 xctest[55099:2968940] [TRACE  ] [   ]: DTR/RTS supported by Serial, resetting
2015-09-13 20:52:57.392 xctest[55099:2968940] [TRACE  ] [   ]: Waiting until subscribed to Rx value ...
2015-09-13 20:52:58.387 xctest[55099:2968989] [DEBUG  ] [IN ]: Updated notifications state for RX characteristic: isNotifying=YES
2015-09-13 20:52:58.408 xctest[55099:2968940] [DEBUG  ] [OUT]: Sending 8 bytes
2015-09-13 20:52:58.408 xctest[55099:2968940] [TRACE  ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 1 [0x31]
2015-09-13 20:52:58.408 xctest[55099:2968940] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-13 20:52:58.463 xctest[55099:2968940] [DEBUG  ] [OUT]: Sending 8 bytes
2015-09-13 20:52:58.463 xctest[55099:2968940] [TRACE  ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 0 [0x30]
2015-09-13 20:52:58.463 xctest[55099:2968940] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-13 20:52:58.518 xctest[55099:2968940] [DEBUG  ] [   ]: Draining for 300 ms ...
2015-09-13 20:52:58.518 xctest[55099:2968940] [TRACE  ] [IN ]: Start reading
2015-09-13 20:52:58.784 xctest[55099:2968989] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-13 20:52:58.785 xctest[55099:2968989] [WARNING] [IN ]: Removing 'OK+PIO2:1' (9 bytes) from incoming buffer (9 bytes)
2015-09-13 20:52:58.785 xctest[55099:2968989] [WARNING] [IN ]: Got 0 bytes in incoming buffer
2015-09-13 20:52:58.786 xctest[55099:2968989] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-13 20:52:58.786 xctest[55099:2968989] [WARNING] [IN ]: Removing 'OK+PIO2:0' (9 bytes) from incoming buffer (9 bytes)
2015-09-13 20:52:58.787 xctest[55099:2968989] [WARNING] [IN ]: Got 0 bytes in incoming buffer
2015-09-13 20:52:58.820 xctest[55099:2968940] [TRACE  ] [IN ]: Finish reading
2015-09-13 20:52:58.820 xctest[55099:2968940] [TRACE  ] [IN ]: Ble clear buffer
2015-09-13 20:52:58.821 xctest[55099:2968940] [DEBUG  ] [IN ]: Drained 0 bytes
2015-09-13 20:52:58.821 xctest[55099:2968940] [DEBUG  ] [OUT]: Sending 2 bytes
2015-09-13 20:52:58.821 xctest[55099:2968940] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
2015-09-13 20:52:58.821 xctest[55099:2968940] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-13 20:52:58.822 xctest[55099:2968940] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-13 20:52:58.822 xctest[55099:2968940] [TRACE  ] [IN ]: Start reading
2015-09-13 20:52:59.193 xctest[55099:2968978] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-13 20:52:59.193 xctest[55099:2968978] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-13 20:52:59.193 xctest[55099:2968978] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-13 20:52:59.194 xctest[55099:2968978] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-13 20:52:59.194 xctest[55099:2968940] [TRACE  ] [IN ]: Finish reading
2015-09-13 20:52:59.195 xctest[55099:2968940] [TRACE  ] [IN ]: Receive: . [0x14]
2015-09-13 20:52:59.195 xctest[55099:2968940] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-13 20:52:59.195 xctest[55099:2968940] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-13 20:52:59.196 xctest[55099:2968940] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-13 20:52:59.196 xctest[55099:2968940] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
2015-09-13 20:52:59.196 xctest[55099:2968940] [TRACE  ] [IN ]: Start reading
2015-09-13 20:52:59.196 xctest[55099:2968940] [TRACE  ] [IN ]: Finish reading
2015-09-13 20:52:59.197 xctest[55099:2968940] [TRACE  ] [IN ]: Receive: . [0x10]
2015-09-13 20:52:59.197 xctest[55099:2968940] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-13 20:52:59.197 xctest[55099:2968940] [TRACE  ] [IN ]: Ble clear buffer
2015-09-13 20:52:59.198 xctest[55099:2968940] [DEBUG  ] [OUT]: Sending 3 bytes
2015-09-13 20:52:59.198 xctest[55099:2968940] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
2015-09-13 20:52:59.198 xctest[55099:2968940] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-13 20:52:59.199 xctest[55099:2968940] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-13 20:52:59.199 xctest[55099:2968940] [TRACE  ] [IN ]: Start reading
2015-09-13 20:52:59.268 xctest[55099:2968978] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-13 20:52:59.268 xctest[55099:2968978] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-13 20:53:02.955 xctest[55099:2968940] [ERROR  ] [OUT]: BLE read timeout: 3.000965 (timeout = 3.000000)
2015-09-13 20:53:02.955 xctest[55099:2968940] [TRACE  ] [IN ]: Finish reading
2015-09-13 20:53:02.955 xctest[55099:2968940] [TRACE  ] [IN ]: Ble clear buffer
2015-09-13 20:53:02.955 xctest[55099:2968940] [ERROR  ] [IN ]: STK500:receive: programmer is not responding
2015-09-13 20:53:02.956 xctest[55099:2968940] [DEBUG  ] [OUT]: Sending 3 bytes
2015-09-13 20:53:02.956 xctest[55099:2968940] [TRACE  ] [OUT]: Send: A [0x41] . [0x82]   [0x20]
2015-09-13 20:53:02.956 xctest[55099:2968940] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-13 20:53:02.956 xctest[55099:2968940] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-13 20:53:02.957 xctest[55099:2968940] [TRACE  ] [IN ]: Start reading
2015-09-13 20:53:03.018 xctest[55099:2968978] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-13 20:53:03.018 xctest[55099:2968978] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-13 20:53:03.280 xctest[55099:2968989] [TRACE  ] [IN ]: Rx value received 5 bytes: h [0x68] e [0x65] l [0x6C] l [0x6C] o [0x6F]
2015-09-13 20:53:03.280 xctest[55099:2968989] [WARNING] [IN ]: Got 5 bytes in incoming buffer
2015-09-13 20:53:03.281 xctest[55099:2968940] [TRACE  ] [IN ]: Finish reading

```

i can see blinking so the character arrives so the characters arrive correctly to the board. also i've tested wiring (sketch returns exactly the same as it was sent and it sends 'hello' after start). So i'm pretty sure: 1. characters arrive correctly to the bootloader 2. wiring is correct (as i can see back what i've sent - i'm using LightBlue mac app to open HM-10 as BLE device, subscribe to the characteristics and send characters and i can see it's changing to what i've sent). 3. bootloader waits for 4 seconds (i can see it in Arduino IDE terminal).

Update 4 :

my understanding now is that optiboot sets wrong baud rate for 115200 passed in bootloader mode as it replies with 0x11 and transmits characters correctly in sketch mode:

```
2015-09-17 09:39:25.628 xctest[60179:4253160] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-17 09:39:25.628 xctest[60179:4253160] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-17 09:39:25.629 xctest[60179:4253160] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-17 09:39:25.629 xctest[60179:4253160] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-17 09:39:25.630 xctest[60179:4253160] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:25.630 xctest[60179:4253160] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:27.351 xctest[60179:4253117] [TRACE  ] [IN ]: Finish reading
2015-09-17 09:39:27.351 xctest[60179:4253117] [TRACE  ] [IN ]: Ble clear buffer
2015-09-17 09:39:27.351 xctest[60179:4253117] [DEBUG  ] [IN ]: Drained 18 bytes
2015-09-17 09:39:27.352 xctest[60179:4253117] [DEBUG  ] [   ]: Draining incoming buffer (0 bytes)
2015-09-17 09:39:27.352 xctest[60179:4253117] [DEBUG  ] [OUT]: Sending 2 bytes
2015-09-17 09:39:27.352 xctest[60179:4253117] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
2015-09-17 09:39:27.353 xctest[60179:4253117] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-17 09:39:27.353 xctest[60179:4253117] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.353 xctest[60179:4253117] [TRACE  ] [IN ]: Start reading
2015-09-17 09:39:27.424 xctest[60179:4253160] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:27.424 xctest[60179:4253160] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:27.424 xctest[60179:4253149] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x11] . [0xFC]
2015-09-17 09:39:27.425 xctest[60179:4253149] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-17 09:39:27.425 xctest[60179:4253117] [TRACE  ] [IN ]: Finish reading
2015-09-17 09:39:27.425 xctest[60179:4253117] [TRACE  ] [IN ]: Receive: . [0x11]
2015-09-17 09:39:27.425 xctest[60179:4253117] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-17 09:39:27.426 xctest[60179:4253117] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-17 09:39:27.426 xctest[60179:4253117] [ERROR  ] [   ]: STK500:synchronize: attempt 1 of 3: no sync: received [0x11]
2015-09-17 09:39:27.426 xctest[60179:4253117] [DEBUG  ] [   ]: Draining incoming buffer (1 bytes)
2015-09-17 09:39:27.426 xctest[60179:4253117] [DEBUG  ] [OUT]: Sending 2 bytes
2015-09-17 09:39:27.427 xctest[60179:4253117] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
2015-09-17 09:39:27.427 xctest[60179:4253117] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-17 09:39:27.427 xctest[60179:4253117] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.427 xctest[60179:4253117] [TRACE  ] [IN ]: Start reading
2015-09-17 09:39:27.499 xctest[60179:4253160] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:27.499 xctest[60179:4253160] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:27.500 xctest[60179:4253160] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-17 09:39:27.500 xctest[60179:4253160] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-17 09:39:27.500 xctest[60179:4253117] [TRACE  ] [IN ]: Finish reading
2015-09-17 09:39:27.501 xctest[60179:4253117] [TRACE  ] [IN ]: Receive: . [0x14]
2015-09-17 09:39:27.501 xctest[60179:4253117] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-17 09:39:27.501 xctest[60179:4253117] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-17 09:39:27.501 xctest[60179:4253117] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.501 xctest[60179:4253117] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
2015-09-17 09:39:27.502 xctest[60179:4253117] [TRACE  ] [IN ]: Start reading
2015-09-17 09:39:27.502 xctest[60179:4253117] [TRACE  ] [IN ]: Finish reading
2015-09-17 09:39:27.502 xctest[60179:4253117] [TRACE  ] [IN ]: Receive: . [0x10]
2015-09-17 09:39:27.508 xctest[60179:4253117] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-17 09:39:27.509 xctest[60179:4253117] [TRACE  ] [IN ]: Ble clear buffer
2015-09-17 09:39:27.509 xctest[60179:4253117] [DEBUG  ] [OUT]: Sending 3 bytes
2015-09-17 09:39:27.509 xctest[60179:4253117] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
2015-09-17 09:39:27.509 xctest[60179:4253117] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-17 09:39:27.510 xctest[60179:4253117] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.510 xctest[60179:4253117] [TRACE  ] [IN ]: Start reading
2015-09-17 09:39:27.574 xctest[60179:4253149] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:27.574 xctest[60179:4253149] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:31.325 xctest[60179:4253117] [ERROR  ] [OUT]: BLE read timeout: 3.000965 (timeout = 3.000000)
2015-09-17 09:39:31.326 xctest[60179:4253117] [TRACE  ] [IN ]: Finish reading
2015-09-17 09:39:31.326 xctest[60179:4253117] [TRACE  ] [IN ]: Ble clear buffer
2015-09-17 09:39:31.326 xctest[60179:4253117] [ERROR  ] [IN ]: STK500:receive: programmer is not responding
2015-09-17 09:39:31.327 xctest[60179:4253117] [DEBUG  ] [OUT]: Sending 3 bytes
2015-09-17 09:39:31.327 xctest[60179:4253117] [TRACE  ] [OUT]: Send: A [0x41] . [0x82]   [0x20]
2015-09-17 09:39:31.327 xctest[60179:4253117] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-17 09:39:31.328 xctest[60179:4253117] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:31.328 xctest[60179:4253117] [TRACE  ] [IN ]: Start reading
2015-09-17 09:39:31.399 xctest[60179:4253160] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:31.400 xctest[60179:4253160] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:35.173 xctest[60179:4253117] [ERROR  ] [OUT]: BLE read timeout: 3.000965 (timeout = 3.000000)
2015-09-17 09:39:35.173 xctest[60179:4253117] [TRACE  ] [IN ]: Finish reading
2015-09-17 09:39:35.174 xctest[60179:4253117] [TRACE  ] [IN ]: Ble clear buffer
2015-09-17 09:39:35.174 xctest[60179:4253117] [ERROR  ] [IN ]: STK500:receive: programmer is not responding
2015-09-17 09:39:35.174 xctest[60179:4253117] [DEBUG  ] [   ]: STK500:initialize: n_extparms = 3
2015-09-17 09:39:35.175 xctest[60179:4253117] [DEBUG  ] [OUT]: Sending 22 bytes
2015-09-17 09:39:35.175 xctest[60179:4253117] [TRACE  ] [OUT]: Send: B [0x42] . [0x86] . [0x00] . [0x01] . [0x00] . [0x01] . [0x01] . [0x01] . [0x03] . [0xFF] . [0xFF] . [0xFF] . [0xFF] . [0x00] . [0x80] . [0x04] . [0x00] . [0x00] . [0x00] . [0x80] . [0x00]   [0x20]
2015-09-17 09:39:35.175 xctest[60179:4253117] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 20
2015-09-17 09:39:35.176 xctest[60179:4253117] [TRACE  ] [OUT]: BLE sending bytes range from 20 length 2
2015-09-17 09:39:35.177 xctest[60179:4253117] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:35.177 xctest[60179:4253117] [TRACE  ] [IN ]: Start reading
2015-09-17 09:39:35.224 xctest[60179:4253149] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:35.224 xctest[60179:4253149] [TRACE  ] [IN ]: Ignoring single 0x00 char

```

Should it work if i wire pins 0 and 1 at Uno to RX/TX (it does work for Mega2560)? Here is soft uart code from optiboot:

```
#ifndef SOFT_UART
#ifdef __AVR_ATmega8__
  UCSRA = _BV(U2X); //Double speed mode USART
  UCSRB = _BV(RXEN) | _BV(TXEN);  // enable Rx & Tx
  UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0);  // config USART; 8N1
  UBRRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
#else
  UCSR0A = _BV(U2X0); //Double speed mode USART0
  UCSR0B = _BV(RXEN0) | _BV(TXEN0);
  UCSR0C = _BV(UCSZ00) | _BV(UCSZ01);
  UBRR0L = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
#endif
#endif

#ifdef SOFT_UART
  /* Set TX pin as output */
  UART_DDR |= _BV(UART_TX_BIT);
#endif

```

Should RX be set as input separately too (like Tx as output)? Why it tries to set 'Double speed'?

# Answer
Eventually i've found the reason. And it was bug in HM-10 firmware. In mode 0 it does not accept control commands and in modes 1 and 2 it accepts AT commands to control PIO and commands are look like 'AT+...', f.e. 'PIO set value 1 to pin 1' command is 'AT+PIO11' and change mode to 0 look like 'AT+MODE0'. I need mode 1 to set PIO to 1 and 0 to reset arduino board. The problem is that some of upload commands look like 'A \[0x41\] . \[0x81\] \[0x20\]' (starts from 'A' too) and it makes HM-10 think it's control command which also starts from 'A'. If i add changing mode to 0 after pin control commands (in order to make HM-10 stop accepting control commands) it starts uploading:

```
2015-09-18 10:27:32.144 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-18 10:27:32.145 xctest[94852:4603627] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-18 10:27:32.145 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-18 10:27:32.146 xctest[94852:4603627] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-18 10:27:32.146 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 8 bytes: O [0x4F] K [0x4B] + [0x2B] S [0x53] e [0x65] t [0x74] : [0x3A] 0 [0x30]
2015-09-18 10:27:32.147 xctest[94852:4603627] [WARNING] [IN ]: Got 8 bytes in incoming buffer
2015-09-18 10:27:32.147 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.147 xctest[94852:4603627] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.207 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.208 xctest[94852:4603578] [TRACE  ] [IN ]: Ble clear buffer
2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG  ] [IN ]: Drained 26 bytes
2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG  ] [   ]: Draining incoming buffer (0 bytes)
2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 2 bytes
2015-09-18 10:27:32.208 xctest[94852:4603578] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
2015-09-18 10:27:32.209 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-18 10:27:32.209 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.209 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
2015-09-18 10:27:32.561 xctest[94852:4603630] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.561 xctest[94852:4603630] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.561 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x11] . [0xFC]
2015-09-18 10:27:32.561 xctest[94852:4603627] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x11]
2015-09-18 10:27:32.563 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.563 xctest[94852:4603578] [ERROR  ] [   ]: STK500:synchronize: attempt 1 of 3: no sync: received [0x11]
2015-09-18 10:27:32.564 xctest[94852:4603578] [DEBUG  ] [   ]: Draining incoming buffer (1 bytes)
2015-09-18 10:27:32.564 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 2 bytes
2015-09-18 10:27:32.564 xctest[94852:4603578] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
2015-09-18 10:27:32.564 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-18 10:27:32.565 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.565 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-18 10:27:32.636 xctest[94852:4603627] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x14]
2015-09-18 10:27:32.638 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.639 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.640 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x10]
2015-09-18 10:27:32.644 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-18 10:27:32.644 xctest[94852:4603578] [TRACE  ] [IN ]: Ble clear buffer
2015-09-18 10:27:32.645 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 3 bytes
2015-09-18 10:27:32.645 xctest[94852:4603578] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
2015-09-18 10:27:32.645 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-18 10:27:32.645 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.646 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE  ] [IN ]: Rx value received 3 bytes: . [0x14] . [0x04] . [0x10]
2015-09-18 10:27:32.711 xctest[94852:4603630] [WARNING] [IN ]: Got 3 bytes in incoming buffer
2015-09-18 10:27:32.712 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x14]
2015-09-18 10:27:32.713 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 3 bytes
2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE  ] [IN ]: 2 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.713 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE  ] [IN ]: Having current receive buffer: . [0x04] . [0x10]
2015-09-18 10:27:32.714 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
2015-09-18 10:27:32.714 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.728 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x04]
2015-09-18 10:27:32.728 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.729 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x10]
2015-09-18 10:27:32.730 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE  ] [IN ]: Ble clear buffer
2015-09-18 10:27:32.731 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 3 bytes
2015-09-18 10:27:32.731 xctest[94852:4603578] [TRACE  ] [OUT]: Send: A [0x41] . [0x82]   [0x20]
2015-09-18 10:27:32.731 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-18 10:27:32.732 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.732 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
2015-09-18 10:27:32.786 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.786 xctest[94852:4603627] [TRACE  ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.787 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 3 bytes: . [0x14] . [0x04] . [0x10]
2015-09-18 10:27:32.787 xctest[94852:4603627] [WARNING] [IN ]: Got 3 bytes in incoming buffer
2015-09-18 10:27:32.788 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
2015-09-18 10:27:32.788 xctest[94

```

I was working for Mega2560 since it uses different bootloader and upload commands do not start from 'A'. It's definitely HM-10 firmware bug as it can understand it's not control command since the second byte is not 'T'.

If i had oscilloscope i'd find the reason in 1 hour but for casual engineering i don't need it. I've reported a bug to HM-10 manufacturer but i'm not sure when they fix it. HM-10 firmware version is v532.
> 1 votes

# Answer
The reset procedure for the Arduino Uno works this way:

1. If supported, toggle USB DTR/RTS or if not, open the Serial port at 1200 baud & close it
2. The Atmega8u2 or Atmega16u2 (which is acting as the USB-UART bridge) detects one of these two events, and pulls PD7 (which is capacitively coupled to the pulled-up reset pin on the main Atmega328 IC) low, causing a low pulse on the reset pin, putting the Uno into bootloader mode.

Although microcontrollers do generally have a register which records the reset event reason (for example brownout detect, watchdog timer overflow, power-on reset or external reset) to allow for differentiation in startup routines, this isn't at play here because the Atmega328 can't know whether it was the Atmega8/16u2 which pulled the line low, or if you did it, or if it was a very focused beam of ionising radiation from outer space.

With this in mind, there are two possible reasons for the problem you are having:

1. The reset isn't actually happening. You can write your own code that has a particular startup routine to detect this, along with watching the reset pin with a scope to observe the pulse.
2. The onboard bootloader timeout is kicking in before you are passing data to it. From looking at the optiboot code (and the makefiles in the Arduino Github repo) it seems that you have a timeout of 1 second from reset to pass your first valid character to the bootloader. This is longer for other boards (8 seconds for the Arduino Leonardo, for example). Are you certain that you are getting data there that fast?

If the issue is a timing one (and you can't improve your timing), you could always consider flashing your own compiled version of Optiboot based on the Arduino makefile options for the atmega328 target but with an additional -DTIMEOUT\_MS=XXXX in the CFLAGS definition, where XXXX is the timeout in ms chosen from the supported list of 500, 1000, 2000, 4000, 8000.
> 1 votes

---
Tags: usb, bootloader, reset
---


# Question
Title: Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest)
I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128. When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward.

I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.

Here's some explanations for implementing PID in Arduino. http://playground.arduino.cc/Code/PIDLibraryConstructor

For instance the joystick readings go from 140, 137, 131, \[128\], 128, 128, 133, 139, 131, \[128\], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, \[\] in the example above.

If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.

```
void loop()
{

  int pwmSpeed;

  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

  if (Y_axis == 128)
  {

    Setpoint = encoder0Pos;
    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

}

```

Thanks.

//New edited code is shown below:

What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.

If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint.

However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.

```
global g_detect128 = false;

void setup()
    {
//any code here
    }

void loop()
{

  int pwmSpeed;
  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

 if (!g_detect128 && Y_axis == 128)
    {
    Setpoint = encoder0Pos;
    g_detect128 = true;
    }

  if (Y_axis == 128)
  {

    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

 if(Y_axis != 128)
    {
    g_detect128 = false;
    }

}

```

# Answer
If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:

```
boolean g_bSeen128 = false;

void setup()
{
    // ... whatever
}

void loop()
{
    // ... your existing code

    // catch first time we see 128
    if (!g_bSeen128 && Y_axis == 128)
    {
        // ... do whatever you need here. e.g.
        Setpoint = encoder0Pos;
        myPID.Compute();
        analogWrite(pwm, Output);

        // stop the event being caught next time
        g_bSeen128 = true;
    }

    // from comments below - to just ignore consecutive 128's, add this:
    if (Y_axis != 128) g_bSeen128 = false;

    // ... your existing code

}

```

If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:

```
int g_nLastInput = -1;

void setup()
{
    // ... whatever
}

void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change, e.g.
        if (Y_axis == 128)
        {
            // ... do something special for 128
        }
        else
        {
            // ... do something else for other inputs
        }
    }
}

```

I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.

If that's correct, an alternative way of coding your original logic might be like this:

```
void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    Input = encoder0Pos;

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change
        int nDelta = Y_axis - 128;

        if (nDelta == 0)
        {
            // i.e. Y_axis is 128
            Setpoint = encoder0Pos;
            myPID.Compute();
            analogWrite(pwm, Output);
        }
        else
        {
            // choose direction
            digitalWrite(dir, (nDelta > 0) ? HIGH : LOW);

            // set PWM speed scaled to 0..255
            analogWrite(pwm, abs(nDelta) * 2);
        }
    }
}

```
> 2 votes

---
Tags: programming
---


title: Servo Speed Control

text:
# Question
Title: Servo Speed Control
I work in a robot using arduino, and i have a few questions: It is possible to increase the speed of a servo, for example a parallax? It is possible to measure the current that pass through a servo?

# Answer
> 1 votes
# Part 1: Can I increase the speed of the servo motor?

## Solution #1 :

You can run your servo motor at its maximum rated voltage, which will give you the fastest response. If angle is all you want, that should be ok.

## Solution #2 :

If speed control is just as important, you're better off using a DC motor with an encoder. You will have to write a PI control loop, but in return you will be granted a fine-tune control and potentially superior performance.

## Solution #3 :

If you need to hold a physical load accurately at a certain angle, then I would go for a stepper motor. But you need to make sure that you do not overload it, as it will cause a misstep.

# Part 2: Can I measure the current?

The simplest and cheapest method, is to connect a current sensing resistor to your servo and measure the potential difference using the analog input. Since the resistance is known, you can calculate the current using the formula I = V/R.

Two things to make sure: 1) Your resistor power rating is not exceeded. 2) The voltage difference has to be large enough to be measurable. (e.g. 2 ohm resistor gives .05V @ 100mA, .5V @ 1A and your Arduino analog input may have the resolution of roughly 0.005V)

What? Did I hear you say that the accuracy isn't good enough? Well actually you can buy an op amp to amplify to the scale that you need. Or to make life easier: buy one from Adafruit. :p

Hope this helps.

# Answer
> 0 votes
The speed of most servos cannot be changed in your code (unless your code is limiting the speed by changing the position in small increments with long delays between your writes). Most servos, in my experience, try to get to the set position as fast as the physical motors can possibly move while keeping the motion somewhat motors. However, motors can only go so fast, so you are limited.

One thing to note: some servo motors can be powered at higher voltages, but still controlled at 5V. With the increase in voltage, it might allow the motor to go a little faster, although the results will vary based on the servo's electrical characteristics and the motor driver's algorithm.

As for the current, you can buy cheap current sensors online that can be interfaced with the Arduino. You will want to measure the current (in series) flowing either from your power source to the VCC of the stepper, or from the GND of the stepper back to the GND of your Arduino.

---
Tags: servo, robotics
---


# Question
Title: Why does my LCD display random characters?
I've been struggling with my LCD for hours, and after solving more different issues than I can remember, I'm out of ideas for this one.

My LCD is showing random characters, see the picture below (the last character blinks, some characters change and over time there are slowly more and more characters). I'm starting to wonder if the LCD I chose has a driver compatible with the LiquidCrystal library, what do you think? If so what can I do to avoid buying another one?

Here is the code:

```
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
//RS EN D4 D5 D6 D7
LiquidCrystal lcd(2, 3, 4, 5, A2, A3);
//RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer

void setup() {
  Serial.begin(9600);
  Serial.println("Starting");
  lcd.begin(16, 2);
}

void loop() {
  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);
  Serial.println("Printing");
  delay(1000);
}

```

I'm using this Arduino and this LCD. Note that I'm using pins 10,11,12,13 for a SD (which works) and 6 7 8 for a MAX232 (which is disabled).

Any ideas?

# Answer
> 3 votes
It could be because "millis()/1000" generates a "number", and not the "string" (or "char"). Try to add ",DEC" in your lcd.print(), something like "millis()/1000,DEC" to convert it to "decimal". Generally, it depends on the library, how they implement this function.

Good luck,

Mike

---
Tags: lcd
---


# Question
Title: Passing the input from one pin to another as output without polling?
I am trying to pass the input from one pin to another pin as output. Effectively I want to create a blind passthrough. The end goal is to connect two Arduinos and a series of test points together like the diagram below. I want Arduino B to shuffle which test points are connected to which pins on Arduino A on startup.

```
+-----------+       +-----------+     +-------------+
|           |       |           |     |             |
| Arduino A <-------> Arduino B <-----> Test Points |
|           |       |           |     |             |
+-----------+       +-----------+     +-------------+

```

I figure one way to do this is to poll the input pins in the loop() and then change the output pins accordingly but I would prefer if the voltage changes just passed right through without it affecting timing.

**Update:** For some clarification:

* All signaling is digital
* I'm looking to "route" around 10-12 test points to Arduino A ideally but 6 at a minimum

# Answer
You could use an analog multiplexer such as the 74HC4051 (8 channels) or the 74HC4067 (16 channels) like this:

Arduino B could alter the multiplex selector (A/B/C) pins to route the signal from the test points to a specific pin on Arduino A. If you are wanting to see the result of the signal on a different pin then a second multiplexer would be required (ie. one to send data to a pin, the second to see the result on a different pin).

I have a post about the 74HC4051 multiplexer / demultiplexer which gives more details about using it.

When I tested it I found only about a 5 ns delay in timing:

Ignacio's answer about a crossbar switch sounds like a more elaborate form of multiplexer. Personally I haven't used one of them.
> 4 votes

# Answer
No Arduino is capable of doing this. You need to be looking at a crossbar/crosspoint/matrix switch IC instead.
> 2 votes

# Answer
You can reduce latency by using interrupts to detect input changes instead of polling in loop(), if you're dead set on using an Arduino instead of adding switching hardware (as suggested in other answers).

See attachInterrupt() for details, and beware that different Arduino models differ greatly in how many pins support interrupts.

Alternately, you can speed up the polling approach by using direct port access (e.g., PORTB and PORTD registers) instead of the simpler Arduino read and write functions. This will bypass some wrapper code and also let you manipulate multiple pins in parallel.
> 1 votes

# Answer
Because this is digital I would like to add a third option in addition to Ignacio's and Nick's great suggestions. Use a logic device such as an FPGA or CPLD. This will require some extra knowledge and set up to get it working, but it is well suited for the functionality you are looking for.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to count the time until the next day of the week?
I wants to do in Arduino countdown that shows how many days, hours and minutes remaining to Friday 12:00. In my program I used a function in php `strtotime('next friday')` which thus could calculate differential timestamp and show how much time is left until Friday 12:00.

Is there a function `strtotime('next friday')` in Arduino? I have RTC which gives me just the current date and time, but does not show the current day of the week.

**EDIT: I have a solution**

We have day of week. We multiplied by 86400.
We have an hour. We multiply by 3600.
We have a minute. We multiplied by 60.
Add everything.
Subtract this from 604800.

`nextFriday = 604800-((dayofweek * 86400)+(now.hour()*3600)+(now.minute()*60)+now.second());`

Important, Friday is the number of the week "0". Friday = 0; Saturday = 1; etc...

# Answer
> 1 votes
The key to working with time is to have a known "base" time to calculate everything relative to. This is called the *epoch*. Different systems use different epochs, and each has advantages and disadvantages.

I generally use the UNIX epoch in my programming (chiefly because I am a UNIX nut), which is the first of January, 1970 (01/01/1970). This is year, month, day, hour, minute and second 0.

From that you can then calculate the number of seconds between the epoch and any other time you choose as long as it is later than the epoch.

To calculate the day of the week for any given date you first need to know the day of the week for the epoch (for UNIX that's a Thursday) then work out how many days there are between the epoch and the target time.

Calculating real times in terms of seconds can be somewhat tricky due to leap years and daylight savings, but there are plenty of algorithms in the public domain, and many RTC libraries include functions to convert to/from epoch times.

For instance, the Arduino Time Library has functions to calculate weekdays, and to convert to "time\_t" format (seconds since epoch) which can be used to work out differences in times. For instance, if you know that it's Tuesday and you want next Friday then you know that Friday is 3 days in the future - so you can get the current time in seconds from the epoch then add to that 3 days' worth of seconds (3 × 60 × 60 × 24) to that time to get the same time of day next Friday.

# Answer
> 0 votes
There are generic examples, e.g. Determination of the day of the week - Wikipedia.

> In the C language expressions below, **y**, **m** and **d** are, respectively, integer variables representing the year (e.g., 1988), month (1-12) and day of the month (1-31).

```
        (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7

```

Also see StackOverflow - C Program to find day of week given date.

---
Tags: programming, rtc
---


title: Uno as a composite USB HID keyboard

text:
# Question
Title: Uno as a composite USB HID keyboard
I'm looking to create a USB device that would be basically a HID keyboard. I am able to do that with Uno. I flash new firmware with a HID keyboard descriptor and on the arduino side I loop and check for button presses. Based on butotn presses I send the report.

What I would like to add to this is option to send some data from a PC and based on that data do something (like turn an LED on.)

Here is an example:

```
loop() {
  check_and_send_buttons();
  uint8_t inputByte = get_input(); //new
  handle_input(inputByte); //new
}

```

I'm on Linux and I tried sending some data via hidrawX but that did not work out. Any ideas?

I'm willing to also write new device driver for Linux if needed.

# Answer
> 1 votes
On UNO R3 the HID protocol is handled by the secondary AVR present on the board. Which is the one talking to the PC. So what you should modify is the code implementing the USB protocol on the secondary AVR.

The main (328p) AVR interacts with it through the serial port.

You do not need to alter the Linux driver, since it already supports the driving of the usual LEDs (CAPS, Num Lock, Scroll Lock), if these are enough for you.

So, to recap:

1) enhance the HID implementation to understand LED status commands coming from the PC

2) report such changes over serial

3) on the primary AVR, monitor for such messages coming over serial port from the secondary AVR and use them to drive the LEDs.

---
Tags: arduino-uno, serial, usb, keyboard, input
---


title: Sending wireless data over with xbee s1

text:
# Question
Title: Sending wireless data over with xbee s1
I am following this tutorial to learn about Arduino wireless communication. I have 2 Arduino unos with Xbee S1s sitting on Xbee Pro shields.

I've programmed the Xbee S1s by screening into the /dev/tty/\* and configuring them with: `+++, ATID1234, ATMY1000 (ATMY1001), ATDL1001 (ATDL1000)` and `ATWR`. I've double checked the values to ensure they are correct.

So i've created a super simple Sender and Receiver package:

Sender.ino

```
int counter = 0;

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

void loop() {
  Serial.println(counter++);
  delay(1000);
}

```

Receiver.ino:

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

void loop() {
  Serial.println("Looping");
  while (Serial.available() == 0);    // wait
  int counter = Serial.parseInt();
  Serial.println(counter);
  Serial.flush();
  delay(500);
}

```

So first of all, when I upload my program to my arduino, I make sure that the S1s are not attached to the Pro shields which is attached to the unos.

When both of my unos are powered, I see a red light blinking but no indication of "busy blinking" which is supposed to happen when two XBee S1s are connected to the same channel. I am currently seeing a consistent blinking at about 1 second frequency.

Can someone tell me why I am only able to see "Looping" in my Serial monitor on my receiver?

# Answer
**blah** reported:

> So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned.

Can someone vote this up please to remove it from the unanswered queue?
> 1 votes

---
Tags: xbee
---