title: compilation error in arduino

text:
# Question
Title: compilation error in arduino
I'm new to arduino. I had found an interesting project to work on with, but unfortunately I'm held up at compilation error. I tried finding answers to this problem but not able to understand.

Here is my code:

```
    // Include Libraries
#include <Wire.h>
#include <Servo.h>
#include <Adafruit_TCS34725.h>

// Initialize Sensors
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);
Servo myservoRed;
Servo myservoGreen;
Servo myservoBlue;

int posRed = 0;
int posGreen = 0;
int posBlue = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("Color View Test!");

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1); // halt!
  }

  //Attach servos to ouput pins
  myservoRed.attach(9);
  myservoGreen.attach(6);
  myservoBlue.attach(3);

  // Initialize Fan pin
  pinMode(7, OUTPUT);

}

void loop() {
  uint16_t clear, red, green, blue;
  tcs.setInterrupt(false);
  delay(60);  // takes 50ms to read
  tcs.getRawData(&red, &green, &blue, &clear);
  tcs.setInterrupt(true);
  Serial.print("C:\t"); Serial.print(clear);
  Serial.print("\tR:\t"); Serial.print(red);
  Serial.print("\tG:\t"); Serial.print(green);
  Serial.print("\tB:\t"); Serial.print(blue);

  // Map color to motor position
  posRed = map(red,100,10000,10,80);
  Serial.print("\tRedPos:\t"); Serial.print(posRed);
  posGreen = map(green,100,10000,10,80);
  Serial.print("\tGreenPos:\t"); Serial.print(posGreen);
  posBlue = map(blue,100,10000,10,80);
  Serial.print("\tBluePos:\t"); Serial.print(posBlue);
  Serial.println();

  // Write position to motor
  myservoRed.write(posRed);
  delay(100);
  myservoGreen.write(posGreen);
  delay(100);
  myservoBlue.write(posBlue);
  delay(100);

}

```

Here is the Wire.h:

```
/*
 * TwoWire.h - TWI/I2C library for Linux Userspace
 * Copyright (c) 2013 Parav https://github.com/meanbot.
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef TwoWire_h
#define TwoWire_h

#include "Stream.h"
#include "variant.h"

#define BUFFER_LENGTH 32
#define I2C2 0x4819c000
#define I2C1 0x00000000
#define WIRE_INTERFACES_COUNT 1

class TwoWire : public Stream {
public:
    TwoWire(void(*begin_cb)(void));
    void begin();
    void begin(uint8_t);
    void begin(int);
    void beginTransmission(uint8_t);
    void beginTransmission(int);
    uint8_t endTransmission(void);
    uint8_t endTransmission(uint8_t);
    uint8_t requestFrom(uint8_t, uint8_t);
    uint8_t requestFrom(uint8_t, uint8_t, uint8_t);
    uint8_t requestFrom(int, int);
    uint8_t requestFrom(int, int, int);
    virtual size_t write(uint8_t);
    virtual size_t write(const uint8_t *, size_t);
    virtual int available(void);
    virtual int read(void);
    virtual int peek(void);
    virtual void flush(void);
    void onReceive(void(*)(int));
    void onRequest(void(*)(void));

    inline size_t write(unsigned long n) { return write((uint8_t)n); }
    inline size_t write(long n) { return write((uint8_t)n); }
    inline size_t write(unsigned int n) { return write((uint8_t)n); }
    inline size_t write(int n) { return write((uint8_t)n); }
    using Print::write;

    void onService(void);

private:
    // RX Buffer
    uint8_t rxBuffer[BUFFER_LENGTH];
    uint8_t rxBufferIndex;
    uint8_t rxBufferLength;

    // TX Buffer
    uint8_t txAddress;
    uint8_t txBuffer[BUFFER_LENGTH];
    uint8_t txBufferLength;

    // Service buffer
    uint8_t srvBuffer[BUFFER_LENGTH];
    uint8_t srvBufferIndex;
    uint8_t srvBufferLength;

    // Callback user functions
    void (*onRequestCallback)(void);
    void (*onReceiveCallback)(int);

    // Called before initialization
    void (*onBeginCallback)(void);

    // Timeouts (
    static const uint32_t RECV_TIMEOUT = 100000;
    static const uint32_t XMIT_TIMEOUT = 100000;

    uint8_t adapter_nr;
    int i2c_fd;
    int i2c_transfer;
};

#if WIRE_INTERFACES_COUNT > 0
extern TwoWire Wire;
#endif
#if WIRE_INTERFACES_COUNT > 1
extern TwoWire Wire1;
#endif

#endif

```

Here is Wire.cpp:

```
/*
 * TwoWire.h - TWI/I2C library for Linux Userspace
 * Copyright (c) 2013 Parav https://github.com/meanbot.
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

extern "C" {
#include <string.h>
#include <i2c.h>
}

#include "Wire.h"

#include <Mux.h>
#include <trace.h>
#define MY_TRACE_PREFIX "Wire"

TwoWire::TwoWire(void(*_beginCb)(void)) : rxBufferIndex(0), rxBufferLength(0),
                      txAddress(0), txBufferLength(0),
                      srvBufferIndex(0), srvBufferLength(0),
                      onBeginCallback(_beginCb),
                      adapter_nr(-1), i2c_fd(-1),
                      i2c_transfer(0)
{
    // Empty
}

void TwoWire::begin(void)
{
    muxSelectI2c(0);
    if (onBeginCallback)
        onBeginCallback();
    if ((adapter_nr = i2c_getadapter(I2C2)) < 0) {
        return;
    }
    if ((i2c_fd = i2c_openadapter(adapter_nr)) < 0) {
        return;
    }

}

void TwoWire::begin(uint8_t address)
{
    if (onBeginCallback)
        onBeginCallback();
}

void TwoWire::begin(int address)
{
    begin((uint8_t) address);
}

uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
{
    if (quantity > BUFFER_LENGTH)
        quantity = BUFFER_LENGTH;

    /* Set slave address via ioctl  */
    i2c_setslave(i2c_fd, address);

    if(i2c_transfer) {
    /* Need to perform a combined read/write operation
     */
        i2c_transfer = 0;
        if (sendStop == false)
            return 0;
        i2c_add_to_buf(address, 1, rxBuffer, quantity);
        if (!i2c_readwrite(i2c_fd)) {
            rxBufferIndex = 0;
            rxBufferLength = quantity;
            i2c_transfer = 0;
            return quantity;
        } else
            return 0;
    }
    if (i2c_readbytes(i2c_fd, rxBuffer, quantity) < 0)
        return 0;
    // set rx buffer iterator vars
    rxBufferIndex = 0;
    rxBufferLength = quantity;

    return quantity;
}

uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
    return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
}

uint8_t TwoWire::requestFrom(int address, int quantity)
{
    return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
}

uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
{
    return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) sendStop);
}

void TwoWire::beginTransmission(uint8_t address)
{
    if (i2c_fd < 0 || adapter_nr < 0)
        return;
    /* set slave address via ioctl in case we need to perform terminating
     * write operation
     */
    i2c_setslave(i2c_fd, address);
    // save address of target and empty buffer
    txAddress = address;
    txBufferLength = 0;
}

void TwoWire::beginTransmission(int address)
{
    beginTransmission((uint8_t) address);
}

//
//  Originally, 'endTransmission' was an f(void) function.
//  It has been modified to take one parameter indicating
//  whether or not a STOP should be performed on the bus.
//  Calling endTransmission(false) allows a sketch to
//  perform a repeated start.
//
//  WARNING: Nothing in the library keeps track of whether
//  the bus tenure has been properly ended with a STOP. It
//  is very possible to leave the bus in a hung state if
//  no call to endTransmission(true) is made. Some I2C
//  devices will behave oddly if they do not see a STOP.
//
uint8_t TwoWire::endTransmission(uint8_t sendStop)
{
    int err;
    if (sendStop == true) {

        // transmit buffer (blocking)
        if (txBufferLength > 1)
            err = i2c_writebytes(i2c_fd, txBuffer, txBufferLength);
        else if (txBufferLength == 1)
            err = i2c_writebyte(i2c_fd, *txBuffer);
        else
        /* FIXME: A zero byte transmit is typically used to check for an
         * ACK from the slave device. I'm not sure if this is the
         * correct way to do this.
         */
            err = i2c_readbyte(i2c_fd);
        // empty buffer
        txBufferLength = 0;
        if (err < 0)
            return 2;
        return 0;
    } else {
    /* sendStop = false
     * pretend we have held the bus while
     * actually waiting for the next operation
     */
        i2c_add_to_buf(txAddress, 0, txBuffer, txBufferLength);
        i2c_transfer = 1;
        return 0;
    }
}

//  This provides backwards compatibility with the original
//  definition, and expected behaviour, of endTransmission
//
uint8_t TwoWire::endTransmission(void)
{
    return endTransmission(true);
}

size_t TwoWire::write(uint8_t data)
{
    if (txBufferLength >= BUFFER_LENGTH)
        return 0;
    txBuffer[txBufferLength++] = data;
    return 1;
}

size_t TwoWire::write(const uint8_t *data, size_t quantity)
{
    for (size_t i = 0; i < quantity; ++i) {
        if (txBufferLength >= BUFFER_LENGTH)
            return i;
        txBuffer[txBufferLength++] = data[i];
    }
    return quantity;
}

int TwoWire::available(void)
{
    return rxBufferLength - rxBufferIndex;
}

int TwoWire::read(void)
{
    if (rxBufferIndex < rxBufferLength)
        return rxBuffer[rxBufferIndex++];
    return -1;
}

int TwoWire::peek(void)
{
    if (rxBufferIndex < rxBufferLength)
        return rxBuffer[rxBufferIndex];
    return -1;
}

void TwoWire::flush(void)
{
    // Do nothing, use endTransmission(..) to force
    // data transfer.
}

void TwoWire::onReceive(void(*function)(int))
{
    onReceiveCallback = function;
}

void TwoWire::onRequest(void(*function)(void)) {
    onRequestCallback = function;
}

void TwoWire::onService(void)
{
}

#if WIRE_INTERFACES_COUNT > 0
static void Wire_Init(void)
{
}

TwoWire Wire = TwoWire(Wire_Init);

void WIRE_ISR_HANDLER(void) {
    Wire.onService();
}
#endif

#if WIRE_INTERFACES_COUNT > 1
static void Wire1_Init(void)
{
    if ((adapter_nr = i2c_getadapter(I2C1)) < 0) {
        return;
    }
    if ((i2c_fd = i2c_openadapter) < 0) {
        return;
    }
}

TwoWire Wire1 = TwoWire(Wire1_Init);

void WIRE1_ISR_HANDLER(void) {
    Wire1.onService();
}
#endif

```

Here is the error message i got:

```
libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `TwoWire::write(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::write(unsigned char const*, unsigned int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:194: multiple definition of `TwoWire::write(unsigned char const*, unsigned int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:194: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:204: multiple definition of `TwoWire::available()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:204: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::read()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:209: multiple definition of `TwoWire::read()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:209: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::peek()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:216: multiple definition of `TwoWire::peek()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:216: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::flush()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:223: multiple definition of `TwoWire::flush()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:223: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::begin()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:43: multiple definition of `TwoWire::begin()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:43: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:57: multiple definition of `TwoWire::begin(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:57: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:63: multiple definition of `TwoWire::begin(int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:63: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:68: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:68: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:100: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:100: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:105: multiple definition of `TwoWire::requestFrom(int, int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:105: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int, int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:110: multiple definition of `TwoWire::requestFrom(int, int, int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:110: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:115: multiple definition of `TwoWire::beginTransmission(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:115: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:128: multiple definition of `TwoWire::beginTransmission(int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:128: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission(unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:146: multiple definition of `TwoWire::endTransmission(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:146: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:181: multiple definition of `TwoWire::endTransmission()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:181: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::onReceive(void (*)(int))':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:229: multiple definition of `TwoWire::onReceive(void (*)(int))'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:229: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::onRequest(void (*)())':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:233: multiple definition of `TwoWire::onRequest(void (*)())'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:233: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::onService()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:238: multiple definition of `TwoWire::onService()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:238: first defined here

libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:248: multiple definition of `WIRE_ISR_HANDLER()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:248: first defined here

libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `Wire'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling.

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

```

# Answer
Looks like the Servo library has Wire source files in it for some reason. I checked my Servo library, and it doesn't have those, so not sure what's going on there, but maybe try removing Wire.cpp from Servo/src/? (keep in the file so you can put it back if necessary)

**credits to uint128\_t**(in the comments)

Based on his suggestion i removed the *wire* library files present in servo library folder and things worked just fine.
> 1 votes

---
Tags: arduino-uno, arduino-ide, compile
---


# Question
Title: Connecting Winbond W49F002U-12B to Arduino Mega
I am trying to connect a CMOS flash memory Winbond W49F002U-12B to an Arduino Mega, but failing.

What I did:

1. Read the Winbond W49F002U-12B datasheet. The key points are: CE - chip enabled; OE - output enabled; WE - write enabled and this table:

>

2. Wrote this code and uploaded to Mega2560:

```
int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
int CE = 50;
int OE = 49;
int WE = 48;

char ch;
char addrs[5];
unsigned long address;
unsigned int result;
void setup() {
  Serial.begin(9600);
  for(int i=0; i<18; ++i)
      pinMode(A_pins[i], INPUT);
  for(int i=0; i<8; ++i)
      pinMode(DQ_pins[i], OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(OE, OUTPUT);
  pinMode(WE, OUTPUT);
  digitalWrite(WE, HIGH);
  digitalWrite(OE, HIGH);
  digitalWrite(CE, LOW);

}

void func(unsigned long adr)
{
  for(int i=0; i<18; ++i){
    if(adr & (1ul << i)){
      digitalWrite(A_pins[i], HIGH);
      Serial.print("A_pins[");
      Serial.print(i);
      Serial.println("] = HIGH");}
    else{
      digitalWrite(A_pins[i], LOW);}}
  digitalWrite(OE, LOW);
  delay(100);
  for(int i=0; i<8; ++i){
    if(digitalRead(DQ_pins[i]) == HIGH){
      result|=1<<i;
      Serial.print("DQ_pins[");
      Serial.print(i);
      Serial.println("] = HIGH");}
  }
  Serial.println(result);
  digitalWrite(OE, HIGH);
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print("address = ");
   Serial.println(address);
   func(address);
   }
}

```

What this code is doing is basically after reading serial:

-\> takes the value as address

-\> changes pins A0-A17 to select particular address cell

-\> changes OE to LOW

-\> reads DQ0-DQ7

-\> coverts those readings into int

-\> prints result out.

Example of Arduino IDE Serial Monitor inputs/ouputs stuff:

```
address = 0
0
address = 1232
A_pins[4] = HIGH
A_pins[6] = HIGH
A_pins[7] = HIGH
A_pins[10] = HIGH
0
address = 131072
A_pins[17] = HIGH
0
address = 245760
A_pins[14] = HIGH
A_pins[15] = HIGH
A_pins[16] = HIGH
A_pins[17] = HIGH
0

```

> Arduino Mega board is 100% functioning. I don't think Winbond w49f002u-12b is not working. Where am I wrong?

**UPDATE:** Here is fixed code:

```
int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
int CE = 50;
int OE = 49;
int WE = 48;

unsigned long address;
unsigned int result;
void setup() {
  Serial.begin(9600);
  for(int i=0; i<18; ++i)
      pinMode(A_pins[i], OUTPUT);
  for(int i=0; i<8; ++i)
      pinMode(DQ_pins[i], INPUT);
  pinMode(CE, OUTPUT);
  pinMode(OE, OUTPUT);
  pinMode(WE, OUTPUT);
  digitalWrite(WE, HIGH);
  digitalWrite(OE, HIGH);
  digitalWrite(CE, LOW);

}

void func(unsigned long adr)
{
  result = 0;
  for(int i=0; i<18; ++i){
    if(adr & (1ul << i)){
      digitalWrite(A_pins[i], HIGH);
    }
    else{
      digitalWrite(A_pins[i], LOW);}}
  digitalWrite(OE, LOW);
  //delay(100);
  for(int i=0; i<8; ++i){
    if(digitalRead(DQ_pins[i]) == HIGH){
      result|=1<<i;
    }}
  Serial.println(result);
  digitalWrite(OE, HIGH);
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print(address);
   Serial.print(": ");
   func(address);
   }
}

```

**UPDATE:** Changed code using PORTs, Thanks to @MikaelPatel for reminding about PORTs:

```
unsigned long address;

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

  DDRL = B00000000; //  DQ7-DQ0 42-49
  DDRA = B11111111; //  A7-A0   29-22
  DDRC = B11111111; //  A15-A8  30-37
  DDRG |= B00000011; // A17-A16 40-41
  DDRB |= B00000111; // WE, OE, CE

  PORTB = B00000110; // WE - HIGH, OE - HIGH, CE - LOW
}

void func(unsigned long adr)
{
  PORTA = adr;
  PORTC = (adr>>8L);
  PORTG = (adr>>16L);
  PORTB = B00000100; //OE - LOW
  Serial.println(PINL);
  PORTB = B00000110; //OE - HIGH
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print(address);
   Serial.print(": ");
   func(address);
   }
}

```

# Answer
> What this code is doing is basically after reading serial: ... -\> reads DQ0-DQ7

But all the DQn pins are in OUTPUT mode and the A pins in INPUT mode. Seems to be a mix up. BW: it is the same with all of the pins. The pin mode is from the Arduinos point of view and not the memory chip.

Cheers!
> 0 votes

---
Tags: arduino-mega, memory-usage, flash
---


# Question
Title: Is it OK to Serial.print(message), when the USB cable is not connected to a host PC?
Often I put a bunch of `Serial.print( F("debugging messages") )` in my Arduino sketch.

Normally those messages go up a USB cable to a host PC so those messages can be seen on the serial monitor.

I want to install this Arduino as part of a stand-alone system far from any PC and plug the "host" end of the USB cable into a wall-wart USB charger.

Without anything to accept those messages, the buffer on the Arduino eventually fills up, right? Do I need to do anything to keep the Arduino from overflowing and crashing when it's not connected to a host PC?

Does it make any difference if I'm using a (1) "single-chip" Arduino-compatible where the processor includes on-chip USB, vs. (2) an Arduino-compatible with separate "USB interface chip" and "processor chip"? (By "single-chip Arduino-compatible", I mean things like the Arduino Leonardo, Arduino Yún, LilyPad Arduino USB, Arduino Micro, the Teensy-LC, etc.)

# Answer
It is OK to write out serial data with nothing connected.

In case (2) "Arduino + USB interface chip", the arduino has no idea if anything is connected or listening to the serial port. The code will transmit the bytes and act exactly the same whether plugged in to anything or not.

In case (1) "arduino with built in USB" it has some idea, but just drops bytes that are going to be transmitted when the USB port is not connected.

Hardware serial (case 2) has an output buffer, but that just makes the program a little faster. When the buffer is empty, a call to `serial.{print, write}` will place bytes in the buffer and move on. When it's full, `Serial.{print,write}` will wait until there is enough room to put the rest of the message in the buffer and move on. The hardware UART and interrupts it generates will keep taking bytes out of the buffer and transmitting them at a constant rate whether something is plugged in or not. In any case, the buffer is a fixed size and will never overflow.

As far as I can tell USB-Serial (case 1) only buffers incoming data. Since the calls to `Serial.{print, write}` do nothing when not connected, they may take less time than they would otherwise. If your code is really unsafe about timing, that could cause a problem, but I doubt it will.

Many examples that come with the Arduino IDE have the following bit of code that pauses native USB Arduino-compatibles until the USB connection is initialized:

```
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

```

This code stops the Arduino from doing anything until the USB cable is connected. Comment out or delete those 3 lines if you want the Arduino to run "stand-alone" without a USB cable connection (Arduino Cookbook p. 117) -- after you delete those lines, if you later plug in a USB cable, the USB will initialize correctly, and *then* you will see on your serial monitor everything printed by any *later* Serial.print() commands that run. (Tested on a Teensy LC).
> 8 votes

---
Tags: serial, usb
---


title: FCC Certification

text:
# Question
Title: FCC Certification
I noticed that both the Uno and Wifi101 are FCC certified. Does this mean that these components can actually be used in commercial applications? This never really occured to me before I noticed the markings.

I'm sure there is more to a commercial product than just FCC certification but I know that the certification process isn't cheap!

# Answer
> 4 votes
These products are not certified, they merely have been verified and issued a Declaration of Conformity. The WiFi module on the WiFi shield itself has been certified, as indicated by the FCC ID on its label.

To explain what that means, I am going to give a simplified explanation. If you are looking to make a commercial product and you are not sure what you need to do to be compliant, hire out a professional to help you through the process.

In the eyes of the FCC, devices fall into one of two categories, devices that are intentional transmitters, and devices that are not. Devices that are intentional transmitters need to be certified. Certification is a process of making sure that it is only transmitting on the frequency band it specified, that it is maintaining certain power limits, and that it will not cause interference with other devices. This is a very expensive testing procedure.

Devices that are not intentional transmitters, only need to get a verification. What this means is that the devices is not designed to transmit anything and is test to makes sure that it indeed does not. If you pass the verification you are issued a Declaration of Conformity basically stating that the device is not unintentionally transmitting any frequencies. This is usually a lot less expensive than than certification (but still in the few thousand USD range).

So taking the WiFi shield as an example, the module shown above circled in red is an intentional transmitter, i.e. it is designed to transmit on a particular frequency band (in this case 2.4 GHz ISM band). The device is certified to make sure that its emissions are within FCC specifications and it is issued an FCC ID.

Now at this point only the module is certified and is good to be used in a product, however, now that it is on a shield with extra circuitry added to it, the extra circuitry could be unintentionally transmitting. So now the whole shield is tested to make sure that the added circuitry does not have any emissions exceeding the FCC specifications and is issued a Declaration of Conformity.

So now fast forward to making your own thing, the module is certified, the WiFi shield and the Uno are verified, you add your own additional circuity around those components that may emit electromagnetic fields. You now may have to get your product verified to ensure that the added components to the system have not caused it to unintentionally emit radio frequencies.

The whole process, conditions, and requirements are a lot more nuanced than my description above. So this should in no way be used as the basis for product development or legal advice.

(Image borrowed from https://www.arduino.cc/en/Main/ArduinoWiFiShield101)

---
Tags: wifi
---


title: Loop behaves oddly in I2C receiveEvent

text:
# Question
Title: Loop behaves oddly in I2C receiveEvent
I am messing around with an ATmega328P hooked on a Raspberry Pi, communicating over I2C. The ATmega is the slave (details at the end). While testing the basics of the concept, I faced an interesting problem.

This is the code on the ATmega:

```
#include <Wire.h>

#define SLAVE_ADRESS 0x1A
#define LED 6

int count = 10;
void setup()
{
    pinMode(LED, OUTPUT);
    /*for(int i=1; i<=3; i++)
    {
      digitalWrite(LED, HIGH);
      delay(100);
      digitalWrite(LED, LOW);
      delay(100);
    }*/
    Wire.begin(SLAVE_ADRESS);
    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);
}

void loop()
{
  delay(10);
}

void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

void requestEvent()
{
  Wire.write(count);
}

```

What you would expect it to do is blink the LED connected to pin 6 five times when the Pi sends a byte to the ATmega slave. (Things like `if(1)` are there because the code was much more specific originally.) The strange thing is that this is not the case:

*The LED only blinks 1 time.*

I honestly have no idea why. This "stdio-fitted" version of the problematic loop ran on the RPi as expected, prints 5\*2 times:

```
#include <stdio.h>

int main()
{
  int j = 5;
  while(j>0)
  {
    printf("LED, HIGH\n");
    printf("LED, LOW\n");
    j-=1;
  }
  return 0;
}

```

**Circumstances:**

* I compile the code in the Arduino IDE on the Pi, then upload it using AVRDUDE to the ATmega with the Pi's GPIOs. No error messages over the process.
* The ATmega gets 3.3 V supply voltage from the Pi, and operates on 16.000 MHz. Only the LED and the Pi is connected to it.
* The (Python) code I use on the Pi to write and read a byte is the following. Reading works well, and I know by tests that the ATmega actually receives the correct byte:

```
import pigpio
import time

pi = pigpio.pi()
atmega = pi.i2c_open(1, 0x1A)

for i in range(6):
    a = pi.i2c_read_byte(atmega)
    print a

pi.i2c_write_byte(atmega, 0x05)
time.sleep(1)

```

# Answer
```
void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

```

`receiveEvent` is an ISR (interrupt service routine). Don't do `delay` in an ISR. That will hang indefinitely. Thus the LED only blinks once. You could do `delayMicroseconds` for *testing*. In general an ISR should be **short**.

---
> 0 votes

---
Tags: i2c
---


# Question
Title: Error when using USART with Arduino Mega 2560
I use the Arduino IDE 1.6.9

What I want is a DMX Receiver which receives 1 channel and displays it on the serial monitor. When I try to compile the code, I get the following error:

```
C:\Users\Helyx\AppData\Local\Temp\build25a76891c667e0896ec10beb77bd0478.tmp/core\core.a(HardwareSerial0.cpp.o): In function `__vector_25':

D:\Programme\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial0.cpp:48: multiple definition of `__vector_25'

sketch\DmxReceive.ino.cpp.o:C:\Users\Helyx\Documents\Arduino\DmxReceive/DmxReceive.ino:26: first defined here

d:/programme/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Fehler beim Kompilieren.

```

Any ideas? Here is my code:

```
#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000

#define DMX_BAUD 250000
#define DMX_LOST_TIMEOUT 8000

volatile unsigned char dmx_buffer[10];
volatile unsigned int dmx_lost = DMX_LOST_TIMEOUT;

volatile unsigned int dmx_adresse = 1;

ISR (USART0_RX_vect)

{
static unsigned int dmx_channel_rx_count = 0;
static unsigned char dmx_valid = 0;
unsigned char tmp = 0;

tmp =  UDR0;

if(UCSR0A&(1<<FE0))
{
 if(dmx_channel_rx_count > 1)
 {
   dmx_lost = 0;
 }
 dmx_channel_rx_count = 0;
 dmx_buffer[0] = tmp;
 if(dmx_buffer[0] == 0)
 {
   dmx_valid = 1;
   dmx_channel_rx_count++;
 }
 else
 {
   dmx_valid = 0;
 }
 return;
}

if(dmx_valid)
{
 dmx_buffer[dmx_channel_rx_count] = tmp;
 if(dmx_channel_rx_count < 514)
 {
   dmx_channel_rx_count++;
 }
 return;
}
}

ISR (TIMER2_COMPA_vect)

{
 if(dmx_lost<DMX_LOST_TIMEOUT)
 {
   dmx_lost++;
 }
}

void setup()
{

EICRA |= (1<<ISC11)|(1<<ISC10); //The rising edge of INT1 generates an interrupt request
EIMSK |= (1<<INT1); //External interrupt request 1 enable

//Init usart DMX-BUS
UBRR0   = (F_CPU / (DMX_BAUD * 16L) - 1);
UCSR0B|=(1 << RXEN0 | 1<< RXCIE0);
UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
sei();//Globale Interrupts Enable

TCCR2A |= (1<<WGM21);
TCCR2B |= (1<<CS22|1<<CS21|1<<CS20);
TIMSK2 |= (1<<OCIE2A);
OCR2A = F_CPU/1024/1000 - 1; //Tick 1ms
Serial.begin(57600);

DDRC = (1<<PE3);
PORTB |= 0x3F;
PORTC |= 0xFF;
PORTC &=~(1<<PE3);

}

void loop()
{

if(dmx_lost==DMX_LOST_TIMEOUT)
{
  dmx_buffer[dmx_adresse] = 0;

}
Serial.print(dmx_buffer[dmx_adresse]);
}

```

# Answer
> 1 votes
The compiler/linker is providing the answer. There are at least two definitions of the ISR for UART0 RX. One in your code and one in HardwareSerial.

# Answer
> 0 votes
If I understand you correctly, you want to receive serial data (in DMX format) on one serial port, and then display that data on the serial monitor (using a different serial port).

The Arduino Mega 2560 is an excellent choice, because it has 4 hardware UARTs.

Alas, there is really only 3 hardware UARTs that you can actually connect to external hardware. USART0 (the Mega pins labeled "TX0" and "RX0") are *already* connected to the USB interface; the Arduino calls that USART "Serial." (without a number).

I avoid connecting anything to the "TX0" or "RX0" pins on the Mega, so I can use "Serial." (USART0) for sending debugging messages to the serial terminal over the USB cable.

```
// doesn't compile
ISR (USART0_RX_vect)
{
    // ...
}
// ...
void loop()
{
    // ...
    Serial.print(dmx_buffer[dmx_adresse]);
}

```

This looks inconsistent to me. One part of your program is trying to use USART0 ("Serial.") for sending and receiving messages to the serial monitor on the PC. Another part of your program is trying to use the same USART0 ("Serial.") for sending and receiving messages on the DMX network.

Have you tried connecting the DMX interface to the other available hardware USARTs -- perhaps USART1 ("Serial1.", the pins labeled TX1 and RX1), or USART2 ("Serial2.", the pins labeled TX2 and RX2), or USART3 ("Serial3.", the pins labeled TX3 and RX3)? Then your code would look more like other people recieving DMX on an Arduino Mega -- (a), (b), (c), etc.:

```
// the ISR setup that the other DMX-on-Arduino-Mega people use:
ISR( USART3_RX_vect ){
    // ...
}
// ...
void loop(){
    // ...
    Serial.print(dmx_buffer[dmx_adresse]);
}

```

---
Tags: arduino-mega, uart
---


title: GPS library for Proteus

text:
# Question
Title: GPS library for Proteus
I am working on a project in which I have to connect my Arduino with a GPS module. In this project I need to get longitude, latitude, time and date from the GPS module and need to send these values via USB to a computer.

On this computer, I am going to design software in Microsoft Visual Studio 2010, which will receive this data and display it on a map.

Now, before designing it in hardware, I want to simulate it on Proteus. I have searched in Proteus but there's no GPS module in it, so does anyone know any GPS module library for Proteus?

# Answer
> 0 votes
I have found the solution to my question so I thought to post it here so that others could also get benefit out of it. Here's the link to GPS Library for Proteus - A complete step by step tutorial on How to download GPS Library for Proteus.

From this link you can download the GPS Library which you need to add to the libraries folder of your Proteus software and you will have the GPS module in Proteus and you can design your simulation quite easily. More details are given in this link.

# Answer
> 0 votes
If you will be using the computer to interface, **you don't really need Arduino in the middle**.

You can hook the GPS module to the computer using a USB-UART bridge like one below:

The usual GPS modules (ebay or other hobby stores) output NMEA sentences over their serial port. Check the datasheet of your GPS module for the baud rate and the RX/TX pins. Connect the RX and TX lines of your GPS to the USB-serial module and you should be able to see NMEA output on a terminal emulator (set to right baud).

Once you see NMEA sentences over a terminal emulator, you can parse those in your application directly (bypassing terminal emulator) instead of using an Arduino.

---
Tags: arduino-uno, gps
---


# Question
Title: If a Timer is used, disabling some PWM pins, can I still use those pins for Digital write?
It's my understanding that when a Timer is used on an Arduino (in my case the Arduino Mega), it can disable analog write on some PWM pins, which pins depends on the Timer being used. For instance on the Mega, pins 44,45,46 are controlled by Timer 5. If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

# Answer
> 4 votes
> If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

You can view the connection between the Timer and the pins as programmable. The connection is enabled by, for instance, analogWrite(). The Timer control registers have a setting for both the connection and control logic of the pin (clean, set or toggle on timer value match).

You can use the Timer to generate interrupts without connecting a pin. This is the case with micros() and millis() which get their values from a counter which is updated by an ISR on Timer 0 (overflow). analogWrite() on pin 5 and 6 connects to Timer 0 value match logic.

analogWrite() uses the Timer value match and connects the pins. Enabling only the Timer (as you suggest) will allow you to use the pins with digitalWrite(). You can also use the Timer ISR for overflow. The Timer prescale is set for analogWrite().

Cheers!

# Answer
> 2 votes
When using an timer (other than by PWM) you can choose to enable it's output to a pin (which basically is what PWM does). So you can still use them as a digital pin (if you choose not to).

You could set up an PWM signal and enable timer interrupts afaik. But changing PWM, would also change the timer.

There is a difference in only using Arduino functions, or changing the registers directly. Try to read the "timers" part of the datasheet and find some tutorials about avr/atmel/atmega register changing or/and setting up timers.

---
Tags: arduino-mega, pwm, timers
---


title: Dereferencing char into a struct

text:
# Question
Title: Dereferencing char into a struct
I am sending some data over an NRF24 link, using the RF24Network library. So far I have only sent numbers, now I also want to send a string, so I have set up my payload struct as

```
struct payload_t {                  // Structure of our payload
   unsigned long data;
   unsigned long datatype;
   char sensorid[20];
   unsigned long counter;
};

```

As far as I do understand, I can not use string here, since I need to know the length of the data I am sending.

At the moment I am using sensors without an internal ID, so in `loop()`, I am calling:

```
 writeToNetwork(voltage,'v',"nosid",packets_sent++);

```

My `writeToNetwork` function is defined as

```
 bool writeToNetwork(unsigned long data,unsigned long type,char sid[20],unsigned long package){

```

and within that, I am setting up the payload with

```
 payload_t payload = { data,type,sid, package };

```

Which gives me an

```
 error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]

```

Clearly, I have no interest of the address the pointer is referencing, so I need to somehow dereference the `sid` \- pointer to get my array into the struct. How can I do that?

Or am I barking up the wrong tree? I tried to transfer the id as a string:

```
#include <string.h>
bool writeToNetwork(unsigned long data,unsigned long type,String sid,unsigned long package){
char sidchar[20];
sid.toCharArray(sidchar,20);
payload_t payload = { data,type,sidchar, package };

```

Which gives me the error

```
array must be initialized with a brace-enclosed initializer

```

Which I do not understand. Doing

```
char sidchar[20]={0};

```

gives me the same error.

# Answer
> 4 votes
In your situation, your best bet is probably to use the standard C function `strcpy`:

```
payload_t payload;
char* source = "abcdef";
strcpy(payload.sensorid, source);

```

Note that source string does not have to be declared as `char source[20]` and can be declared as the rather standard C string `char*`.

Also, since you are limiting the size of the string to be passed in `payload`, you may prefer to use `strncpy` which will ensure no more than 20 characters get copied:

```
payload_t payload;
char* source = "abcdef";
strncpy(payload.sensorid, source, 20);
// Explicitly add a string termination to the end of string
payload.sensorid[19] = 0;

```

In the snippet above, please notice the last line, it is necessary in the situation where `source` string length is 20 or more non-null characters, as in this case, `strncpy` will copy all 20 characters but will not add the terminating 0 at the end of the string.

---
Tags: nrf24l01+, pointer
---


title: Converting data between baud rates

text:
# Question
Title: Converting data between baud rates
This isn't strictly limited to Arduino but I spend a lot of time with serial devices on my Arduino and I'm sure that others do as well:

Here goes..

Let's say a device sends three characters \[ABC\] via serial at 9600 8N1.

And let's also say the device receiving the data only knows that it's serial stream and 8N1 but does not know the baud.

The receiving device would need to take a guess at the baud and so probably get it wrong. It would therefore receive weird characters.

Is there anyway/anything around that a user could paste the strange characters into that would reverse engineer (from the bit stream) to give the correct baud and hence correct ascii characters \[ABC\]?

# Answer
> 6 votes
I am not aware of anything like that, no. The problem is what you are seeing as characters are a complete corruption of the data. Only some part of it may have been interpreted as a valid bit sequence, and even then you can't know what bit it was.

However, there is one magic character in UART communication: `U`

What is special about that character is its binary pattern. It is ASCII character 85, which in HEX is 0x55, or binary it's 0b01010101. Add to that the start and stop bits, and invert it for the UART logic (1 = LOW, 0 = HIGH) and the signal that gets sent out of the UART looks like:

```
____start_____     _____     _____     _____     _____
    |   |  0  | 1 |  0  | 1 |  0  | 1 |  0  | 1 | stop
    -----     -----     -----     -----     -----

```

And yes, that's a pretty good square wave. The frequency of that square wave will be exactly half the baud rate - so a frequency of 4800Hz will be a baud rate of 9600 baud.

This effect is cleverly used for a system called Automatic baud rate detection whereby a receiver waits for a `U` character to determine the baud rate to use. Most modern microcontrollers have this facility available.

If you can't get the frequency of a block of `U` characters you will have to examine the waveform with an oscilloscope. It should be possible to identify the individual characters in the data stream as distinct blocks in the waveform. From that you can then work out the width of one symbol and thus the baud rate. It's best to use a DSO for this since you can then capture a short burst and use the markers to measure the time between different points in the waveform. A logic analyser will also do the job quite well, and will most likely be able to decode the waveform and calculate the baud rate for you.

If you have neither of those it would be possible to program an Arduino to capture the time between transitions of an incoming signal and allow you to plot them in Excel to give you a waveform you can examine to determine the baud.

Another option is just to keep trying different baud rates (there's relatively few "standard" baud rates) until you see the right text coming in.

# Answer
> 2 votes
My logic analyser has a "guess baud rate" feature, which usually is fairly accurate. If you analyse an incoming bit stream you can probably have a reasonably good guess. For example the shortest transition means the baud rate cannot be **slower** than that. For example, at 9600 baud sooner or later you will get a transition in 104 µs (ie. `1/9600`). Thus if you see that, the baud rate could not be 4800 baud.

Also, in general, there will be a gap between "packets", so in your case after the "ABC" there would be a longer gap (of all 1s). You would assume then that the active time represents an integral number of bytes (eg. 3 bytes, 8 bytes, but not 1.5 bytes).

Another thing is that baud rates are usually multiples of a power of 2 times 300 (ie. 300, 600, 1200, 2400, 4800). So this gives you a small range of possible baud rates to test. You could test (say for 9600) and see if you get reasonable results. A "reasonable result" would be a stop bit appearing 10 bits after a start bit.

See my post: How does serial communications work on the Arduino?

# Answer
> 2 votes
Try measuring pulse width and match shortest pulse against pre-defined widths corresponding to available baudrates. This way you can detect baudrate by analysing random binary stream.

Signal glitches, such as very short spikes, will be filtered out, as they will never match the list of baudrates.

Repeat the measurement few times to raise accuracy and choose the most probable value from all guessed values.

# Answer
> 2 votes
In the days of dumb terminals and time sharing systems, setting the baud rate was accomplished by the terminal sending a pre-determined series of characters with gaps between them and the host changing its baud rate and looking for the expected data. It is best to start at a high baud rate and drop the rate between tries.

For example the terminal user would hit Enter repeadedly and the host would try decreasing baud rates until it saw the Carriage Return character. When it saw the CR, it would respond with "Login Please" and you would know you were good to go.

---
Tags: serial, baud-rate
---


title: How do I count time in seconds?

text:
# Question
Title: How do I count time in seconds?
I have a statement:

```
if(control > 100 && control < 130)
{

  //count time 30 seconds and open pin1 for 3 seconds.

}

```

How can I count 30 seconds and open a pin for 3 seconds?

# Answer
> 5 votes
A non-blocking version is often needed as there is often other tasks to be performed during the wait. The "blink-without-delay"-pattern is a solution but unfortunately it becomes tedious to use with several time periods and logic.

The Timemark library helps abstract the pattern and hide a lot of the details. The below sketch uses two timemarks and a simple state-machine to help reduce complexity.

```
#include <Timemark.h>

Timemark turnOnWait(30000L);
Timemark turnOffWait(3000L);

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      turnOnWait.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (turnOnWait.expired()) {
      digitalWrite(pin, HIGH);
      turnOffWait.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (turnOffWait.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

```

Two timemarks are used for clarity. It is possible to use a single timemark and reinitiate it with a new time limit.

```
#include <Timemark.h>

const uint32_t TURN_ON_TIMEOUT = 30000L;
const uint32_t TURN_OFF_TIMEOUT = 3000L;

Timemark timemark;

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      timemark.limitMillis(TURN_ON_TIMEOUT);
      timemark.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, HIGH);
      timemark.limitMillis(TURN_OFF_TIMEOUT);
      timemark.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

```

The Scheduler library allows the blocking version (delay) to be used. Non-blocking is achieved by context switching on yield() or delay(). Below is a rewrite using this style:

```
#include <Scheduler.h>

const int pin = 4;
int control = 0;

void setup()
{
  ...
  Scheduler.start(setupController, loopController);
}

void loop()
{
  ...
  delay(1000);
}

void setupController()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loopController()
{
  ...
  if ((control > 100) && (control < 130)) {
    delay(30000L);
    digitalWrite(pin, HIGH);
    delay(3000L);
    digitalWrite(pin, LOW);
  }
  else {
    delay(100);
  }
}

```

Cheers!

# Answer
> 2 votes
What you can also use is non-blocking code, where `delay()` would block for the 30s. My suggesting makes use of `millis()`, one could say similar to blink without delay code example.

Here is an example of what you could place in the loop:

```
//declared variable stuff here

if(control > 100 && control < 130 && !toggled_bit){

    toggled_bit = true;     //to control the timing section
    start_time = millis();
}
else if (!(control > 100 && control < 130)){
    toggled_bit = false;
}

if (toggled_bit){
        test1 = millis()
    if(test1 - start_time > 30000){

        digitalWrite(1, HIGH);
            short_wait = millis();
            // wait for 3s after fist time
                if(short_wait - start_time > 33000)
                    digitalWrite(1, LOW);
                    toggled_bit = false;
                }
        }
}

// other code here

```

The code sets a 'flag', `toggled_bit`, which is checked by the `if()` later on in the loop, also it sets `start_time`. It then checks if 30s has passed and then waits an extra 3s to turn the output off after being turned on. It then resets the `toggled_bit`.

This will also allow you to check or do other things while waiting.

# Answer
> 1 votes
Rearrange the Blink example:

```
if(control>100 && control<130)
{
  //**count time 30 seconds and open pin1 for 3 seconds.**
  delay(30000);             // wait for 30 seconds
  digitalWrite(1, HIGH);    // turn the LED on (HIGH is the voltage level)
  delay(3000);              // wait for 3 seconds
  digitalWrite(1, LOW);     // turn the LED off by making the voltage LOW
}

```

# Answer
> 1 votes
Well 30s equals 30,000ms and the arduino comes with a native function that counts in Milliseconds so the following code should work:

```
Time = millis();  //time passed before entering loop…
If((control > 100) && (control < 130))
{
While (millis() < Time + 30000) //counts to Thirty seconds
{
While (millis() < Time + 3000) // counts to three seconds
{
DigitalWrite(1,HIGH);
};};};

```

This way you can add some code in the while loops if u want to multitask.

---
Tags: programming, timers
---


# Question
Title: Modify Arduino Due's Bootloader to flash when reset
I bought an Arduino Due, and I noticed unlike the other boards, the onboard LED does not flash after reset. I prefer this behavior, so I want to modify the bootloader to do this behavior when it starts. I have burnt bootloaders before, but I never modified one before.

How can I do this?

# Answer
The Arduino Due bootloader is built-in. If you check the Arduino SAM core there are no bootloader files. There is a firmware file for the ATmega16u2 on the Programming Port. You might be able to modify this to do that (given that there is a LED to flash).

The alternative solution to a modified bootloader is modifing the init() of the Arduino SAM core. Please see https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/cores/arduino/main.cpp#L36 or https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/variants/arduino\_due\_x/variant.cpp#L372. Blink code as proposed by Majenko could be added there.

Cheers!
> 2 votes

# Answer
You cannot.

The SAM3X's bootloader is hard-coded into ROM and can never be changed.

Ever.

Yes, I know, it sucks, doesn't it?

However, the bootloader only executes if the flash is empty (bit of an odd choice if you ask me, but there you go) so you could "emulate" the operation by flashing an LED as the first thing in your sketch.

```
pinMode(13, OUTPUT);
for (int i = 0; i < 5; i++) {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
}
pinMode(13, INPUT); // This will "reset" the pin to default.

```
> 1 votes

---
Tags: bootloader
---


# Question
Title: Programming many Arduinos simultaneously with a wireless broadcast
I will have many microcontroller-based devices which will be independent from each other, but all will run the same program.

I would like to upload a program to all of them at the same time with a wireless broadcast. Ideally the user would plug in a USB controller to his computer, and upload a program from the Arduino environment as if s/he were programming a single device.

To get a better idea of what I'm talking about, please take a look at this video. This was achieved with Atmel microcontrollers but a custom-made, non-Arduino bootloader.

From a Google search for "Arduino infrared programming" this interesting project came up. The main drawback is that the reset button still has to be pressed manually. Ideally I would like the devices to be in a low-power state by default, and wake up to receive a program when they sense a signal from the controller. Still, this may be a good starting point for me.

I just wanted to get some perspectives from people who are familiar with Arduinos as to whether they think this is feasible before I jump in.

# Answer
> 2 votes
### TL;DR -

You have the options of either BlueTooth or XBee (amongst others: IR, for example?) for wireless uploading. However, I believe that only one board can be uploaded to, at a time, so you will need to cycle through the boards one at a time, see Programming multiple ATMegas/Arduinos at once.

> When uploading a sketch or using a programmer (for sketch or bootloader), the software does not just write the code, it actually communicates with the microcontroller.
>
> You can't program them all at once. But you can program them one by one in some automatic way.

---

Your question is a very interesting one, and asks a question that I am sure that I would never have thought of, but would be extremely useful and labour saving, especially if one has, as I do, many Arduino controlled sensor points located around the house. Here is one rather inelegant solution that may be worth trying.

**Wireless upload hardware**

If you use **BlueTooth** to wirelessly upload your sketches, then this solution might be of use, Wireless upload program to Arduino without USB cable. Note that this solution ties up pins D0 and D1:

> But be careful that it maybe not compatible with some projects which need to use the D0 and D1 as hardware UART TX, RX. Because the wireless programmer needs to permanently occupy the two pins.

Looking at it, it employs a custom Arduino Wireless Programmer, to which you may have been referring in your question. However, don't be fooled by the name, it is simply a Bluetooth shield. It is basically a BT HC-05 (or similar) device, bolted onto an Arduino, see also Bluetooth Wireless Upload.

Alternatively, en lieu of BlueTooth, you could use **XBee** devices, see Wireless Programming of Arduino. The advantage of using XBees is that you would not have to go through the pairing new device loop (see below), that would be required when using BT. Instead you would merely have to cycle through the XBee network IDs.

However, in addition to that, you would need to automate the switching of BT devices, selecting the appropriate port and uploading to each Arduino in turn, as *you are not able to broadcast sketches*. (If am I wrong, then will someone please correct me).

**Selecting the port and uploading the sketch**

You could use a script along with the command line version of the Arduino IDE, to select the port that the BT device is connected to, before each upload. How you do this will vary for which ever platform you are compiling upon, see Command line Arduino compiling and downloading? This can be done using the environment variable `ARDUINO_COMPORT` (see the possibly out of date Windows command line build), or the arduino cmd line option `--port <portname>` ( see the man page). The sketch would then be uploaded using the option `--upload <filename>`. You could do this in one fell swoop:

```
arduino --upload --port <portname> FILE.ino

```

Note that on Windows you should use `arduino_debug.exe`.

Or you could use Ino, if you are *not* using a Windows PC... but that might make the next part, which deals with the looping more complex than it needs be.

**Selecting each of the Arduinos (i.e. the BT devices)**

Next, you would need to add a loop to the script, that pairs the PC to each BT device in turn and thereafter calls the Arduino IDE, for the port selection and uploading. Unfortunately, this would not be platform agnostic at all, and would require a different solution for what ever platform you are using. Take a look at Bluetooth from the Command Line, but for Windows you would probably require the Blue Tooth Command Line tools suite.

On OS X you may be best off resorting to using AppleScript, see Connect to bluetooth device (iPhone) via command line on MacOSX, as the cmd line tools for controlling BT seem a little scant - there is BlueUtil, see How to control Bluetooth wireless radio from the command line? but that only appears to turn the BT on of off. However, bolting AppleScript on to the rest of the Arduino IDE control script quickly makes things more complex, although you could just put the Arduino command within the AppleScript, I guess.

# Answer
> 0 votes
You could use ESP-LINK to program the Arduino over WiFi.

The ESP8266 is simple cheap Wi-Fi MCU that can be programmed with Arduino IDE.

ESP-LINK is firmware for the ESP8266 that makes the ESP act like serial connection (USB) to Arduino.

The firmware can be found here at ESP-LINK ESP8266.

# Answer
> 0 votes
One can use something like this. It is a custom bootloader to update a Arduino's code via a NRF24L01+ radio module.\*

\*It only works under Linux machines.

---
Tags: programming, power, bootloader, wireless
---


# Question
Title: Sending data to a webserver with GPRS/GPS Shield (U-blox Sara G-350)
I am working on a project for tracking cars. I am using an Arduino UNO to receive the position from GPS/GPRS shield. I am OK on obtaining the coordinates position. Now I need to send the position to a webserver and then show it on a webpage using the Google Maps API. Which accepts it in a POST or GET method. Here is the shield model: U-blox Sara G-350 and this is its manual here

Here is my approach:

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

SoftwareSerial gprsSerial(7 ,8);

void setup() {
  // put your setup code here, to run once:
  gprsSerial.begin(19200);
  Serial.begin(19200);
  delay(2000);

 gprsSerial.println("AT+CGDCONT=3,\"IP\",\"weborange\"");
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UHTTP=2,1,\"www.navtec.16mb.com\"");
                   //AT+UHTTP=<profile_id>,<op_code>,<HTTP_server_name>
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0,5,80");
 toSerial();
 delay(2000);

}

void loop() {

 //gprsSerial.println("AT+UHTTP=2,1,\"submit\"");
                    //AT+UHTTP=<profile_id>,<op_code>,<param_val>[,<param_val1>]
 //toSerial();
 //delay(2000);

 gprsSerial.println("AT+UHTTPC=2,1,\"/add.php\",\"filename\"");  //Problem here!!!!!!!!
                   //AT+UHTTPC=<profile_id>,<http_command>,<path>,<filename>[,<param1>[,<param2>[,<param3>]]]
 toSerial();
 delay(2000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }

}

```

This is what I get:

> +CGDCONT=3,"IP","weborange"
>
> OK +UHTTP=0
>
> OK +UHTTP=2,1,"www.navtec.16mb.com"
>
> OK +UHTTP=0,5,80
>
> OK +UHTTPC=2,1,/add.php,filename
>
> ERROR +UHTTPC=2,1,/add.php,filename
>
> ERROR +UHTTPC=2,1,/add.php,filename
>
> ERROR +UHTTPC=2,1,/add.php,filename
>
> ERROR ...

Thanks for your time, I am waiting for your support, any ideas could help. Sorry for my bad English

# Answer
I worked on a project similar to yours. I think you forgot to **establish a connection first**. Just add those lines of code at the top of `setup()` method:

```
 gprsSerial.println("AT+UPSDA=2,0"); //Reset connection
 toSerial();
 delay(2000);
  gprsSerial.println("AT+UPSD=2,1,\"weborange\""); //Establish a new one
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSDA=2,3");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSND=2,0");
 toSerial();
 delay(2000);

```

I hope it works for you. Else, you can use `AT+UHTTPER=2` after all to check for error source.
> 1 votes

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


title: Troubleshoot Arduino LCD 16 x 2 shield

text:
# Question
Title: Troubleshoot Arduino LCD 16 x 2 shield
I tried to assemble Adafruit's Arduino LCD 16 x 2 using the instructions RGB LCD Shield: Control a 16x2 Character LCD using 2 pins - Assembly without any success.

After assembly, I uploaded the HelloWorld example sketch on to the Arduino. The shield doesn't seem to be working. The LCD didn't turn on.

If I push back/press the LCD it turn on. Any idea on how to troubleshoot this?

# Answer
By visually assessing the pictures, the issue seems to be due to poor soldering job.

You should try re-heating the soldering joints and make sure they are clean. There could be dry joints that may not be conducting signals.

Also you should upload pictures to your question post, not as an answer.
> 0 votes

---
Tags: lcd
---


# Question
Title: How to set string in the structure part of NRF24?
Can anyone help me on how to correct my program ? I want to transmit value in string form.

I put this to TX code

```
struct payload_t
{

 String sensor1;
};

```

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

At the loop part I put this code

```
String sensor1 = (String(x) + "," + String(y) + "," + String(z)) ;

```

In the RX part I put this code

```
 struct payload_t
{

 String sensor1;
};

```

At the loop part

```
RF24NetworkHeader header;
payload_t payload;
network.read(header,&payload,sizeof(payload));

Serial.println("Sensor1 ");

Serial.println(payload.sensor1);

```

Below is the Attach picture result of RX code.

Thanks in advance :)

# Answer
Did you actually 'instantiate' the struct in the TX and construct `sensor1` as `payload.sensor1 = ...`? Anyways, there's still a problem.

You are using `String` in your payload. The third argument to `read` is the maximum message length that can be stored in `payload`. In your `read` call, you passed the size of payload as `MAX_LEN`. You will receive incomplete payloads since the String object in the RX `payload` struct has no content in it yet and thus `payload`'s size, which you passed as `MAX_LEN`, will be less than that of the actual payload that was transmitted. Just ditch the Strings and try:

TX:

```
int vals = {x, y, z};   // guessing they are ints

network.write(header, &vals, sizeof(vals));

```

RX:

```
int vals[3];
network.read(header, &vals, sizeof(vals));

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

```
> 2 votes

---
Tags: nrf24l01+
---


# Question
Title: (HELP)How to read Physical Dimensions in datasheets
Sir/ Ma'am, . How to read the dimension labels of this IC?

# Answer
> 2 votes
I have annotated your drawing a little to help you understand it better:

# Answer
> 1 votes
Values above the horizontal lines are in inches. Values below it are in mm.

---
Tags: electronics, components
---


# Question
Title: how to change increase pwm frequency by changing resolution?
As told in this post:

http://forum.arduino.cc/index.php/topic,16612.0.html#

The arduino can achive up to 62.5khz with 8 bits resolution

adding this line in the setup:

```
TCCR0B = TCCR0B & 0b11111000 | 0x01

```

sets the divisor of the timer to 1

```
int output = 5;
void setup() {
  // put your setup code here, to run once:
  TCCR0B = TCCR0B & 0b11111000 | 0x01;

}

void loop() {
  analogWrite(output,127);

}

```

But I need a frequency of 100khz or as close as possible, the 8 bits resolution is not necessary of my porpouse, it will work just fine with 6 or 7 bits.

# Answer
Here's code for timer 1 on a atmega32u tested in a Teensy 2.0:

```
void setup() {
  // put your setup code here, to run once:

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB5) | bit(DDB6);  // atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

```

The trick here is using OCRxA to set the TOP value/resolution/frequency of the timer, and then using OCRxB as the PWM-controlled output. The popular examples aim for a specific frequency with toggling, but often don't go into showing the PWM with the non-TOP OCRxx registers.

If you check the registers for your chip, this should also adapt to the other timers. Here, I used timer1 to avoid confusing delay() and millis().
> 1 votes

---
Tags: pwm
---


# Question
Title: Arduino Nano PWM output acting strange after running for a day or so
I have an Arduino Nano, and I have some issues with it. Basically it needs to control the brightness of a lamp via PWM (plus some circuitry of course). It's hooked up via serial to a little x86 embedded board which runs Linux, and that board is telling the Arduino the desired brightness level (0-255) every 5 seconds over serial. So the only thing the Arduino has to do is retrieve numbers from the other device over serial, and set the PWM output to those values. Here's the code that runs on the Arduino (I inserted some comments so it's easier to read):

***Edit: I removed the original code to clean things up as it's not relevant anymore, but you can still view it here.***

There's nothing fancy about the code really. It checks for incoming data about 10 times a second, and if there's any, it converts it into an `int` and sets the PWM output to that value. I know, that part where I manually extract the number characters probably could be replaced by Arduino library calls for cleaner code, but whatever. It works just fine.

The incoming data as I mentioned is the textual representation of an integer ranging from 0-255 followed by a new line character. This data is sent to the Arduino once every 5 seconds.

So whenever I turn this on, it works just fine for a day or so. But this is supposed to be a system that's constantly on 24/7. If I leave it running for a day or so, the output will start acting weird. I already checked, and the values that the other device sends are perfectly normal. It's the Arduino that messes up something. The brightness is NOT what it needs to be. The Arduino is outputting wrong PWM values. If I simply reset the Arduino (without restarting the other device), everything goes back to normal, and it works again for a day, so the problem is definitely in the Arduino somewhere. But I don't think it's in my code. This piece of code looks super simple and innocent, and I bet it is. I have no idea what causes this.

Could this be a hardware problem? I do have another Arduino, so I could try replacing it with that one. I haven't tried that yet since I already put all components in a case, fixed everything in place with screws, and soldered wires directly to the Arduino, so I would rather not replace it if it's not necessary.

So, any ideas on what could cause this?

---

**Update:**

I updated the programs on both devices to use a more error-prone protocol for communicating (as suggested here), which is kind of similar to the NMEA 0183 protocol (basically a simplified version of that). The sender sends the data in the following format now:

* A single `$` character to indicate the beginning of the data
* The data itself (which is the textual representation of a single integer)
* A single `*` character to indicate the end of the data
* An exactly two digit long hexadecimal checksum value. This is the bitwise XOR of the ASCII codes of all the characters between `$` and `*` (not including those). Letters (if any) are always uppercase.
* The packet is finished up with either `\n` or `\r\n`

An example would be `$178*3E\n`, where \n of course means a newline character.

The code running on the Arduino now is the following:

```
#include <Time.h>

#define _analogWrite(a, b) analogWrite(a, 255-(b))
#define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)

const PROGMEM int pwmPin = 3;
time_t lastUpdate = 0;
String incoming = "";
int pwmValue = 0;

inline void flushSerialBuffer() {
    while (Serial.available()) Serial.read();
}

void setup() {
    Serial.begin(9600);
    Serial.setTimeout(500);
    pinMode(pwmPin, OUTPUT);
    _analogWrite(pwmPin, 0);
}

void loop() {
    time_t currentTime = now();

    if (Serial.available()) {
        delay(250); // Just to make sure that all data has arrived in the buffer
        incoming = "";
        incoming = Serial.readStringUntil('\n');
        flushSerialBuffer();
        int b = incoming.indexOf('$') + 1;
        if (b == 0) return; // -1 was returned
        int e = incoming.indexOf('*', b);
        if (e == -1) return;
        int checksum = 0x0;
        for (int i=b; i<e; i++) checksum ^= incoming[i];
        String hexString = String(checksum, HEX);
        hexString.toUpperCase();
        if (hexString.length() < 2) hexString = String("0") + hexString;
        if (!hexString.equals(incoming.substring(e+1, e+3))) return;

        pwmValue = incoming.substring(b, e).toInt();

        if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
        lastUpdate = currentTime;
    }

    if (currentTime - lastUpdate > 30) pwmValue = 0;

    _analogWrite(pwmPin, pwmValue);

    delay(250);
}

```

It seems like it's working so far, although I'm still testing if this is reliable over a longer period of time. I will edit the question once again to let you know.

---

**Update 2:**

Still no success. After a while it just gets stuck on one PWM value and keeps outputting that, regardless of what it receives over serial. It's kind of like it ignores the incoming data after a day or so. I can verify that the other device still sends data correctly, since if I only restart the Arduino, everything goes back to normal.

# Answer
After trying the original code using Arduino IDE 1.6.7, I do not see a problem with using up memory.

Depending on the nature of the errors you are seeing, another possible explanation is that you are getting spurious data between real events. If electrical noise or whatever produces one or more characters on the serial line in the long interval between real data points, the current code will treat it as a new data point. If the bogus characters are numeric, they will be sent to the pwm. In the more likely case of non-numeric data, this code converts them to a value of 0 and sends that to the port. This situation is likely if the Arduino is more than a few feet from the PC. A slew rate limited differential driver and receiver like the MAX488 should greatly reduce the chance of this happening. Also make sure there is a good ground between the ends.

You could also reduce the chance of undetected data errors by delimiting your data with something like a '$' to start, then the data, then '\*' then a checksum then a newline. The checksum could be simply the sum of all the characters up to the \*, truncated to 8 bits and sent as 2 hex characters. This is what the NMEA protocol used by GPS receivers does. At the receiving end you only accept data packets with the proper format and checksum.
> 1 votes

# Answer
You have a race condition in your code: if you try to read a message while it's being sent, you may catch only a partial message, and end up reading the wrong numbers. My bet is that this is exactly what is biting you. Once this happens once, it is bound to happen again for some time, since 5 seconds is a multiple of your 100 ms delay.

The right thing to do would be to wait until you get the new-line character (then you know you have a complete message) before trying to parse the message. A quick and dirty hack is to just `delay(10)` after `Serial.available()` but before `Serial.readString()`.
> 0 votes

# Answer
Your problem may be related to the dynamic memory allocation of your String objects. Each time the Arduino receives data, you are creating two new String objects. Perhaps the memory is not being released properly, causing eventual exhaustion of your RAM.

You could make your Strings global and empty them out each time, but a far better solution would be to replace all your string manipulation with a call to Serial.ParseInt() so your big if block becomes

`if (Serial.available()) {
 pwmValue = Serial.ParseInt();
 while(Serial.available() > 0 {
 Serial.read(); // flush anything after the integer
 // Save the current time
 lastUpdate = currentTime;
 }`

Serial.ParseInt also makes use of the timeout so you don't have to worry about partial values being read.
> 0 votes

---
Tags: pwm
---


# Question
Title: Will enabling parity bit actually decrease corruption?
I have an Arduino Mega communicating with a Bluetooth adapter through one of the auxiliary hardware serial ports. It works, but there appears to be a corruption rate of approximately 1 in 200 small packets. In other words, about 0.5% of the packets are being corrupted, it seems. I have the option of configuring the serial mode on both ends. While I cannot decrease the baud rate for bandwidth reasons, I do have enough room to enable *parity* or a larger *stop bit* if that would help.

Granted the corruption is on the serial line and not on the Bluetooth, if I enable parity, will this actually decrease the corruption rate? Or will the corrupt bytes simply be dropped without being re-sent? In other words, what happens when the hardware detects a bad byte?

# Answer
> 5 votes
Parity doesn't, and was never intended to, decrease corruption.

All parity does is allow you to DETECT errors. If you detect errors, you still have to handle them.

Parity in memory is usually fatal - your code or data is corrupt, the solution is to halt the box, to stop this corruption (in memory) getting on to disk.

When used in communication (as it is here), parity errors usually mean you have to request a re-transmit (or, if acknowledgements are sent back, fail to send an acknowledgement and wait for an automatic re-transmit).

Also, be aware that the relevant error rate is per bit, not per packet. If a small packet (very small!) is 20 bytes, and there is corruption 0.5% of those packets, this indicates a 0.5% / 20 bytes per packet / 8 bits per byte (assuming 7 data bits, 1 parity bit, for example). This comes out to 0.003% errors.

Note that parity checks only work for 1-bit errors - in fact, a 2-bit error (in the same byte), the parity change will cancel out, and it will look ok.

An alternative to requesting re-transmits, is to use forward error correction - send redundant data (reducing your bandwidth). A very easy scheme is to send each packet twice (halving your bandwidth). You still need error checking (or some checksum) - if two packets are different, you still need to know which one was right. Checksums, on a more complex device, could let you try each combination, but for an Arduino, this would probably be too expensive (the code would take up sizable space, which an Arduino may, or may not, have spare).

All of this is usually written into higher level protocols (TCP, used for most internet file transmission, ZModem file transfer used for modems prior to the Internet). Other protocols, such as internet radio, will use either forward error correction, or will accept the occasional glitch.

# Answer
> 3 votes
Parity by itself does not reduce the error rate, it is used to detect errors. It is up to higher level protocols to determine what to do when the error is detected.

To answer your question about stop bits, going to two *might* help. The extra stop bit adds a 1-bit-time gap between characters and gives the receiver a little more time to sync up with the transmitter. If the baud rates are a little off between the sender and receiver, it would make it more likely that errors would be limited to one character rather than a whole string of them. That said, the 2 stop bit option is mostly a relic from the days of mechanical Teletype machines. These days it is usually better to make sure both clocks are at the correct frequency.

Have you determined where the errors are occurring - in the serial connection between the Mega and the BT adapter, in the BT link itself, or at the other end? With short wires, correct baud rates (check for the correct clock frequency), a good ground, and correct logic voltages, the raw error rate in the serial connection should be extremely low. I would focus on finding the source of the errors before trying to correct them.

# Answer
> 1 votes
I am guessing that the problem is that your clock is not 100% divisable to produce exactly 115200. If so it makes sense that communication sometimes fail.

See this question for more details, in particular the link to WormFood's AVR Baud Rate Calculator.

# Answer
> 1 votes
Parity checking will only let your code detect a corrupted byte, and not very well at that. Assuming your primary goal is to get packets transferred reliably, you'd be better off to add a checksum to each packet sent, testing the checksum when the packet is received, and asking the transmitter to re-send a failed packet. Since you only expect 1 packet in 200 to be retransmitted, your bandwidth shouldn't take a big hit.

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


# Question
Title: Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8?
It keeps giving me this warning:

> You are using a version of the Arduino IDE that is newer than available at the release of this plugin.\`

Does this means I need to use a night build?

# Answer
> 1 votes
V2.2 is pretty old by now. As far as I recall it should work fine.

V2.2 of the Arduino eclipse plugin should work fine with the Arduino IDE version 1.5.8. What that phrase wants to say is: the plugin V2.2 was released before Arduino IDE 1.5.8 was released; as such the code can not make a statement on the compatibility.

But again V2.2 is old. We hope to release V3.0 end of February 2016

---
Tags: eclipse
---


# Question
Title: Bluetooth transfer problem with big files
I want to send some data from an Arduino Mega to an android device via bluetooth (HC-06). I have installed some sensors whose values are frequently written in an SD card. Every time a new string line is added in a text file of the SD card. This is the format of the line

```
27/5/2015,11:55:00,34.00,27.00,42.50,26.80,47.80,26.00,24.62,24.12,26,0,0,708,1023,1023,1023,1023,10.5,10.5,10.5,10.5

```

and this is part of the code. I send from a bluetooth terminal the string "download" and after that the text file is opened and every line is readed and sent to the android device via bluetooth.

```
void loop(void){
    while(Serial1.available()) {
       character = Serial1.read();
       content.concat(character);
     }

if (content == "download") {
    Serial.println(content);
    content = "";
    read_from_SD_Card();
    }
    ........................
    ........................
    ........................
}

void read_from_SD_Card(){
    myFile = SD.open("test.txt");
    if (myFile) {
        Serial1.println("test.txt:");

        while (myFile.available()) {
            Serial1.write(myFile.read());
      }
      myFile.close();
    }
else {
  Serial1.println("error opening test.txt");
  }
}

```

The problems are:

* the data are downloaded only after an upload of the sketch has been done. (I can't upload the sketch once and download the data from time to time)
* No more than 10-20 lines can be downloaded. With bigger files the downloading seems to slow down and finally stops after a few lines.

Any thoughts would be appreciated.

# Answer
I suspect that this is a String class heap-fragementation issue (again). To test this you could sending a fixed string buffer (vector of characters, "Hello world" :). Do not use String and SD/FAT in the test. Just send a large number of lines with dummy data.

If this works replace the String usage with a character buffer. Fill it from the SD file (buffer size at a time) and write to Serial.

Cheers!
> 1 votes

# Answer
```
String content;
void loop()
{
    while(Serial1.available()) {
       character = Serial1.read();
       content.concat(character);
     }

if (content == "download")
{
    Serial1.println(content);
    content = "";
    read_from_SD_Card();
    }

........................
    ........................
    ........................
}//end of loop()

read_from_SD_Card(){
    myFile = SD.open("test.txt");
    if (myFile) {
        Serial1.println("test.txt:");

        while (myFile.available()) {
            Serial1.print(myFile.read());
      }
      myFile.close();
    }
else {
  Serial1.println("error opening test.txt");
  }
  Serial1.readString()//to flush the serial buffer.
}

```
> 0 votes

# Answer
@user3060854 -- were you able to resolve this? A higher baud rate for communicating with the HC bluetooth module can help with your speed/slowdown problem. But have noticed baud rates above 115200 dont work well. I believe the problem is the receiver baud rate %error, which should not happen at 250k baud. But I havent figured out how to set a baud rate of 250k in the BT module. The question with details is here --- Setting non-standard baud rate (250k) for the HC-05 bluetooth module
> 0 votes

---
Tags: bluetooth
---