# Question
Title: Read float and long from external EEPROM chip
I am using an Arduino to read information from an EEPROM chip over I2C with the code I found here: https://playground.arduino.cc/Code/I2CEEPROM

It works great for *int* and *char* values but I also need to read *short*, *long*, and *float* values.

They are stored in this order: 1510543923
is stored as: 01011010 00001001 00010010 00110011

How can I read multiple bytes into a single variable of these types?

I tried the following but it gives me a 16 bit number:

```
i2c_eeprom_read_buffer(0x50, 25, (byte *)bytes, 4);
long j = (bytes[3] << 0) + (bytes[2] << 8) + (bytes[1] << 16) + (bytes[0] << 24);

```

# Answer
> 4 votes
> 1510543923 is stored as: 01011010 00001001 00010010 00110011

This is known as “big endian”, or “MSB first”, because the most significant byte (MSB, here 01011010) comes first.

I recommend against this order. If you can, swap all the bytes and store the value LSB first, i.e. with the least significant byte first, and the most significant byte last. This will make your life easier since it's the order used internally in the Arduino. If you can go little endian, then you will be able to read the data straight into the required variable, with no conversion needed, as in:

```
i2c_eeprom_read_buffer(0x50, 25, (byte *) &j, sizeof j);

```

and it will work identically with any data type.

If you cannot choose the byte order (maybe you cannot control what is inside the EEPROM), then you will have to reverse all the bytes. You can do this either with bit shifts or by explicitly moving bytes.

> `bytes[1] << 16`

This will not work. Per the rules of the C++ language, `bytes[1]` is implicitly promoted to `int` type before the shift, then it is shifted as an `int`. But on your Arduino an `int` is 16-bits long, thus by shifting it 16 positions you are dropping off *all* of the bits. Actually, this is even worse: you are invoking what is known as *undefined behavior*, meaning that it is considered nonsense and the compiler is free to interpret however it wants.

To do this properly, you first have to *explicitly* cast `bytes[i]` to `unsigned long`. It has to be unsigned because changing the sign bit on a `long` by bit shifting is also undefined behavior. Thus, the proper way of reconstructing the number via bit shifts is:

```
long j = ((unsigned long) bytes[3] << 0)
       | ((unsigned long) bytes[2] << 8)
       | ((unsigned long) bytes[1] << 16)
       | ((unsigned long) bytes[0] << 24);

```

This is portable (it should also work on big-endian architectures) but only works with integral types, not with floats.

For reconstructing a float, my preferred option would be to use a `union`, in order to access the bytes of the variable explicitly. Then you just have to copy the bytes from the buffer to the `union` in reverse order:

```
union { float f; byte b[4]; } data;
data.b[0] = bytes[3];
data.b[1] = bytes[2];
data.b[2] = bytes[1];
data.b[3] = bytes[0];
float x = data.f;

```

One nice thing about this approach is that it works with any data type.

# Answer
> 3 votes
It gives you a 16-bit integer because the compiler automatically makes casts. In particular:

* `byte << int` returns `int`
* `int + int` returns `int`

So your `(bytes[1] << 16)` is converted to an `int`, and consequently gets zeroed.

I tried to simulate this code; the results are shown as comments

```
int a = 0x1234;
long b = a << 8;
long c = a << 8L;
long d = ((long)a) << 8;
Serial.println(a); // a is 0x1234
Serial.println(b); // b is 0x3400
Serial.println(c); // c is 0x3400
Serial.println(d); // d is 0x123400

```

Personally I'd bet that `int << long` would result in a `long`, but apparently I'm wrong.

In any case, you should write

```
long j= (bytes[3] << 0) + (bytes[2] << 8) + (((unsigned long)bytes[1]) << 16) + (((unsigned long)bytes[0]) << 24);

```

This should fix your error. In any case, you can also simply write

```
long write_value;
i2c_eeprom_write_page(0x50, 25, (byte *)&write_value, sizeof(write_value));
long read_value;
i2c_eeprom_read_buffer(0x50, 25, (byte *)&read_value, sizeof(read_value));

```

Please note that accessing directly the pointers, like in this case, will respect the endianness of the compiler. In the case of a big endian implementation, the long with value `0x12345678` will be saved as `12 34 56 78`, while with a little endian implementation it will be saved as `78 56 34 12`. This is not a problem if you always use the same platform, but if you are trying to transfer information over a network you will have to ensure that all the devices have the same endianness or manually correct it

# Answer
> 0 votes
Using template functions this could be written as:

```
template<class T> void i2c_read(uint16_t addr, T& x)
{
  i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(T));
}

template<class T> void i2c_write(uint16_t addr, T& x)
{
  i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(T));
}

```

These two functions take the data type as template parameter. Some examples:

```
  long x = 0x12345;
  i2c_write<long>(0, x);

  long y = 0;
  i2c_read<long>(0, y);

```

With `auto` the functions could be written as:

```
void i2c_read(uint16_t addr, auto& x)
{
  i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(x));
}

void i2c_write(uint16_t addr, auto& x)
{
  i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(x));
}

```

With `auto` the compiler will determine the data type.

Cheers!

# Answer
> -1 votes
> How can I read multiple bytes into a single variable of these types?

use a pointer to read each byte of a multi-byte type and save it into eeprom;

then do the same in reading them back: use a pointer to re-assemble the data (in bytes).

sizeof() comes in handy here.

Edit: lots of wonderfully complex answers for something this simple. When I get sometime I will pin my approach down.

Btw, many i2c libraries allow blocked read or write. So take that into your coding consideration.

edit2:

so here is what I have, to demonstrate how pointers can be used to write / read data.

```
//simulated write to buffer
//write n bytes of data from *ptr to address starting with addr
void mem_write(char addr, char *ptr, char n) {
    do {buffer[addr++] = *ptr++;} while (n--);
}

//simulated read from buffer
void mem_read(char addr, char *ptr, char n) {
    do {*ptr++ = buffer[addr++];} while (n--);
}

```

in this particular example, mem\_write() writes n bytes of data, from source pointer ptr, into buffer\[\] starting at address addr. the read does the same.

you can port in your i2c byte read / write routines here, or use block read/write routines for more efficiency.

to confirm that it works, I wrote the following:

```
void setup() {
    Serial.begin(9600);         //initialize serial transmission

    dat.x = 1; dat.z = 3.0;     //initialize dat
    dat_ptr = (uint8_t *)&dat;  //initialize pointers
    dat_ptr1= (uint8_t *)&dat1;

    //print serial
    Serial.print("line 0: size = "); Serial.print(sizeof dat); Serial.print(", x = "); Serial.print(dat.x); Serial.print(", z = "); Serial.println(dat.z);

    //round 1: similated eeprom write/read
    mem_write(0, dat_ptr, sizeof dat);                  //write to buffer
    dat1.x = 0; dat1.z = 0;                             //initialize dat1
    mem_read(0, dat_ptr1, sizeof dat1);                 //read from buffer
    //now, dat1 contains the same data as dat
    //print dat1 on serial -> it should read identical to line 0
    Serial.print("line 1: size = "); Serial.print(sizeof dat1); Serial.print(", x = "); Serial.print(dat1.x); Serial.print(", z = "); Serial.println(dat1.z);

    //round 2: similated eeprom write/read
    //slightly different way of doing the same
    dat.x +=1; dat.z +=10.0;                            //x=2, z=13.0
    mem_write(0, (char *)&dat, sizeof dat);             //write to buffer
    dat1.x = 0; dat1.z = 0;                             //initialize dat1
    mem_read(0, (char *)&dat1, sizeof dat1);            //read from buffer
    //now dat1.x = 1+1=2, dat1.z = 3.0+10.0 = 13.0
    //print dat1 on serial
    Serial.print("line 2: size = "); Serial.print(sizeof dat1); Serial.print(", x = "); Serial.print(dat1.x); Serial.print(", z = "); Serial.println(dat1.z);

}

```

it essentially writes one data element "dat" into the buffer, and read it back into "dat1"; both items are printed over serial to confirm that the write / read are successful.

then I incremented on dat, and wrote it to buffer and read it back to dat1. again, printed dat1 on the serial monitor to confirm that we have the right result.

here is what I got:

so we have the expected result.

the approach here is fairly standard. Obviously, experts usually come up with far more complex ways of doing simple things, as shown earlier answers, :)

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


# Question
Title: Problem reading an EEPROM chip using the I2C protocol
I am trying to read an EEPROM chip that supports the ***I2C*** protocol (cannot tell the IC model number as it is not printed). For sure it supports the I2C protocol, since I wrote a code to detect it using the I2C library and the device address I got it return is ***0x51***. Now I am trying to write a code that reads data from this IC chip. The code is as follows:

```
#include <Wire.h>

int addr = 0;

void setup() {
    Wire.begin(); // initialise the connection
    Serial.begin(9600);
    while (!Serial) {}
    delay(100);
}

void loop() {
  byte deviceAddress = 0x51;
  byte data = readData(addr, deviceAddress);
  Serial.print(data, HEX);
  Serial.print(" ");
  addr++;
  if(addr%16 == 0) {
     Serial.print('\n');
  }
  // check for 1Kbits first
  if (addr%128 == 0) {
     Serial.println("round complete");
     Serial.println();
     addr = 0;
  }
  delay(100);
}

byte readData(int address, int deviceAddress) {
  // sending device address
  Wire.beginTransmission(deviceAddress);
  Wire.write(address);
  Wire.endTransmission();
  Wire.requestFrom((short int)deviceAddress, 1);
  if(Wire.available()) {
    byte data = Wire.read();
    return data;
  }
  return 0xAA; // random data
}

```

The problem I am facing is, I get back the address (from which I want to read the data) as the data itself (For e.g. read(0) returns 0, read(1) returns 1 and so on). I even tried to debug the I2C communication using the logic analyzer (Saleae logic in this case). A screenshot is shown below.

The screenshot shows the logic for a read operation from a single address (0x78), but the story holds for each and every address i.e. I get back the address instead of the data from the address.

The output of the above code is as follows:

> 0 1 2 3 4 5 6 7 8 9 A B C D E F
> 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
> 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
> 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
> 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
> 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F
> 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F
> 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F
> round complete

Can you help me identifying what possibly I am doing wrong here?

Thanks.

# Answer
You need to pass the address as two bytes, one by one.

Do not do:

```
Wire.write(address);

```

Rather, do:

```
Wire.write((uint8_t)(address >> 8)); // MSB
Wire.write((uint8_t)(address & 0xFF)); // LSB

```
> 2 votes

# Answer
In short, you should split

```
Wire.write(address);

```

into

```
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB

```

I am working on a similar project right now. I have searched through many different codes and libraries and found the following to work the best: https://playground.arduino.cc/Code/I2CEEPROM

I am using the 24LC1025 who's datasheet can be found here: http://www.microchip.com/datasheet/24LC1025

I am using the 1Mb version and it uses 0x51 and 0x50 becuase it has two pages. I suspect you will find your chip to at least be similar because of the I2C Address you listed. You may have a smaller version of the same chip that only uses the one address.
> 1 votes

# Answer
Without the specific chip info this will be difficult.

However, my experience with EEPROMs and I2C is that the first action is to write a command, then write the parameter(s) for that command, then read the response.

Often, there is a status register in the EEPROM that needs to be read (by writing a command, then reading the response) to determine if the EEPROM is ready to receive a different command, like writing to set the address for a read/or/write, then the actual read command.
> 0 votes

---
Tags: arduino-uno, i2c, c, eeprom
---


# Question
Title: Can I use a ThunderBorg is a dual motor controller on an Arduino UNO R3
I am new to Arduino and Electronics and am thinking of making a 6 wheel drive all terrain platform similar to the MonsterBorg pi, but I want to use an Arduino instead of a Raspberry pi to control the motors. The motors I intend to use need to be powerfull. Any advice on what would be shield or motor controllers I should use would be a great help.

# Answer
> 1 votes
Hello,
You have many possibility for drive one or more motor.

* Transistor(1 motor)
* L293D(2 motor backward and forward or 4 motor just forward)
* L298D(like L293D but he support more Amp and Vol
* L293D Adafruit shield(4 motor)
* ...

Here is an example for

L293D:
enable PWM(0-255), inputs digital(0-1).
Motor1 : Input1, Input2, Enable1,2
Motor2 : Input3, Input4, Enable3,4
```
void motor1RotationDirection(int input1arg, int input2arg){
    digitaleWrite(input1, input1arg);//  LOW  |  HIGH
    digitaleWrite(input2, input2arg);//  HIGH |  LOW
                                     //Forward|Backward
}

void motor1speedRotation(int speed){
    analogWrite(enableMotor1, speed);
}    //for motor2 is the same.

```

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


title: Add id to raw data in an array

text:
# Question
Title: Add id to raw data in an array
I am working on an Arduino project, where I am transmitting GPS data between two Arduinos. This code can transmit the raw GPS data:

```
int a = Serial1.available();
if(a){
    uint8_t hej[a];
    for(int i=0; i<a; i++){
        hej[i] = Serial1.read();
    }

    rf95.send(hej, a);
}

```

I need to be able to identify the device that's transmitting the data. This can be in form of an integer value. I have tried to add a value to the array, but that messes up the data when I receive it. Is there a simple way to add an ID to the data I am transmitting?

# Answer
I would suggest:

1. Use a library (TinyGPS++ for example) to read the GPS data and extract just what you want.
2. Use a `struct` to craft a packet that you can send over bluetooth, or send the data as a textual representation, depending on your needs.

For a struct you can:

```
struct packet {
    uint8_t id;
    float latitude;
    float longitude;
};

struct packet myPacket;
myPacket.id = 32; // Unique ID
myPacket.latitude = gps.getLatitude(); // Whatever function call here
myPacket.longitude = gps.getLongitude(); // or whatever
rf95.send((uint8_t *)&myPacket, sizeof(struct packet));

```
> 2 votes

# Answer
Well, the main problem here is that you don't know when the string will enter from the serial port. For instance, let's see a sample communication:

```
$GPGGA,154655,4328.1874,N,00340.5185,W,1,03,08.5,-00044.7,M,051.6,M,,*79
$GPGSA,A,2,13,23,25,,,,,,,,,,08.5,08.5,00.9*0E
$GPGSV,3,1,10,02,50,290,26,04,60,210,26,08,33,173,29,10,21,296,00*7E

```

Making a sample reading like this:

```
int a = Serial1.available();
if(a){
    uint8_t hej[a];
    for(int i=0; i<a; i++){
        hej[i] = Serial1.read();
    }

    Serial.print("Received \"");
    Serial.write(hej, a);
    Serial.println("\"");
}

```

you will see something like

```
Received "$GPG"
Received "GA,1546"
Received "5"
Received "5,4"

```

or, most probably,

```
Received "$"
Received "G"
Received "P"
Received "G"
Received "G"
Received "A"

```

so it is difficult to detect where to insert your ID.

I have two solutions for you.

The simpler one is to use the fact that the GPS sends formatted sentences. According to the NMEA specification, the message is at most 82 chars long and is terminated by a LF (0x10) char. This means that you can do something like this (I assume you want to use a 4-chars ID, and in this case the ID is `MYID`)

```
#define ID_LENGHT 5 /* 4 chars and a separator */
#define BUFFERSIZE ID_LENGHT+82 /* ID plus the max NMEA sentence*/
byte recvBuffer[BUFFERSIZE];
byte recvIdx;

void setup()
{
    // ... other initialization

    // Fill the ID at the beginning, and prepare to store data at the end of ID
    memcpy(recvBuffer, "MYID-", ID_LENGHT * sizeof(byte));
    recvIdx = ID_LENGHT;
}

void loop()
{
    // ... other program

    while (Serial1.available())
    {
        byte ch = Serial1.read();
        if (recvIdx >= BUFFERSIZE)
            continue; // Should never arrive here, since the sentences are shorter
        recvBuffer[recvIdx++] = ch;
        if (ch == 0x10) // received LF, so end of sentence
        {
            // Send the buffer (plus the identifier)
            rf95.send(recvBuffer, recvIdx);
            // Reset the idx (and so you will overwrite previous buffer
            recvIdx = ID_LENGHT;
        }
    }

    // ... Other code
}

```

This approach transfers a lot more thata then needed, since you want to only transfer the latitude and longitude. So the second (and best) approach in my opinion is to have a NMEA parser on the arduino that extracts the lat and long values you need and then sends a (formatted) message to the master, with ID, lat and long.

This is the best solution, but I don't have experience with NMEA parsers so you'd better try searching online for some library and, most important, have the necessary computational power and flash available to perform this computation
> 0 votes

# Answer
You could try NeoGPS. NeoGPS is smaller, faster, more reliable and more accurate than all other GPS libraries. It packages all the GPS fields into a structure for you:

```
#define gpsPort Serial1

struct msg_t {
  uint8_t ID;   // A node's ID
  gps_fix fix;  // The NeoGPS structure containing all configured GPS fields
};

msg_t msg = { THIS_NODE_ID };

void loop()
{
  if (gps.available( gpsPort )) {  // parses characters
    msg.fix = gps.read();          // gets the struct when it's ready (once per second)

    rf95.send( (uint8_t *) &msg, sizeof(msg) );  // send the msg struct
  }
}

```

The receiving side will similarly read into the same struct, something like:

```
    rf95.receive( (uint8_t *) &msg, sizeof(msg) );
    if ((msg.id == ROVER_ID) && msg.fix.valid.location) {
      // Check lat/lon against target location
       ...

```

This will also coordinate the RF transmission with the GPS quiet time, helping to avoid losing GPS characters while the RF transmission is busy.

The `gps_fix` structure can be quite small, depending on what GPS fields you enable in the NeoGPS configuration files. This structure is 10x to 80x smaller than the raw NMEA data, so it is transmitted very quickly. The default configuration uses only 31 bytes; most GPS devices send about 400 bytes per second.

If you'd like to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**. You should also read about Choosing a Serial Port and the Troubleshooting tips.
> 0 votes

---
Tags: c++, adafruit, gps
---


# Question
Title: Error: `nullptr` was not declared in this scope. Arduino IDE
I try to use this *ArduinoThread* library. In the Arduino I go *Sketch-\>Import Library-\>ArduinoThread*. After that I have the following line in the beginning of the sketch:

```
#include <ThreadController.h>
#include <Thread.h>
#include <StaticThreadController.h>

```

I leave `setup()` and `loop()` empty and try to verify or upload the sketch on my Arduino board. But I get the following errors:

Is this about the library or I do something wrong?

# Answer
> 3 votes
I installed Arduino IDE in two different ways (only god knows why). The first one was via using of manager `apt-get` and other was manually via downloading, unzipping and installation through the `install.sh` file. It seems that on Ubuntu 14.04 the

```
sudo apt-get install arduino

```

command provides an installation of an old version of Arduino IDE. So eventually I was launching Arduino IDE by `arduino` command in my terminal (actually I was using d-menu in i3). No surprise it ran the old one installed by `apt-get`. I just removed that version by

```
sudo apt-get remove arduino

```

And now I am using executable `arduino` inside unzipped folder. Actually, I am not using Arduino IDE explicitly at all. I am using a Makefile from here.

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


# Question
Title: Attiny85 DigiSpark: Drive 128X64 OLED screen, no picture problem
**Devices used** It's about these devices:

---

**Quick scheme** (how I connected those)

---

Got the **wiring info** from the TinyWire library

---

**Program I use** (also many different examples tried but no luck):

```
#include <Wire.h>

//~ DEFINES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Some defines for the SSD1306 controller driving a 128x64 resolution OLED display
// PART     - http://www.simplelabs.co.in/content/96-blue-i2c-oled-module
// DATASHEET  - https://www.adafruit.com/datasheets/SSD1306.pdf

// The Slave Address (SLA) of the OLED controller - SSD1306 - is 0x3C
// The LSB is supposed to be the mode. Since we are only going to WRITE to the OLED, the LSB is going to be 0
// SLA (0x3C) + WRITE_MODE (0x00) =  0x78 (0b01111000)
#define OLED_I2C_ADDRESS   0x3C

// The SSD1306 datasheet (pg.20) says that a control byte has to be sent before sending a command
// Control byte consists of
// bit 7    : Co   : Continuation bit - If 0, then it assumes all the next bytes are data (no more control bytes).
//        :    You can send a stream of data, ie: gRAM dump - if Co=0
//        :        For Command, you'd prolly wanna set this - one at a time. Hence, Co=1 for commands
//        :    For Data stream, Co=0 :)
// bit 6      : D/C# : Data/Command Selection bit, Data=1/Command=0
// bit [5-0]  : lower 6 bits have to be 0
#define OLED_CONTROL_BYTE_CMD_SINGLE  0x80
#define OLED_CONTROL_BYTE_CMD_STREAM  0x00
#define OLED_CONTROL_BYTE_DATA_STREAM 0x40

// Fundamental commands (pg.28)
#define OLED_CMD_SET_CONTRAST     0x81  // follow with 0x7F
#define OLED_CMD_DISPLAY_RAM      0xA4
#define OLED_CMD_DISPLAY_ALLON      0xA5
#define OLED_CMD_DISPLAY_NORMAL     0xA6
#define OLED_CMD_DISPLAY_INVERTED     0xA7
#define OLED_CMD_DISPLAY_OFF      0xAE
#define OLED_CMD_DISPLAY_ON       0xAF

// Addressing Command Table (pg.30)
#define OLED_CMD_SET_MEMORY_ADDR_MODE 0x20  // follow with 0x00 = HORZ mode = Behave like a KS108 graphic LCD
#define OLED_CMD_SET_COLUMN_RANGE   0x21  // can be used only in HORZ/VERT mode - follow with 0x00 + 0x7F = COL127
#define OLED_CMD_SET_PAGE_RANGE     0x22  // can be used only in HORZ/VERT mode - follow with 0x00 + 0x07 = PAGE7

// Hardware Config (pg.31)
#define OLED_CMD_SET_DISPLAY_START_LINE 0x40
#define OLED_CMD_SET_SEGMENT_REMAP    0xA1
#define OLED_CMD_SET_MUX_RATIO      0xA8  // follow with 0x3F = 64 MUX
#define OLED_CMD_SET_COM_SCAN_MODE    0xC8
#define OLED_CMD_SET_DISPLAY_OFFSET   0xD3  // follow with 0x00
#define OLED_CMD_SET_COM_PIN_MAP    0xDA  // follow with 0x12

// Timing and Driving Scheme (pg.32)
#define OLED_CMD_SET_DISPLAY_CLK_DIV  0xD5  // follow with 0x80
#define OLED_CMD_SET_PRECHARGE      0xD9  // follow with 0x22
#define OLED_CMD_SET_VCOMH_DESELCT    0xDB  // follow with 0x30

// Charge Pump (pg.62)
#define OLED_CMD_SET_CHARGE_PUMP    0x8D  // follow with 0x14

// NOP
#define OLED_CMD_NOP          0xE3

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Box pattern
uint8_t pattern1[] = {
  0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00,
  0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00
  };

// Cross weave pattern
uint8_t pattern2[] = {
  0x81,0x42,0x24,0x18,0x18,0x24,0x42,0x81,
  0x81,0x42,0x24,0x18,0x18,0x24,0x42,0x81
  };

void setup()   {
  // Init the OLED controller
  OLED_init();
}

void loop() {
  // I2C
  Wire.beginTransmission(OLED_I2C_ADDRESS);
  Wire.write(OLED_CONTROL_BYTE_CMD_STREAM);
  Wire.write(OLED_CMD_SET_COLUMN_RANGE);
  Wire.write(0x00);
  Wire.write(0x7F);
  Wire.write(OLED_CMD_SET_PAGE_RANGE);
  Wire.write(0);
  Wire.write(0x07);
  Wire.endTransmission();

  for(uint16_t i=0;i<1024;i++){
    Wire.beginTransmission(OLED_I2C_ADDRESS);
    Wire.write(OLED_CONTROL_BYTE_DATA_STREAM);
      for (uint8_t x=0; x<16; x++) {
      // Wire.write(0b11000001);
      // Wire.write(0x81);
      // Wire.write(0x02);
      Wire.write(pattern1[x]);
      // Wire.write(pattern2[x]);
      i++;
      }
      i--;
      Wire.endTransmission();
  }

    delay(5000);

}

void OLED_init() {
  // Init the I2C interface (pins A4 and A5 on the Arduino Uno board) in Master Mode.
  Wire.begin();
  // keywords:
  // SEG = COL = segment = column byte data on a page
  // Page = 8 pixel tall row. Has 128 SEGs and 8 COMs
  // COM = row

  // Begin the I2C comm with SSD1306's address (SLA+Write)
  Wire.beginTransmission(OLED_I2C_ADDRESS);

  // Tell the SSD1306 that a command stream is incoming
  Wire.write(OLED_CONTROL_BYTE_CMD_STREAM);

  // Follow instructions on pg.64 of the dataSheet for software configuration of the SSD1306
  // Turn the Display OFF
  Wire.write(OLED_CMD_DISPLAY_OFF);
  // Set mux ration tp select max number of rows - 64
  Wire.write(OLED_CMD_SET_MUX_RATIO);
  Wire.write(0x3F);
  // Set the display offset to 0
  Wire.write(OLED_CMD_SET_DISPLAY_OFFSET);
  Wire.write(0x00);
  // Display start line to 0
  Wire.write(OLED_CMD_SET_DISPLAY_START_LINE);

  // Mirror the x-axis. In case you set it up such that the pins are north.
  // Wire.write(0xA0); - in case pins are south - default
  Wire.write(OLED_CMD_SET_SEGMENT_REMAP);

  // Mirror the y-axis. In case you set it up such that the pins are north.
  // Wire.write(0xC0); - in case pins are south - default
  Wire.write(OLED_CMD_SET_COM_SCAN_MODE);

  // Default - alternate COM pin map
  Wire.write(OLED_CMD_SET_COM_PIN_MAP);
  Wire.write(0x12);
  // set contrast
  Wire.write(OLED_CMD_SET_CONTRAST);
  Wire.write(0x7F);
  // Set display to enable rendering from GDDRAM (Graphic Display Data RAM)
  Wire.write(OLED_CMD_DISPLAY_RAM);
  // Normal mode!
  Wire.write(OLED_CMD_DISPLAY_NORMAL);
  // Default oscillator clock
  Wire.write(OLED_CMD_SET_DISPLAY_CLK_DIV);
  Wire.write(0x80);
  // Enable the charge pump
  Wire.write(OLED_CMD_SET_CHARGE_PUMP);
  Wire.write(0x14);
  // Set precharge cycles to high cap type
  Wire.write(OLED_CMD_SET_PRECHARGE);
  Wire.write(0x22);
  // Set the V_COMH deselect volatage to max
  Wire.write(OLED_CMD_SET_VCOMH_DESELCT);
  Wire.write(0x30);
  // Horizonatal addressing mode - same as the KS108 GLCD
  Wire.write(OLED_CMD_SET_MEMORY_ADDR_MODE);
  Wire.write(0x00);
  // Turn the Display ON
  Wire.write(OLED_CMD_DISPLAY_ON);

  // End the I2C comm with the SSD1306
  Wire.endTransmission();
}

```

Source: https://github.com/SonalPinto/Arduino\_SSD1306\_OLED/blob/master/oled\_test/oled\_test.ino

---

**Other examples** I have been tried:

---

**Question**

What could be wrong, do I miss something inhere? Wires seems to be OK, do I use the correct pins (sometimes a little confusing on Attiny85, digital versus analog)? Tried also another `OLED_I2C_ADDRESS`, 0x3D instead of 0x3C but no luck at all. Tried both screen and both remain black.

# Answer
With I2C you always need pull up resistors on the data lines, otherwise nothing works. Normally ones around 4.7K for a Uno, not sure what they should be for a Tiny.

If you are unsure about the I2C address get "I2CScanner" (An Arduino program) and that will tell you.
> 3 votes

# Answer
Hmm not strictly true I've currently got mine working without resistors, and the screens I get often do work without them, for example the Arduino Nano and ESP8266/NodeMCU I have used without resistors.

I had a bit of a pain with this board, the drivers for Windows originaly not working or detecting the board correctly and then the board not seeing the OLED mine is the 128x32 version. I edited the code to reflect the screen size in the DigiSparkOLED.cpp

```
0xA8, 0x1F,      // Set multiplex ratio(1 to 64)

```

And change:

```
0xDA, 0x12,      // Set com pins hardware configuration

```

To:

```
0xDA, 0x02,      // Set com pins hardware configuration

```

Also on several sites it does say to use PINS SCL on P5 and SDA on P2 so if its not working maybe try that pinout. I used the one mentioned above and the I2C scanner is now seeing it on address 0x3C (I wouldn't try changing the address in my experience the pinout will be wrong)

Do your usual checks to see if the screen is drawing power on all lines with a multimeter, also run I2C Scanner program to see if it sees anything and if not then try the alternative pinout.
> 0 votes

---
Tags: wires
---


# Question
Title: Which input pins can I use on the ESP8266 NodeMCU
On the ESP8266 NodeMCU I have GPIO2 , GPIO3 , GPIO1 , GPIO9 free but when I assign them to a button they do not work. I assume it is because those pins have other function behind them. When I look at the schematic I found that they are TXD1, RXD0, TXD0, and SSD2. Is there a way to still use these pins as inputs?

If not, can I use an Arduino Uno for my inputs and send signals from there to the analog pin to my ESP8266 NodeMCU for the connection to the MQTT server?

For the record all my other pins are used so I can't use any other input pin than these 4.

# Answer
GPIO2 is NodeMCU D4 which is U1TXD, transmit for the second UART, generally available. GPIO3 is NodeMCU U0RXD, receive for the first UART, generally available if you aren't using serial. GPIO1 is NodeMCU U0TXD, transmit for the first UART, generally available if you aren't using serial. GPIO9 is NodeMCU SPIHD and is NOT available, as it is required for the flash memory. All that is well documented in many places. You can easily use serial to move data between modules, or multiplex your input to the one module. Cannot provide much insight without more details.
> 1 votes

---
Tags: arduino-uno, esp8266, pins, nodemcu
---


title: Connecting my Arduino with Bluetooth

text:
# Question
Title: Connecting my Arduino with Bluetooth
What I want to do is to create a temperature measurement bracelet that you wear on your wrist. So it takes data from the sensors and sends them to the PC. What I am using to do that:

* an Arduino Uno
* a temperature sensor
* a Bluetooth module to connect with Arduino Uno
* a mobile phone
* a PC

I will connect Arduino Uno with the Bluetooth module so it sends data to the mobile for example. Since I am a beginner I do not have it very clear. Do I need a GPRS SIM (SIM900A for example or whatever) for this to function or just the Bluetooth connection is enough?

Specify that the question is very basic because I am a beginner.

# Answer
> 0 votes
You should only need the Bluetooth module, not a Sim card. The HC-05 and HC-06 are Bluetooth modules that are commonly used with Arduinos, are relatively inexpensive, are fairly small, and there's quite a bit of documentation out there on how to use them.

# Answer
> 1 votes
Assuming the mobile device to which you are connected by bluetooth is always kept near the bracelet, you don't need a GPRS module. The mobile device, then, would use it's network connection (either GPRS, LTE, WiFi, etc.) to communicate the data to the PC for processing or storage.

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


# Question
Title: How to Time the Arduino using RTC that I can operate the valves at 7am, 12pm, and 4 am?
The idea of this project is to open 3 valves one after the other for 5 minutes each, at a time like like 7am, 12pm, 4pm in a day.
The for loop should be executed at 7am, where valve 1 is open and water is pumped for 5 minutes, then valve 1 closes and valve 2 runs for 5 minutes, then valve 3 opens and runs for 5 minutes.
The program comes to a stop. Now at 12pm, the same cycle, or process repeats for the 3 valves.
The question is how do I Time the Arduino using the RTC that I can operate the valves at 7am, 12pm, and 4am?

```
#include <SoftwareSerial.h>

#include <DS3231.h>

// intialise Valves for Each Vegetation Bed

int valvePorts[] = { 4,5,6};

int valveCount= 3;

DS3231  rtc(SDA, SCL);

Time t;
const int OnHourOne = 12;   // assuming that one Tank- valve takes 5minutes each

const int OnMinOne = 00;

const int OffHourOne = 12;

const int OffMinOne = 30;

const int OnHourTwo = 16;

const int OnMinTwo = 00;

const int OffHourTwo = 16;

const int OffMinTwo = 30;

void setup()

{

 for( int thisvalve=0; thisvalve<=valveCount; thisvalve++)

{

 pinMode(valvePorts[thisvalve], OUTPUT);

}

pinMode(Waterpump,OUTPUT);             // Waterpump

  Serial.begin(9600);
}

void loop()

{

   t = rtc.getTime();

  Serial.print(t.hour);

  Serial.print(" hour(s), ");

  Serial.print(t.min);

  Serial.print(" minute(s)");

  Serial.println(" ");

  delay (1000);

   if(t.hour == OnHour && t.min == OnMin)

{

     Startwatering(1);

    }

    else if(t.hour == OffHour && t.min == OffMin)
{
      Startwatering(0);

    }

void Startwatering(int id)

 {

         if( id== 0)
                  {

                    return;

                  }

     //while(valvePorts[thisvalve],HIGH)

      if(id==1)

     {

   for( int thisvalve=0; thisvalve <=valveCount; thisvalve++)

pinMode(valvePorts[thisvalve], OUTPUT);

   {

  digitalWrite(Waterpump,LOW);

 delay(5000)

  } // close for loop

     }// close if loop

 } // close for loop

```

# Answer
> 0 votes
Many ways of doing it.

1. Poll the rtc constantly until the set time is reached. Then operate the valves. Or
2. Set an alarm on the rtc for the next time to operate the valves. The rtc will interrupt the mcu when the time is up. The mcu can then operate the valves.

You don't have to use an rtc for this.

---
Tags: rtc
---


# Question
Title: MFRC522 ReadNUID example reboots unless I include a null if statement
I'm fairly new to Arduino (and C), but not to embedded electronics and programming.

I'm using an MFRC522 module (the common one) with a Nano, and getting some strange results. They are on a very simple custom PCB I've made (the only parts on it, except for a couple of LEDs on D4 & D5) I'm using SS\_PIN on 8, and RST\_PIN on 7, which is changed from 10 & 9, because the board will also be using an NRF24L01 module on the SPI bus (not fitted yet).

And I'm using the MFRC522 library. The DumpInfo example in the library works fine, but not the ReadNUID example.

When I bring a tag/card near the reader, the sketch (sometimes) gets some of its output to the serial monitor, but then (always) the board reboots and the startup messages appear again. This happens continuously while the card is near.

I have the RFID IRQ connected to pin D3, and while thinking that may be causing the problem, and trying all sorts of stuff, I found that it wasn't. In the process I did get the sketch to work, and have distilled the fix down to two seemingly superfluous lines of code:-

Added a null if statement at the start of loop:-

```
if (GotIRQ) {}

```

and defined a volatile variable for it to test:-

```
volatile boolean GotIRQ=false;

```

Doesn't work if it's not volatile. (A clue?)

What Gives? Some dumb newbie mistake?

(I could post the entire code if required, but I've started again from the original source, and only made the 2 changes and 2 additions described above)

Here is the code:-

```
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read new NUID from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to the read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the type, and the NUID if a new card has been detected. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 8   //QQ This changed from 10
#define RST_PIN 7   //QQ This changed from 9

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key;

volatile boolean GotIRQ=false; //QQ needed for null if statement

// Init array that will store new NUID
byte nuidPICC[3];

void setup() {
  Serial.begin(9600);
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
  Serial.print(F("Using the following key:"));
  printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
}

void loop() {
  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
    piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
    piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
    rfid.uid.uidByte[1] != nuidPICC[1] ||
    rfid.uid.uidByte[2] != nuidPICC[2] ||
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    Serial.print(F("In hex: "));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
    Serial.print(F("In dec: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

/**
 * Helper routine to dump a byte array as hex values to Serial.
 */
void printHex(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

/**
 * Helper routine to dump a byte array as dec values to Serial.
 */
void printDec(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], DEC);
  }
}

```

OK, trying to cut down to a minimal example has proved useful. It seems the problem is caused by the loop that stores the NUID, but not if the superfluous if statement is present. The code is :-

```
// Cut down version of MFRC522 library ReadNUID example that exhibits strangle
// problem of rebooting the board when a card is near the reader.
// But only if:-
// * the Store NUID loop is included
// and
// * the superfluous "if" statement at start of loop() is NOT present.
// Changes from original example are indicated by comments starting with "//QQ"
// (plus a lot of removed code)

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 8   //QQ This changed from 10
#define RST_PIN 7   //QQ This changed from 9

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key;

volatile boolean GotIRQ=false; //QQ needed for null if statement

// Init array that will store new NUID
byte nuidPICC[3];

void setup() {
  Serial.begin(9600);
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
}

void loop() {
//  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Store NUID into nuidPICC array //QQ does not fail if this loop is excluded
  for (byte i = 0; i < 4; i++) {
    nuidPICC[i] = rfid.uid.uidByte[i];
  }

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

```

# Answer
> 1 votes
You've defined this array to have three elements:

```
byte nuidPICC[3];

```

those three elements are numbered 0, 1, and 2.

In this for loop:

```
for (byte i = 0; i < 4; i++) {
    nuidPICC[i] = rfid.uid.uidByte[i];
  }

```

you are writing to position 3, which is out of bounds for that array.

Once you write out of bounds on an array the behavior is undefined. Resetting is one common result. But anything could happen.

# Answer
> 0 votes
I'm assuming that the extra byte in the array is needed, possibly for a null terminator or whatever, and that the example code has a bug. I've had no further problems since changing the NUID\[3\] to NUID\[4\], so I'll leave this at that.

---
Tags: arduino-nano, rfid, reset
---


title: Receiving hex data from terminal

text:
# Question
Title: Receiving hex data from terminal
I am trying to transmit serial data from terminal to Arduino and I want to reconfirm that its the same data. But I am not able to get the right answer. I want data to be HEX. I want to check only the third last and last bytes since they will be changing every time.

I tried to write it in 2 different ways but none worked.

First try:

```
byte thisByte[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
void setup()
{
  // start serial port at 9600 bps:
  Serial.begin(9600);
}

void loop()
{
  while (Serial.available())
  {
    delay(250);
    // get the new byte:
    byte thisByte = Serial.read();
    // add it to the inputString:
    //inputString += char(intChar);

    if(thisByte == 0x03 || thisByte == 0x03)
    {
      Serial.print(thisByte, 'Hello');
      //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(50);             // wait for a second
      Serial.print(thisByte, 'Nothing');
      //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    }
    Serial.print(thisByte,HEX);
    Serial.print(" | ");
  }
}

```

Second try:

```
const byte message[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
boolean found = false;

byte byte1 = 0xAA;
byte byte2 = 0xBB;
byte byte3 = 0x06;
byte byte4 = 0x00;
byte byte5 = 0x00;
byte byte6 = 0x00;
byte byte7 = 0x01;
byte byte8 = 0x01;
byte byte9 = 0x03;
byte byte10 = 0x03;

const byte Hallo;
//void rules();
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  // put your main code here, to run repeatedly:
  //int hexIn = Serial.read();
  //Serial.write(message,2);
  //Serial.write(message,sizeof(message));
  //delay(500000);
  while(Serial.available())
  {
    delay(10);  //small delay to allow input buffer to fill
    byte c = Serial.read();
    byte message = c;

    //Serial.print(c,HEX);
    //Serial.print(" | ");

    //if (c =!byte 0xAA && c =!byte 1 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA);

    if (c == message);
    //Serial.print("I received: ");
    Serial.println(c);

    // byte c = Serial.read();  //gets one byte from serial buffer
    // readmessage += c;
  } //makes the string readString
  //Serial.print(messsage);
  //readString=""; //clears variable for new input
}

```

# Answer
First, you have to understand what “hex” means. Basically, you are representing binary data as *text*, where each byte is represented as two characters. For example, the number 42 is represented as either “2A” or “2a”. In C and C++, you can write this number as `0x2a`, but I assume your serial stream sends the raw hex data, without the “0x” prefix. Thus, on the serial stream you may receive the character “2” (character code 0x32 = 50 in decimal) followed, some time later, by “a” (charcode 0x61 = 97).

What you need is a conversion routine that takes these characters and reconstructs the binary data out of them. Here is one such routine I use. You have to provide it with an input string `in` and an output array `out` large enough to store the resulting binary data. The function will return the number of bytes filled in `*size`:

```
/*
 * Convert an hex string to binary. Spaces are allowed between bytes.
 * The output array is supposed to be large enough.
 * On return, *size is the size of the byte array.
 */
static void hex2bin(uint8_t *out, const char *in, size_t *size)
{
    size_t sz = 0;
    while (*in) {
        while (*in == ' ') in++;  // skip spaces
        if (!*in) break;
        uint8_t c = *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
        in++;
        c <<= 4;
        if (!*in) break;
        c |= *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
        in++;
        *out++ = c;
        sz++;
    }
    *size = sz;
}

```

As a mere convenience, the function above accepts spaces within the string, but only between bytes. Notice however that it does not attempt to do any error checking. You may want to improve it in this respect.

Next, you have to devise a way to frame your messages on the serial line. Serial does not provide any framing per se: it only transmits byte one by one. When dealing with text, a common scheme is to send a carriage return (`\r`) to indicate the end of a message. With this convention, you sketch has to buffer the bytes it receives until it sees a carriage return. Then it can process the whole message as a whole. This approach is nicely explained in the blog post Reading Serial on the Arduino, by Majenko, a regular contributor to this site.

Here is an example that reads an hex string, converts it to binary, and then sends it back as hex again:

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

void loop()
{
    static char buffer[1024];
    static size_t length = 0;

    if (Serial.available()) {
        char c = Serial.read();

        // On carriage return, process the received data.
        if (c == '\r') {
            Serial.println();  // echo

            // Properly terminate the string.
            buffer[length] = '\0';

            // Convert the hex data to a byte array.
            size_t byte_count = length/2;
            uint8_t data[byte_count];
            hex2bin(data, buffer, &byte_count);

            // Echo back the byte array in hex.
            for (size_t i = 0; i < byte_count; i++) {
                Serial.print(data[i], HEX);
                Serial.print(" ");
            }
            Serial.println();

            // Reset the buffer for next line.
            length = 0;
        }

        // Otherwise buffer the incoming byte.
        else if (length < sizeof buffer - 1) {
            Serial.write(c);  // echo
            buffer[length++] = c;
        }
    }
}

```

Notice the lines with the comment “echo”: they are meant to help you see in the terminal what you are typing. You can remove them if you do not what the Arduino to echo your typing. I tested it by sending

```
AA bb06 000000 0101 03 03

```

and it replied

```
AA BB 6 0 0 0 1 1 3 3

```
> 2 votes

---
Tags: arduino-mega, array, data-type, serial-data
---


# Question
Title: Which voltage should I use with a component that allows between 3v and 5.5v?
I have a DS18B20 temperature sensor that needs between 3v and 5.5v to work, as seen in its documentation.

What's the difference? Should it work better which 5.5v?

I know that a LED with more voltage will bright more but it will burn or a pump with more voltage will take water faster. But what about the temperature sensor?

# Answer
> 2 votes
According to the datasheet the absolute maximum is -0.5 V to 6.0 V.

The normal voltage for which it works according to the specifications in the datasheet is 3.0 V to 5.5 V.

That means het DS18B20 works well with 3.3 V and just as well with 5.0 V. One voltage is not "better" than the other. There is not difference. You can use it with a 3.3 V Arduino board and with a 5 V Arduino board.

The power it uses when being active is 1 mA * 5.0 V = 5 mW. It is possible that it causes some self-heating. But let's not go there. That is something for nerds.

# Answer
> 2 votes
When a sensor like this allows a range of power supply voltages it's not because one voltage is "better" than another. It's purely to allow it to work with a wider range of controllers.

The voltage you would use it with is more dictated by what it is you are using it with. If you are using it with a 5V microcontroller, such as the Arduino Uno then you would run the sensor at 5V, since that is the logic levels your MCU will be working at. If you are using it with a 3.3V microcontroller, such as a Teensy, Due, or chipKIT board, then you would run the sensor at 3.3V to maintain the right logic levels for the board you are using.

By running both the MCU and the sensor at the same voltage you remove the need for any logic level translation between the two.

# Answer
> 1 votes
It's the same thing for a measurement module. You can use the 5V of the arduino, but with a resistance of 4.7KΩ between "Data" and "5V".

Like this example

---
Tags: sensors, voltage-level, temperature-sensor, ds18b20
---


# Question
Title: How to fix the Break Beam Sensor programming issue that says "USB Device Disabled"?
I am trying to use the Adafruit Metro Mini as Arduino (can be used the same way) to program an IR Break Beam sensor and a stepper motor. I connected the beam sensor to the breadboard and plugged the Arduino into my computer. But my MAC pops up with the notification:

> "USB Device Disabled - Unplug the device using too much power to re-enable USB Devices."

What is the problem causing the issue? Did I short circuit something? I attached photos to my circuit to the post.

Thanks so much in advance.

# Answer
> 1 votes
The stepper motor driver is installed with the error (shifted) to the breadboard.

The electrolytic capacitor at the output of the voltage stabilizer in reverse polarity.

Power to Adafruit Metro Mini is put in inverse polarity ...

---
Tags: arduino-uno, sensors, usb, breadboard
---


# Question
Title: Difference between ISR and other functions in AVR twi library
I was studying the ISR for twi and I want to know how is it working.

I have two questions about the code handling for ISR and the other functions and what they do exactly:

1. My first question is about how ISR for twi is working? The following example shows a piece of the ISR for twi library. My concern here is how switch statement is working?

And probably I have to understand how TWSR works; for example, I think when twi module sends or receive an address, the TWSR is updated according to TWSR Status codes. But I really don't understand exactly what is happening?! Which happens first?

The programmer issue the twi operation; like, sending a start address. Then, the TWSR is updated with the code 0x08 which means according to the datasheet "A START condition has been transmitted". If that so, then why in the following ISR code. The status code is called as a switch result for twi operation, then it issue an action based on that??!! that what is confusing to me! So, is the procedure of twi: 1. Send start address. 2. TWSR is updated with 0x08 as a confirmation for the start action. 3. Here the ISR issues another action based on the TWSR again? This is what I didn't understand.

```
ISR(TWI_vect)
{
  switch(TW_STATUS){
    // All Master
    case TW_START:     // sent start condition
    case TW_REP_START: // sent repeated start condition
      // copy device address and r/w bit to output register and ack
      TWDR = twi_slarw;
      twi_reply(1);
      break;

```
2. My second question is about the relationship between ISR and other functions. For example,

```
  if (true == twi_inRepStart) {
twi_inRepStart = false;
do {
  TWDR = twi_slarw;
} while(TWCR & _BV(TWWC));
TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);
}
else
TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA);
while(wait && (TWI_MTX == twi_state)){
continue;
}

```

Here is another start send address operation. So which one is the real one? The start send in the ISR or this one?

# Answer
> 3 votes
The confusing thing is that there is only one interrupt, and it is called for a number of different reasons.

To make sense of why it's being called you also have to know what you have just done in order to know what to expect. In this case we have just sent a START bit, so we set the current status to "start sent". When the interrupt fires we know that it must be in response to the start bit we sent earlier having been completed, so it's time to then send the address. It's just implementing a simple state machine.

To answer your second question: both are "real" and used.

When sending data to a slave it can be easily implemented with a non-blocking interrupt arrangement. This makes it fast and efficient, and you can get on with doing other things while the data is being sent. That uses the ISR.

When reading from a slave it's harder to implement it with an ISR and still fit into the Arduino ethos of "data is available immediately", so when using `requestFrom` a simpler blocking routine is called that doesn't use the ISR. This means that when the function is completed all the data has been received and you can get on with reading it from the buffer. If you used the ISR instead then data wouldn't have arrived until some unknown time after you have made the request - so you would have to implement either some kind of callback system to execute a user function when the data has arrived, or manually block waiting for the data to arrive polling a status set by the ISR, which is pretty pointless anyway. So it's just been implemented as a simple blocking routine.

It's crude, but like much of the Arduino API it "gets the job done with the minimum of fuss" - sacrificing efficiency for simplicity and ease of use.

---

To break it down for you further:

1. When using `Wire.beginTransmission(...)` the ISR is used to empty the buffer onto the physical wires. Your sketch can continue while that is happening.
2. When using `Wire.requestFrom(...)` the ISR is *not* used. Your sketch cannot continue until the whole buffer has been received (or it times out).

When using `Wire.beginTransmission(...)` you first fill the buffer (32 bytes maximum) with your data to send. Calling `Wire.endTransmission(...)` then starts the sending of the data from the buffer using the ISR.

When you use `Wire.requestFrom(...)` a call to the `Wire.beginTransmission(...)` and `Wire.endTransmission(...)` functions are called to send the address. This uses the ISR. Following that the `twi_readFrom(...)` function is called to receive the data in a blocking fashion. That first blocks itself waiting for the ISR to signal that the I2C bus is available and it has finished sending the address. The `twi_readFrom(...)` function then, if it's using *repeated start*, sends the start bit again. If it's not using *repeated start* then it just gets on with the task of reading the data into the buffer. The actual reception of the data triggers an interrupt which copies the data into the incoming RX buffer from the FIFO, but that's pretty much all the interrupt does when receiving.

Much of the confusion (and it's confusing even to me) comes because the Wire library is written in two layers - an Arduino API wrapper class which implements the Wire object that you are familiar with, and a pure C set of helper functions which most likely were ported over from some other Atmel application library originally. This makes it quite hard to follow what is going on, since the two programming styles and ways of working are very different. Following the thought processes of two different parties working in different ways with different goals in mind is tricky at best.

To better understand how it all fits together you want to sit down with a couple of example transactions (both read and write) and a copy of the datasheet and trace exactly how the program would flow and respond to the different events and sequences within those transactions. Have the transaction waveforms on paper in front of you and mark on them where the different interrupts trigger. Follow that through in the code and work out what exactly gets called when and why it gets called. Quite an arduous task, but essential if you want to fully understand exactly what is going on in the code.

# Answer
> 0 votes
ISRs are triggered by status (more precisely status changes). For example, once the device address is sent, the hardware will set a flag, which will be serviced by the isr; if the data is sent, the hardware will set another flag, triggering the isr....

It is through this process that the transmission is carried out in an orderly fashion, without tying up the mcu.

For a more detailed description of how avr i2c modules work, check out datasheet for older lpc/nxp mcus.

The other approach is for the mcu to poll the hardware and process the flags accordingly.

Hope it helps.

---
Tags: i2c, c, isr
---


# Question
Title: delay(time); vs if(millis()-previous>time); and drift
Going through an old project, I had code on two Arduino Due that looked like this

```
void loop()
{
  foo();
  delay(time);
}

```

taking to heart the majority of literature on using `delay();` I recoded this as

```
void loop()
{
  static unsigned long PrevTime;
  if(millis()-PrevTime>time)
  {
    foo();
    PrevTime=millis();
  }
}

```

However, this seems to have created a situation where the two devices drift over a period of time when they didn't previously

My question is twofold:

1. Why would `if(millis()-PrevTime>time)` cause more drift than `delay(time)`?
2. Is there a way to prevent this drift without going back to `delay(time)`?

# Answer
> 12 votes
There's one important thing that you need to remember when working with time on an Arudino of any form:

* Every operation takes time.

Your foo() function will take an amount of time. What that time is, we cannot say.

The most reliable way of dealing with time is to only rely on the time for triggering, not for working out when the next triggering should be.

For instance, take the following:

```
if (millis() - last > interval) {
    doSomething();
    last = millis();
}

```

The variable `last` will be the time the routine triggered \*plus the time `doSomething` took to run. So say `interval` is 100, and `doSomething` takes 10ms to run, you will get triggerings at 101ms, 212ms, 323ms, etc. Not the 100ms you were expecting.

So one thing you can do is to always use the same time regardless by remembering it at once specific point (as Juraj suggests):

```
uint32_t time = millis();

if (time - last > interval) {
    doSomething();
    last = time;
}

```

Now the time that `doSomething()` takes will have no effect on anything. So you will get triggerings at 101ms, 202ms, 303ms, etc. Still not quite the 100ms you wanted - because you're looking for *more* that 100ms having passed - and that means 101ms or more. Instead you should use `>=`:

```
uint32_t time = millis();

if (time - last >= interval) {
    doSomething();
    last = time;
}

```

Now, assuming that nothing else happens in your loop you get triggerings at 100ms, 200ms, 300ms, etc. But note that bit: *"as long as nothing else happens in your loop"*...

What happens if an operation that takes 5ms happens to occur at 99ms...? Your next triggering will be delayed until 104ms. That's a drift. But it's easy to combat. Instead of saying "The recorded time is now" you say "The recorded time is 100ms later than it was". That means that no matter what delays you get in your code your triggering will always be at 100ms intervals, or drift within a 100ms tick.

```
if (millis() - last >= interval) {
    doSomething();
    last += interval;
}

```

Now you will get triggerings at 100ms, 200ms, 300ms, etc. Or if there are delays in other bits of code you may get 100ms, 204ms, 300ms, 408ms, 503ms, 600ms, etc. It always tries to run it as close to the interval as possible regardless of delays. And if you have delays that are greater than the interval it will automatically run your routine enough times to catch up with the current time.

Before you had *drift*. Now you have *jitter*.

# Answer
> 1 votes
Because you reset the timer after the operation.

```
static unsigned long PrevTime=millis();

unsigned long t = millis();

if (t - PrevTime > time) {
    foo();
    PrevTime = t;
}

```

# Answer
> 0 votes
For what you are trying to do, delay() is the appropriate way to implement the code. The reason you would want to use the if(millis()) is if you want to allow the main loop to continue to loop so your code or some other code outside of that loop can do other processing.

For example:

```
long next_trigger_time = 0L;
long interval = DESIRED_INTERVAL;

void loop() {
   do_something(); // check a sensor or value set by an interrupt
   long m = millis();
   if (m >= next_trigger_time) {
       next_trigger_time = m + interval;
       foo();
   }
}

```

This would run foo() on the specified interval while allowing the loop to continue to run in between. I put the calculation of next\_trigger\_time before the call to foo() to help minimize the drift, but it is inevitable. If drift is a significant concern, use an interrupt timer or some sort of clock/timer synchronization. Also remember that millis() will wrap around after some period of time and I didn't account for that to keep the code example simple.

---
Tags: arduino-due, code-review, timing
---


# Question
Title: Communication with socketserver fails after specific number of packets
I'm trying to implement a full-duplex communication between my ESP8266 and a socketserver running on my laptop. In concrete I need each of the devices to initiate communication whenever it needs to. The ESP is measuring temperature all the time and when the temperature changes, I want the ESP to transmit the new temperature to my laptop. On the other side I want to transmit a command from my laptop whenever I want to know the actual temperature (even if the temperature has not changed).

Therefore I have a python server-script and a python client-script both running on my laptop (see scipts below).

In the loop function on my ESP I'm also running a server and a client (script below).

Sending commands from laptop-client to ESP-server works perfectly. Even at high rates and **for days** without any problem.

Communicating the other way around (that is sending from ESP-client to laptop-server) seems to work in general, but after numerous packages (usually a few hundreds) have been sent from ESP-client to laptop-server the communication fails and the laptop-server only receives empty byte-strings. After that has happened, also sending commands from laptop-client to ESP-server does not work any more temporarily. When I shutdown the laptop-server, the ESP needs some time to "calm down" and will then continue working as usual.

Can anyone imagine what causes this behaviour? To me it looks like a buffer overflow or something like that. I appreciate any help and hints about how to implement the desired functionality (do I actually need to run a server on both my laptop and the ESP?).

**Laptop-Server**:

```
import socket
import time

# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

host = "0.0.0.0"
port=1992

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

try:
  while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()
    try:
        data = clientsocket.recv(1024)
        print(str(addr),":  ",data)
        clientsocket.send("hi there, "+str(addr)+"\n")
        clientsocket.close()
    except:
        pass
except:
  print(" !!! an exception occured !!!")
  serversocket.shutdown(socket.SHUT_RDWR)
  serversocket.close()

```

**Laptop-Client**:

```
import os,sys,re,time,socket,threading,readline

timeout=2

HOST, PORT = "ESP-IP", 1991

response=""
def s_client(data):
    global response
    try:
        response='Error: received no response'

        # Connect to server and send data
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.connect((HOST, PORT))
        sock.sendall(bytes(data + "\n", "utf-8"))

        # Receive data from the server and shut down
        response=str(sock.recv(1024), "utf-8")
    except ConnectionRefusedError:
        response='Error: connection refused by remote host'
    except socket.timeout:
        response='Error: connection timed out'
    finally:
        sock.close()
    return 1

while True:
    try:
        print('  -->  '+s_client(input('_$ ')))
    except KeyboardInterrupt:
        break

```

**ESP-script** (containing server and client):

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

IPAddress laptop_ip=(0,0,0,0);
uint16_t TCP_port=1991;
uint16_t TCP_remote_port=1992;
WiFiServer TCPserver(TCP_port);
WiFiClient client;

void ESP_server(void){
  if (!client.connected()) {
    client=TCPserver.available();
  }
  else {
    laptop_ip=client.remoteIP();
    Serial.println("received request");
    int query_l=client.available();
    if(query_l>0){
      String query="";
      for (int nb = 0; nb < query_l-1; nb++){
        query+=(char) client.read();
      }client.read();
      Serial.print("received from laptop: ");Serial.println(query);
      //  Do something with query and return the result
      //  For simplicity I'm just returning a constant value
      client.write("command transmitted");
    }
  }
}

void ESP_client(String message){
  WiFiClient TCPclient;
  if (TCPclient.connect(laptop_ip, TCP_remote_port)){
    TCPclient.print(message);
  }
}

void setup() {
  Serial.begin(115200);
  WiFi.begin("MYSSID","MYPASS");
  Serial.print("connecting with WiFi  ");
  while(WiFi.status()!=WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }Serial.println();
  TCPserver.begin();

  // wait until a command has been received from the laptop
  // ESP_server stores the remote (laptop) ip in laptop_ip
  while(laptop_ip==(0,0,0,0)){
    ESP_server();
  }
}

int temp=0;
void loop() {
  // handle commands sent from my laptop
  ESP_server();

  //  here is a temperature meaurement returning the current temperature
  //  I've replaced it with a temperature generator
  if(temp<30){temp++;}
  else{temp=0;}

  // temperature has changed and needs to be transmitted by this function
  ESP_client((String) temp);
}

```

The above code differes from the code I'm actually running but it reproduces my problem. I hope that somebody can figure out a misstake or give my some advice about how I could implement things in a better way. Actually I'm not sure whether the misstake is on laptop- or ESP-side but as the ESP crashes **sometimes** I think it's the ESP...

I'm using the arduino IDE for flashing, btw.

# Answer
> 1 votes
I found my stupid mistake: By using `try` without catching **specific** exceptions (I know one shouln't do that) in my Laptop-Server script I didn't recognize that I was trying to send unencoded strings. So, `clientsocket.send("hi there, "+str(addr)+"\n")` has to be `clientsocket.send(bytes(("hi there, "+str(addr)+"\n").encode('utf-8')))` instead.

# Answer
> 1 votes
close the disconnected socket before reconnecting

```
if (!client.connected()) {
  client.stop();
  client=TCPserver.available();
}

```

---
Tags: esp8266, code-review, python, tcpip, buffer
---


# Question
Title: Are pins 0 and 1 (Rx and Tx) parallel with the USB jack? Can I connect another USB jack th 0 and 1 and use it to upload sketches?
I have a compact weatherproof enclosure and the onboard USB jack of my Mega is close to the edge. I didn't want to add a bulky weatherproof USB jack, so I'd like to just leave a female USB pigtail loose inside the enclosure.

The only thing is, I want to avoid the extra assembly step of soldering leads directly to the lugs on the board. I'd like to make a shield instead, with screw lug headers to attach all my wires to. That way a lot of my connections can be solderless and the assembly tech can just plug in the shield.

Can I connect the four wires of a USB cable to the header pins? I suspect I'd use Vin, GND, pin 0 and pin 1, but I'm not 100% sure. Thanks for your advice, gentlemen.

# Answer
> 1 votes
No. For many reasons. No. USB is not TTL. You need an adapter to connect rx/tx pins of arduino to USB. And the on-board adapter has the DTR line connected to reset the Atmega before writing a program into it. Without it, you would need to push the reset button in the right moment.

---
Tags: serial, arduino-mega
---


# Question
Title: Transmit IR-Signal A, Receive IR-Signal B
I used the following program to send an IR code and I got the an unexpected result as below:

```
/*
   IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
   An IR LED must be connected to Arduino PWM pin 3.
   Version 0.1 July, 2009
   Copyright 2009 Ken Shirriff
   http://arcfn.com
*/

#include <IRremote.h>

IRsend irsend;

int j = 0;
void setup()
{
}

void loop() {
  for (int i = 0; i < 3; i++) {
    irsend.sendNEC(0xFF6897, 32);
    delay(40);
    j = j + 1;
  }
  delay(5000); //5 second delay between each signal burst
}

```

With the following schematic:

I expected to receive:

> FF6897 Decoded NEC: FF6897 (32 bits) Raw (68): 8750 -4450 550 -550 500 -600 550 -550 550 -550 550 -550 550 -600 500 -600 500 -600 500 -1650 550 -1650 550 -1650 500 -1650 550 -1650 550 -1650 500 -1700 500 -1650 550 -550 500 -1700 550 -1600 550 -600 500 -1650 550 -600 500 -600 500 -600 500 -1650 550 -550 550 -600 500 -1650 500 -600 500 -1700 500 -1650 550 -1650 550

Instead I receive consistently

> C101E57B Unknown encoding: C101E57B (32 bits) Raw (68): 8850 -4450 500 -650 450 -600 500 -600 550 -550 500 -650 450 -650 500 -600 450 -650 450 -1800 450 -1700 500 -1750 500 -1700 500 -1750 500 -1700 500 -1750 450 -1750 500 -600 500 -1750 450 -1750 500 -600 450 -1750 500 -650 450 -600 550 -600 500 -1700 500 -600 500 -600 500 -1750 500 -600 500 -1700 500 -1700 550 -1700 450

anyone knows how to fix this?

Code the Reciever uses to decode the just send signal:

```
/*
 * IRremote: IRrecvDump - dump details of IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
 * LG added by Darryl Smith (based on the JVC protocol)
 */

#include <IRremote.h>

/*
*  Default is Arduino pin D11.
*  You can change this to another available Arduino Pin.
*  Your IR receiver should be connected to the pin defined here
*/
int RECV_PIN = 6;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void dump(decode_results *results) {
  // Dumps out the decode_results structure.
  // Call this after IRrecv::decode()
  int count = results->rawlen;
  if (results->decode_type == UNKNOWN) {
    Serial.print("Unknown encoding: ");
  }
  else if (results->decode_type == NEC) {
    Serial.print("Decoded NEC: ");

  }
  else if (results->decode_type == SONY) {
    Serial.print("Decoded SONY: ");
  }
  else if (results->decode_type == RC5) {
    Serial.print("Decoded RC5: ");
  }
  else if (results->decode_type == RC6) {
    Serial.print("Decoded RC6: ");
  }
  else if (results->decode_type == PANASONIC) {
    Serial.print("Decoded PANASONIC - Address: ");
    Serial.print(results->address, HEX);
    Serial.print(" Value: ");
  }
  else if (results->decode_type == LG) {
    Serial.print("Decoded LG: ");
  }
  else if (results->decode_type == JVC) {
    Serial.print("Decoded JVC: ");
  }
  else if (results->decode_type == AIWA_RC_T501) {
    Serial.print("Decoded AIWA RC T501: ");
  }
  else if (results->decode_type == WHYNTER) {
    Serial.print("Decoded Whynter: ");
  }
  Serial.print(results->value, HEX);
  Serial.print(" (");
  Serial.print(results->bits, DEC);
  Serial.println(" bits)");
  Serial.print("Raw (");
  Serial.print(count, DEC);
  Serial.print("): ");

  for (int i = 1; i < count; i++) {
    if (i & 1) {
      Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
    }
    else {
      Serial.write('-');
      Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC);
    }
    Serial.print(" ");
  }
  Serial.println();
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    dump(&results);
    irrecv.resume(); // Receive the next value
  }
}

```

Schematic wise:

one IR reciever with VCC and Ground connect and signal-out on pin 6

# Answer
> 1 votes
In the received RAW codes, the width of the modulated pulses is less than the expected value. And the width of the spaces is bigger than expected.

This is due to the lack of an infrared sensor.

Use infrared receiver another model. For example TSOP4838.

Or try reducing MARK\_EXCESS in the IRremoteInt.h of the Arduino-IRremote library from 100 to 50 or 0.

```
...
// Pulse parms are ((X*50)-100) for the Mark and ((X*50)+100) for the Space.
// First MARK is the one after the long gap
// Pulse parameters in uSec
//

// Due to sensor lag, when received, Marks  tend to be 100us too long and
//                                   Spaces tend to be 100us too short
#define MARK_EXCESS    0
...

```

And please increase the delay time in transmitter sketch (to avoid codes overlapping) :

```
...
for (int i = 0; i < 3; i++){
  irsend.sendNEC(0xFF6897, 32);
  delay(200);
  j = j + 1;
}
...

```

---
Tags: arduino-uno, arduino-mega, ir
---


# Question
Title: External ADC reference when using MATLAB support package for Arduino
I am using the MATLAB support package for Arduino.

However, I need to configure the ADC reference to external. MATLAB documentation doesn't really explain how to do this?

Is there any way I can use the MATLAB support package and configure the Analog pins to use external ADC reference?

# Answer
> MATLAB documentation doesn't really explain how to do this?

it makes sense. read your arduino documentation instead.

> Is there any way I can use the MATLAB support package and configure the Analog pins to use external ADC reference?

absolutely.
> -1 votes

---
Tags: analogread, adc, matlab, analog-sampling, analogreference
---


# Question
Title: How the output of a bicycle dynamo can be displayed using Arduino?
I am on a project in which I need to make bicycle dynamo frequency meter. The power generator’s output should vary with the speed of the wheel.

Which parts do I need to make it work?

The project should look like: : http://www.lanzo.se/experiments/dynamo/dynamo.html or http://practicalphysics.org/bicycle-dynamo-and-oscilloscope.html

--\>without oscilloscope ( which is replaced with Arduino and panel )

# Answer
> 1 votes
The first thing to look at before you connect the bicycle dynamo to an Arduino is what type of signal / voltage it generates. The link you've provided: http://www.lanzo.se/experiments/dynamo/dynamo.html gives you the answer. It's an AC signal which varies between +4V and -4V (It could be much higher if you spin it faster). On the Atmega328P data sheet under "Absolute Maximum Ratings" it says "Voltage on any Pin except RESET with respect to Ground -0.5V to VCC +0.5V". Obviously, -4V exceeds the -0.5V maximum so don't connect it directly to an Arduino.

The signal from the dynamo to Arduino must be limited to between 0V and 5V (for an Arduino operating at 5V). The answer on how to accomplish this is a general electronics question and should be asked on a different forum e.g. https://electronics.stackexchange.com/questions/132330/8v-ac-signal-into-3-3v-digital-input-pin

The "frequency meter" part of your question is easy to build with an Arduino. You could use an Uno or something smaller like a Pro Mini with a 16 x 2 LCD display and this library: https://github.com/k3ng/k3ng\_antenna\_tuner/tree/master/libraries/FreqCounter. An I2C backpack for the LCD is only a dollar more and makes the wiring much easier. To use the backpack you'll need this library: https://github.com/marcoschwartz/LiquidCrystal\_I2C.

# Answer
> 1 votes
It al depends on what is the maximum output of the dynamo.

* less than 5V (not likely): great just connect it directly with the Analog measuring pin of the Arduino (A1- A7)
* more than 5V: we got different options here
    + Make a simple voltage divder to measure the output
    + use an external ADC

---
Tags: electronics, signal-processing
---


# Question
Title: Looking for link to Double Pole Single Throw (DPST) relay for Arduino
Need to find a DPST relay that is 'Arduino' friendly and that is capable of 30A at 240VAC. Anyone can share links ?

Not looking for recommendation, just ideas on what you saw or used in the past.

Thanks.

# Answer
> 1 votes
A relay that can switch 30A on mains voltage is not going to be able to switch directly from 5V. Getting something that can switch from 24V is much more realistic.

High amp relays are often called contactors. 4-pole ones are not uncommon for industrial motor applications. 3 high-amp poles are for 3-phase power and a low-amp one for a control signal.

You can buffer up the signal using a transistor (you'd need one anyway to supply the coil amps) or another relay.

# Answer
> 1 votes
Do not be scared from other answers. There are relays which hold the coil with 5 V from Arduino. Like the relay on this Grove 30 A Relay Module. It is powered from 5 V pin and the command to close is from the GPIO pin (works with 3.3V IO too).

Use two of these SPDT modules, if you can't find DPST powered with 5 V.

If you will use the Grove module and you do not use other Grove modules, there is no need to buy the Grove base shield. You can connect the module with this cable.

# Answer
> 0 votes
You will be hard-pressed to find a mechanical relay that you can directly connect to the Arduino digital pins. Any general purpose relay that fits your specs for the switched side will do, but you will need to pay attention to the datasheet for the coil voltage and current required to activate the relay.

Then, you'll want to use a driver circuit like a transistor (BJT or MOSFET) so that the low-voltage, low-current digital output of the Arduino can control the larger-current needed to trip the relay coil.

---
Tags: arduino-mega, relay
---


title: Arduino uno and ESP8266

text:
# Question
Title: Arduino uno and ESP8266
**Scenario :**

* I want to connect ESP8266 to Raspberry-pi's wifi network.
* Arduino Uno is connected to ESP8266
* Raspberry-pi will send a signal (1/0) to ESP8266, when its 1 Arduino will turn on/off a Relay.
* I do not have a USB to UART Serial module

So my question is how to complete this task? Is it a feasible one?

I had been looking for many websites, almost all are using USB to UART Serial module to burn firmware to ESP8266.

# Answer
> 2 votes
You can use the USB-to-Serial adapter of the Arduino UNO, it has one on-board (ATmega16U2). Check the schematic of the UNO to understand what's going on.

First, upload an empty sketch to the UNO's ATmega328P, to make sure that it doesn't use the UART.

Connect the TX pin of the ATmega16U2 (i.e. the RX pin of the Arduino, digital pin 0) to the RX pin of the ESP8266. Connect a 2kΩ resistor between the ESP's RX pin. Together with the 1kΩ resistor on the ATmega16U2's TX line (on the Arduino), this creates a voltage divider that acts as a level shifter from 5V to 3.3V.

Connect the RX pin of the ATmega16U2 (i.e. the TX pin of the Arduino, digital pin 1) to the TX pin of the ESP8266.

Connect the grounds together as well.

In the Arduino IDE, select the ESP8266 under Tools \> Board. Then enter programming mode on the ESP:

1. Bring reset low
2. Bring GPIO0 low
3. Bring reset high
4. Bring GPIO0 high

Then upload your sketch to the ESP.

I recommend adding simple push buttons and pull-up resistors: (The ESP-01 has GPIO15 shorted to ground internally, so you don't have to worry about that. If you were using an ESP-## module that breaks out this pin, you need an external pull-down resistor.)

Keep in mind that you will also need a decent 3.3V power source, and some decoupling capacitors.

A Beginner's Guide to the ESP8266

---
Tags: arduino-uno, wifi, communication
---


# Question
Title: ESP8266 cannot connect to an existing network after using AT command
I followed this tutorial to connect the ESP8266 to a wifi network using AT commands. I used the below schematics (without the connection between ESP's CPIO 0 and Arduino's Ground):

After that, I was able to follow through the tutorial and got this response in the Serial Monitor:

That means my ESP8266 has successfully connected to my Wifi named W3. However, I decided to switch the mode of my ESP8266 from Network Device (mode 1) to Both network device AND Access Point (mode 3) (at this point I called AT+CWJAP? and can still see that it's connected to W3 wifi). I then was able to see the ESP wifi in my wifi list as (AI-THINKER\_4C8CF2) but when I connected to it, I cannot connect to the internet. I'm wondering what the problem is and would appreciate any help.

*Note:* **The reason why I switched to mode 3 is because I want to control an Arduino Pro Mini (instead of Arduino Pro) using NodeJS.** I followed another tutorial and I figured that I need to connect to an ESP8266 access point.

I uploaded the StandardFirmataSketchPlus to my Arduino Pro Mini, with the baud rate set to 115200 (which is the same baud rate with my ESP8266). The schematic I used is similar to the one below, except I used a 3.3V Pro Mini and a Lipo battery, instead of a 5V:

The nodejs code is below:

```
var VirtualSerialPort = require('udp-serial').SerialPort;
var firmata = require('firmata');
var five = require("johnny-five");
var sp = new VirtualSerialPort({
  host: '192.168.1.243' //I got this number from the AT command (STAIP above)
 });

var io = new firmata.Board(sp);

io.once('ready', function(){
    io.isReady = true;

    var board = new five.Board({io: io, repl: true});

    board.on('ready', function(){
        var led = new five.Led(12);
        led.blink(3000);
    });
});

```

This code is to test the connection between Arduino and Nodejs and when I run this file, it doesn't work.

# Answer
you have Firmata in Atmega, AT firmware in ESP and the 'blink led' js on computer.

you did not follow the tutorial properly. it requires jonny-five firmware in esp8266
> 1 votes

---
Tags: arduino-uno, esp8266, wifi, arduino-pro-mini, node.js
---


# Question
Title: Should I use an accelerometer or gyroscope in my project?
A friend and I are working on a sign language translation glove.

Our glove currently successfully uses 5 flex sensors to determine the bend of each finger and can accurately detect letters in the sign language alphabet.

We are now trying to add the functionality to detect one-handed words. Many of these words involve making a letter, but adding some motion. For example, the colour "blue" involves making a B, then shaking/waving your hand in the B position.

We are wondering which type of sensor would be able to handle this. From our research so far, we assume this will either be an accelerometer or a gyroscope, but are not sure which one would be best in the scope of our project.

Any help would be much appreciated!

# Answer
> 1 votes
Use both. Accelerometer measure movement in direction of axes when gyroscope measure rotational movement. Being very delicate you can spin accelerometer and sensor won't see any changes, and you can move gyro in one axis without sensor detection. Having both mounted on one board (or in one casing) there is no possibility that motion will be missed by both. Look at the pictures what the sensors do:

There is a plenty of integrated accelerometer-gyro sensors, for example MPU-6050 Accelerometer + Gyro with supporting libraries. Please check here

# Answer
> 0 votes
An accelerometer is a better choice here. For your application, you aren't worried about initial motion but just acceleration. Plus, an accelerometer is cheaper.

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


# Question
Title: When Raspberry Pi is preferred over Arduino
We are doing some projects in class. One of my friends is doing a weather and humidity station using raspberry Pi with a couple of sensors and LCD. I have a little experience in Arduino. So I asked her, why doesn't she do it using an Arduino? She said Pi is more 'powerful'. In what aspects, is it more powerful than Arduino? When should I go for Raspberry Pi over Arduino?

# Answer
Somewhat of an opinionated question but I'll give some feedback. It depends on various things:

* How much UX and UI you want to give to your client
* How easily can you program it
* Which is a cheaper solution
* How fast do you want the program to run
* What is more durable and how long do you want to use the device

To prevent this answer from being lengthy, I'll do a quick comparison from my experiences with both.

**Arduino:** Cheap, easy to program, capable of flexibility with UX and UI but has very limited memory. The Arduino is typically good for something that can just complete tasks on their own. I've written state machines and have used it for PLCs with an Arduino. It's a good device for a cheaper budget. Arduino is pretty fragile, however.

**Raspberry Pi:** More expensive, a lot more powerful in terms of processing speed, has a lot more memory, extremely good for UX and UI devices that are being developed, good for artificial intelligence, state machines, PLCs, etc. Also really good for data logging, image processing, and radio frequency applications. You can also boot an operating system on it (e.g. Linux/Unix). In other words, a Raspberry Pi can used as a computer while the Arduino... well I guess it depends how you define, "computer" LOL.

So if you're trying to do something as simple as using sensors and LEDs, I'd go for the Arduino Uno.
> 7 votes

# Answer
The claim that the Pi is more "powerful" is a bit misleading. What does "powerful" really mean? And is it relevant to making a weather station?

I made a temperature and humidity sensor as described here using an Atmega328P (the processor that is in the Arduino Uno). The estimated average power consumption is 42 µA which has allowed it to run from 3 x AA batteries for a couple of years before they needed replacing. I think you'll find that the Pi with its more "powerful" processor and extra components would not be able to do that.

I see from a quick search that the Pi consumes 80 mA to 240 mA when idle (depending on the model). This would make a Pi-powered weather station eat through batteries 2000 times as quickly. Perhaps that would be a consideration.

The Pi is really a Unix PC on a board, which means it goes through the normal boot sequence with a possibility of errors occurring during booting. To see what those errors are you need to connect up a keyboard and screen, or connect via a network to it from another PC.

I don't want to run down the Pi - it's a nice cheap Unix computer on a small board. But the Arduinos (many of them) are somewhat simpler to program. You don't need to worry about the operating system for a start. For a weather station, taking a reading every 5 minutes, who cares if the Pi can take the reading "50 times faster"?

---

## Speed of recovery from sleep

I have an answer about letting serial data wake an Arduino \- after some experimenting I was able to get the Atmega328P to wake from its deepest sleep (260 nA - yes 0.260 µA!) within 6 clock cycles (750 ns). I doubt you could achieve that on the Pi, either the low power consumption, or waking up in under a microsecond.

This was fast enough to detect the start bit in serial data at 9600 baud, process the start bit, and then the rest of the incoming byte without losing data.
> 10 votes

# Answer
As opposed to the Arduino boards, the Raspberry Pi is a single-board computer with a quad-core CPU, a GPU, on-board RAM, and many peripherals. The main difference between the Pi and the Arduino (or any basic microcontroller) is the operating system. The Pi runs many Linux distributions (Debian being the official one), enabling the user to execute complex computing tasks that would be impossible to run on Arduino without external circuitry. Hence, the Raspberry Pi would be adequate for any software requiring significant CPU/GPU power or memory. Keep in mind that most Arduino's can be interfaced with the same type of peripherals that are found on the Raspberry Pi, although processing power might be lacking. Also, low-level interfacing with analog signals is much more convenient with Arduino, since it has integrated ADCs (analog-to-digital converters).
> 6 votes

# Answer
> When should I go for Raspberry Pi over Arduino

There is always the price difference but apart from that I would say: The Raspberry Pi can do everything the Arduino can and do it better and faster **EXCEPT** tasks which are very time critical. Thus if you need to responds to events in micro seconds or millisecond or if you need to generate signals in those order of magnitudes you will need an Arduino.
> 4 votes

# Answer
In "pure hardware" based systems, real time systems, you can always prefer Arduino over Pi with OS. Power consumption, price are other plus points for UNO. Pi is always the better one in complex computing tasks, where its OS simplifies those tasks. But you don't wanna use a "computer" for sensor related projects for sure !
> 2 votes

---
Tags: arduino-uno, hardware, raspberrypi, performance
---


# Question
Title: Arduino Yun with PoE does not work when powered via PoE
I have a Arduino Yun with PoE with LininoOS version

> Linux arduino 3.3.8 #1 Thu Jun 2 12:28:33 CEST 2016 mips GNU/Linux

I have the Version 4.0 of the module.

I often notice that when I connect the module via a USB cable and login via Serial the **WAN** and **WLAN** LEDs blink and I can SSH via both the mediums.

However I cannot do the same when the Yun is completely powered via an Ethernet Cable and the I see the Yun frequently restarting and becoming inaccessible via SSH.

I cannot troubleshoot this problem via software as whenever I connect the USB cable along with the Ethernet Cable the power supply switches completely to the USB and the PoE stops and everything suddenly works well again.

Has someone faced the same issue? Is it because of the High Frequency Whistle problem where I need to solder a **100µF Electrolytic Capacitor** to the PoE adapter?

### Update

I measured the **5 V** and **3.3 V** pins on the Yun they provide their respective voltages via a multimeter.

I have a Microsens fast ethernet switch with PoE which provides standard **(minimum 44V DC)**

> Apparently, the **WAN** LED blinks indicating the Ethernet Connection is available however everytime I ping the Yun it goes down.

# Answer
> 0 votes
## PoE Adapter

**Silvertel AG9600 1R** requires a `100µF 16V Electrolytic Capacitor` between it's `PIN 7` and `PIN 8`

According to the PoE Yún Thread the capacitor polarity should be as follows:

> PIN 7 --\> Capacitor\_Negative. PIN 8 --\> Capacitor\_Positive

solved my problem. I think the default **470uF** capacitor might not be able to charge-discharge appropriately with data signals in the PoE.

---
Tags: power, arduino-yun, hardware
---


# Question
Title: What do symbols like UCSR0C, UMSEL01, etc. means?
I have a code with a connection to serial port:

```
// Set baud rate
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
// Disable USART rate doubler (arduino bootloader leaves it enabled...)
UCSR0A &= ~(1 << U2X0);
// Set async, no parity, 1 stop, 9bit
UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(0<<UPM01)|(0<<UPM00)|(0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00);
UCSR0B |= (1<<UCSZ02); // 9bit
// Enable rx/tx
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);

```

I see the comments but I want to know exactly what does these chunks means. Is there any complete documentation about these symbols?

# Answer
> 5 votes
Take a look in the datasheet under the "20. USART0" section:

http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P\_datasheet\_Complete.pdf

I will list the names of the registers, what they are called, and then what your code is doing specifically:

* UBRR0H and UBRR0L together form the baud rate divider. Your program probably uses F\_CPU and `<util/setbaud.h>` to calculate a divider and set the baud rate. For more information see Table 20-12.
* UCSR0A "USART Control and Status Register n A" -- This line is enabling the U2X0 which doubles the transmission speed
* UCSR0C "USART Control and Status Register n C" -- This line is enabling the UCSZ01 and UCSZ00 bits to set parity check to "Enabled, Odd Parity". See Table 20-9. This line has extra information, all the statements with 0\<\< actually do nothing.
* USCR0B " USART Control and Status Register n B" -- This line is setting the UCSZ02 bit which is described here: "The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (Character SiZe) in a frame the Receiver and Transmitter use. " This basically allows you to select 9 bit wide serial if you would like (8 bit is more common)
* The final USCR0B line enables tx and rx

# Answer
> 0 votes
I strongly recommend you to read the datasheet. You are confusing UART module with GPIO module. Once you use one pin for one purpose (say serial comunication) you cannot use it for another thing (say general I/O to read a physical button state). Of course it is possible if you write your code in a way it changes all the registers (the ones you call "symbols") on excecution time. But just be carefull that the routines that used those pins for UART don't execute meanwhile!

---
Tags: serial, softwareserial
---