# Question
Title: How can I get a unique address for all my Arduino boards while in RS485?
My attempt is to know how to identify the board I'll be sending parameters to in a serial connection like rs485. I'm asking because I will have about 11 or so mcu's as "Rx slaves" while my pc is the Master "Tx". I want to know how my code block is being sent to a specific board will be received by just that board and not all the other boards connected to that Rx port COM?

If I send 'LT2|LP3|LM5|LR4|LI6' and I want that to be for one specific Arduino, I don't want all the other 10 arduinos to take those parameters in this serial Rx line.

@Federico Fissore you mentioned in another post "Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says"

```
[16818.451423] usb 3-2: SerialNumber: 85235353137351E02242

```

how and where can i find this info?

# Answer
> 1 votes
> I dont think that could have sounded more advanced for me then anything thus far. Any links on how to go about that?

First, run a sketch like this for each board:

```
#include <EEPROM.h>

const int SERIAL_NUMBER_ADDRESS = 1023;
const byte SERIAL_NUMBER = 42;
void setup ()
  {
  // don't do it if it has been done before
  if (EEPROM.read(SERIAL_NUMBER_ADDRESS) != SERIAL_NUMBER)
    EEPROM.write(SERIAL_NUMBER_ADDRESS, SERIAL_NUMBER);
  }  // end of setup

void loop () { }

```

The serial number **address** can be any address in range for that chip - a Uno has 1024 bytes. I chose 1023 to leave the other addresses free, but it could be 0. Anything you don't need for any other purpose.

Then write a different serial number to each board (eg. 42, 43, 44, 45). Obviously you change the sketch each time you upload to a different board.

---

Once you have done this (once per board) now each board "knows" its serial number. You can detect this in your main sketch:

```
#include <EEPROM.h>

const int SERIAL_NUMBER_ADDRESS = 1023;
byte serialNumber;
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  serialNumber = EEPROM.read(SERIAL_NUMBER_ADDRESS);
  Serial.print (F("Serial number of this board is: "));
  Serial.println (int (serialNumber));
  }  // end of setup

void loop () { }

```

Output for me in this case was:

```
Serial number of this board is: 42

```

---

Also I have a post about RS485 on my forum.

# Answer
> 1 votes
Just assign every node a variable like "const int ID = 5" and so on and then before sending the instructions send a line terminator, the ID, line terminator and the data you need to send to the nodes. Every device listens but they all wait their ID to accept the commands. For example:

```
Serial.write('\n');
Serial.print(ID);
Serial.write('\n');
Serial.print(|LT2|LP3|LM5|LR4|LI6);
Serial.write('\n');

```

NOTE: This is the easiest way. Most likely not the most reliable or optimized.

---
Tags: serial, rs485
---


title: Response of Modbus Protocol

text:
# Question
Title: Response of Modbus Protocol
I have the below code. This code is successfully compiling and uploading, but I am not getting any response from Slave. What do I need to do?

Some time data being received from Slave (I get this error):

My main code:

```
#define ID  1
/*static float ARDUINO_ANALOG_SCALING = 0.00488758;
static float Ydegree;
static int Sensor_Value;
float Yvoltage;

*/

Modbus slave(ID, 0, 0);
boolean led;
int8_t state = 0;
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[9];
float latitude=13.08;

void setup() {
  pinMode(13, OUTPUT);
  slave.begin( 19200 );
  tempus = millis() + 100;
  digitalWrite(13, HIGH );
}

void loop() {

  state = slave.poll( au16data, 9 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

  au16data[4] = analogRead(0);
  au16data[5] = analogRead(1);

  au16data[6] = slave.getInCnt();
  au16data[7] = slave.getOutCnt();
  au16data[8] = slave.getErrCnt();
}

```

Modbus code:

```
#define  MAX_BUFFER  64
typedef struct {
  uint8_t u8id;          /*!< slave address between 1 and 247. 0 means broadcast */
  uint8_t u8fct;         /*!< function code: 1, 2, 3, 4, 5, 6, 15 or 16 */
  uint16_t u16RegAdd;    /*!< address of the first register to access at slave/s */
  uint16_t u16CoilsNo;   /*!< number of coils or registers to access */
  uint16_t *au16reg;     /*!< pointer to memory image in master */
}
modbus_t;

enum {
  RESPONSE_SIZE = 6,
  EXCEPTION_SIZE = 3,
  CHECKSUM_SIZE = 2
};

enum MESSAGE {
  ID = 0,
  FUNC,
  ADD_HI,
  ADD_LO,
  NB_HI,
  NB_LO,
  BYTE_CNT
};

enum MB_FC {
  MB_FC_NONE                     = 0,   /*!< null operator */
  MB_FC_READ_COILS               = 1,   /*!< FCT=1 -> read coils or digital outputs */
  MB_FC_READ_DISCRETE_INPUT      = 2,   /*!< FCT=2 -> read digital inputs */
  MB_FC_READ_REGISTERS           = 3,   /*!< FCT=3 -> read registers or analog outputs */
  MB_FC_READ_INPUT_REGISTER      = 4,   /*!< FCT=4 -> read analog inputs */
  MB_FC_WRITE_COIL               = 5,   /*!< FCT=5 -> write single coil or output */
  MB_FC_WRITE_REGISTER           = 6,   /*!< FCT=6 -> write single register */
  MB_FC_WRITE_MULTIPLE_COILS     = 15,  /*!< FCT=15 -> write multiple coils or outputs */
  MB_FC_WRITE_MULTIPLE_REGISTERS = 16   /*!< FCT=16 -> write multiple registers */
};

enum COM_STATES {
  COM_IDLE                     = 0,
  COM_WAITING                  = 1

};

enum ERR_LIST {
  ERR_NOT_MASTER                = -1,
  ERR_POLLING                   = -2,
  ERR_BUFF_OVERFLOW             = -3,
  ERR_BAD_CRC                   = -4,
  ERR_EXCEPTION                 = -5
};

enum {
  NO_REPLY = 255,           /*!< */
  EXC_FUNC_CODE = 1,        /*!< Function code not available */
  EXC_ADDR_RANGE = 2,       /*!< Address beyond available space for Modbus registers */
  EXC_REGS_QUANT = 3,       /*!< Coils or registers number beyond the available space */
  EXC_EXECUTE = 4           /*!< */
};

const unsigned char fctsupported[] = {
  MB_FC_READ_COILS,
  MB_FC_READ_DISCRETE_INPUT,
  MB_FC_READ_REGISTERS,
  MB_FC_READ_INPUT_REGISTER,
  MB_FC_WRITE_COIL,
  MB_FC_WRITE_REGISTER,
  MB_FC_WRITE_MULTIPLE_COILS,
  MB_FC_WRITE_MULTIPLE_REGISTERS
};

#define T35  5

class Modbus {
private:
  HardwareSerial *port; //!< Pointer to Serial class object
  uint8_t u8id; //!<0=master, 1..247=slave number
  uint8_t u8serno; //!<serial port: 0-Serial, 1..3-Serial1..Serial3
  uint8_t u8txenpin; //!<flow control pin: 0=USB or RS-232 mode, >0=RS-485 mode
  uint8_t u8state;
  uint8_t au8Buffer[MAX_BUFFER];
  uint8_t u8BufferSize;
  uint8_t u8lastRec;
  uint16_t *au16regs;
  uint16_t u16InCnt, u16OutCnt, u16errCnt;
  uint16_t u16timeOut;
  uint32_t u32time, u32timeOut;
  uint8_t u8regsize;

  void init(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin);
  void sendTxBuffer(); // transmit buffer to serial port
  int8_t getRxBuffer(); // get serial buffer contents
  uint16_t calcCRC(uint8_t u8length); // get CRC from au8Buffer until u8length
  uint8_t validateAnswer();
  uint8_t validateRequest(); // validate master request
  void get_FC1(); // *** only master ***
  void get_FC3(); // *** only master ***
  int8_t process_FC1( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC3( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC5( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC6( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC15( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  int8_t process_FC16( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
  void buildException( uint8_t u8exception ); // build exception message

public:
  Modbus(); // !< Default Constructor
  Modbus(uint8_t u8id, uint8_t u8serno); // !< Constructor
  Modbus(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin); // !< Full Constructor
  void begin(long u32speed);
  void begin();
  void setTimeOut( uint16_t u16timeout); //!< write communication watch-dog timer
  uint16_t getTimeOut(); //!< get communication watch-dog timer value
  boolean getTimeOutState(); //!< get communication watch-dog timer state
  int8_t query( modbus_t telegram ); //!< only for master
  int8_t poll(); //!< cyclic poll for master
  int8_t poll( uint16_t *regs, uint8_t u8size ); //!< cyclic poll for slave
  uint16_t getInCnt(); //!< number of incoming messages
  uint16_t getOutCnt(); //!< number of outcoming messages
  uint16_t getErrCnt(); //!< error counter
  uint8_t getID(); //!< get slave ID between 1 and 247
  uint8_t getState();
  uint8_t getLastError(); //!< get last error message
  void setID( uint8_t u8id ); //!< write new ID for the slave
  void end(); //!< finish any communication and release serial communication port
};

Modbus::Modbus() {
  init(0, 0, 0);
}

Modbus::Modbus(uint8_t u8id, uint8_t u8serno) {
  init(u8id, u8serno, 0);
}

Modbus::Modbus(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin) {
  init(u8id, u8serno, u8txenpin);
}

void Modbus::begin(long u32speed) {

  switch ( u8serno ) {
#if defined(UBRR1H)
  case 1:
    port = &Serial1;
    break;
#endif

#if defined(UBRR2H)
  case 2:
    port = &Serial2;
    break;
#endif

#if defined(UBRR3H)
  case 3:
    port = &Serial3;
    break;
#endif
  case 0:
  default:
    port = &Serial;
    break;
  }

  // port->begin(u32speed, u8config);
  port->begin(u32speed);
  if (u8txenpin > 1) { // pin 0 & pin 1 are reserved for RX/TX
    // return RS485 transceiver to transmit mode
    pinMode(u8txenpin, OUTPUT);
    digitalWrite(u8txenpin, LOW);
  }

  port->flush();
  u8lastRec = u8BufferSize = 0;
  u16InCnt = u16OutCnt = u16errCnt = 0;
}

void Modbus::begin() {
  begin(19200);
}

void Modbus::setID( uint8_t u8id) {
  if (( u8id != 0) && (u8id <= 247)) {
    this->u8id = u8id;
  }
}

uint8_t Modbus::getID() {
  return this->u8id;
}

void Modbus::setTimeOut( uint16_t u16timeOut) {
  this->u16timeOut = u16timeOut;
}

boolean Modbus::getTimeOutState() {
  return (millis() > u32timeOut);
}

uint16_t Modbus::getInCnt() {
  return u16InCnt;
}

uint16_t Modbus::getOutCnt() {
  return u16OutCnt;
}

uint16_t Modbus::getErrCnt() {
  return u16errCnt;
}

uint8_t Modbus::getState() {
  return u8state;
}

int8_t Modbus::query( modbus_t telegram ) {
  uint8_t u8regsno, u8bytesno;
  if (u8id != 0) return -2;
  if (u8state != COM_IDLE) return -1;

  if ((telegram.u8id == 0) || (telegram.u8id > 247)) return -3;

  au16regs = telegram.au16reg;

  // telegram header
  au8Buffer[ ID ]         = telegram.u8id;
  au8Buffer[ FUNC ]       = telegram.u8fct;
  au8Buffer[ ADD_HI ]     = highByte(telegram.u16RegAdd );
  au8Buffer[ ADD_LO ]     = lowByte( telegram.u16RegAdd );

  switch ( telegram.u8fct ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
  case MB_FC_READ_REGISTERS:
  case MB_FC_READ_INPUT_REGISTER:
    au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
    au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
    u8BufferSize = 6;
    break;
  case MB_FC_WRITE_COIL:
    au8Buffer[ NB_HI ]      = ((au16regs[0] > 0) ? 0xff : 0);
    au8Buffer[ NB_LO ]      = 0;
    u8BufferSize = 6;
    break;
  case MB_FC_WRITE_REGISTER:
    au8Buffer[ NB_HI ]      = highByte(au16regs[0]);
    au8Buffer[ NB_LO ]      = lowByte(au16regs[0]);
    u8BufferSize = 6;
    break;
  case MB_FC_WRITE_MULTIPLE_COILS:
    u8regsno = telegram.u16CoilsNo / 16;
    u8bytesno = u8regsno * 2;
    if ((telegram.u16CoilsNo % 16) != 0) {
      u8bytesno++;
      u8regsno++;
    }

    au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
    au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
    au8Buffer[ NB_LO + 1 ]    = u8bytesno;
    u8BufferSize = 7;

    u8regsno = u8bytesno = 0; // now auxiliary registers
    for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {

    }
    break;

  case MB_FC_WRITE_MULTIPLE_REGISTERS:
    au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
    au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
    au8Buffer[ NB_LO + 1 ]    = (uint8_t) ( telegram.u16CoilsNo * 2 );
    u8BufferSize = 7;

    for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {
      au8Buffer[ u8BufferSize ] = highByte( au16regs[ i ] );
      u8BufferSize++;
      au8Buffer[ u8BufferSize ] = lowByte( au16regs[ i ] );
      u8BufferSize++;
    }
    break;
  }

  sendTxBuffer();
  u8state = COM_WAITING;
  return 0;
}

int8_t Modbus::poll() {
  // check if there is any incoming frame
  uint8_t u8current = port->available();

  if (millis() > u32timeOut) {
    u8state = COM_IDLE;
    u16errCnt++;
    return 0;
  }

  if (u8current == 0) return 0;

  // check T35 after frame end or still no frame end
  if (u8current != u8lastRec) {
    u8lastRec = u8current;
    u32time = millis() + T35;
    return 0;
  }
  if (millis() < u32time) return 0;

  // transfer Serial buffer frame to auBuffer
  u8lastRec = 0;
  int8_t i8state = getRxBuffer();
  if (i8state < 7) {
    u8state = COM_IDLE;
    u16errCnt++;
    return i8state;
  }

  // validate message: id, CRC, FCT, exception
  uint8_t u8exception = validateAnswer();
  if (u8exception != 0) {
    u8state = COM_IDLE;
    return u8exception;
  }

  // process answer
  switch ( au8Buffer[ FUNC ] ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
    // call get_FC1 to transfer the incoming message to au16regs buffer
    get_FC1( );
    break;
  case MB_FC_READ_INPUT_REGISTER:
  case MB_FC_READ_REGISTERS :
    // call get_FC3 to transfer the incoming message to au16regs buffer
    get_FC3( );
    break;
  case MB_FC_WRITE_COIL:
  case MB_FC_WRITE_REGISTER :
  case MB_FC_WRITE_MULTIPLE_COILS:
  case MB_FC_WRITE_MULTIPLE_REGISTERS :
    // nothing to do
    break;
  default:
    break;
  }
  u8state = COM_IDLE;
  return u8BufferSize;
}

int8_t Modbus::poll( uint16_t *regs, uint8_t u8size ) {

  au16regs = regs;
  u8regsize = u8size;

  // check if there is any incoming frame
  uint8_t u8current = port->available();
  if (u8current == 0) return 0;

  // check T35 after frame end or still no frame end
  if (u8current != u8lastRec) {
    u8lastRec = u8current;
    u32time = millis() + T35;
    return 0;
  }
  if (millis() < u32time) return 0;

  u8lastRec = 0;
  int8_t i8state = getRxBuffer();
  if (i8state < 7) return i8state;

  // check slave id
  if (au8Buffer[ ID ] != u8id) return 0;

  // validate message: CRC, FCT, address and size
  uint8_t u8exception = validateRequest();
  if (u8exception > 0) {
    if (u8exception != NO_REPLY) {
      buildException( u8exception );
      sendTxBuffer();
    }
    return u8exception;
  }

  u32timeOut = millis() + long(u16timeOut);

  // process message
  switch ( au8Buffer[ FUNC ] ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
    return process_FC1( regs, u8size );
    break;
  case MB_FC_READ_INPUT_REGISTER:
  case MB_FC_READ_REGISTERS :
    return process_FC3( regs, u8size );
    break;
  case MB_FC_WRITE_COIL:
    return process_FC5( regs, u8size );
    break;
  case MB_FC_WRITE_REGISTER :
    return process_FC6( regs, u8size );
    break;
  case MB_FC_WRITE_MULTIPLE_COILS:
    return process_FC15( regs, u8size );
    break;
  case MB_FC_WRITE_MULTIPLE_REGISTERS :
    return process_FC16( regs, u8size );
    break;
  default:
    break;
  }
}

/* _____PRIVATE FUNCTIONS_____________________________________________________ */

void Modbus::init(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin) {
  this->u8id = u8id;
  this->u8serno = (u8serno > 3) ? 0 : u8serno;
  this->u8txenpin = u8txenpin;
  this->u16timeOut = 1000;
}

int8_t Modbus::getRxBuffer() {
  boolean bBuffOverflow = false;

  if (u8txenpin > 1) digitalWrite( u8txenpin, LOW );

  u8BufferSize = 0;
  while ( port->available() ) {
    au8Buffer[ u8BufferSize ] = port->read();
    u8BufferSize ++;

    if (u8BufferSize >= MAX_BUFFER) bBuffOverflow = true;
  }
  u16InCnt++;

  if (bBuffOverflow) {
    u16errCnt++;
    return ERR_BUFF_OVERFLOW;
  }
  return u8BufferSize;
}

void Modbus::sendTxBuffer() {
  uint8_t i = 0;

  // append CRC to message
  uint16_t u16crc = calcCRC( u8BufferSize );
  au8Buffer[ u8BufferSize ] = u16crc >> 8;
  u8BufferSize++;
  au8Buffer[ u8BufferSize ] = u16crc & 0x00ff;
  u8BufferSize++;

  // set RS485 transceiver to transmit mode
  if (u8txenpin > 1) {
    switch ( u8serno ) {
#if defined(UBRR1H)
    case 1:
      UCSR1A = UCSR1A | (1 << TXC1);
      break;
#endif

#if defined(UBRR2H)
    case 2:
      UCSR2A = UCSR2A | (1 << TXC2);
      break;
#endif

#if defined(UBRR3H)
    case 3:
      UCSR3A = UCSR3A | (1 << TXC3);
      break;
#endif
    case 0:
    default:
      UCSR0A = UCSR0A | (1 << TXC0);
      break;
    }
    digitalWrite( u8txenpin, HIGH );
  }

  // transfer buffer to serial line
  port->write( au8Buffer, u8BufferSize );

  // keep RS485 transceiver in transmit mode as long as sending
  if (u8txenpin > 1) {
    switch ( u8serno ) {
#if defined(UBRR1H)
    case 1:
      while (!(UCSR1A & (1 << TXC1)));
      break;
#endif

#if defined(UBRR2H)
    case 2:
      while (!(UCSR2A & (1 << TXC2)));
      break;
#endif

#if defined(UBRR3H)
    case 3:
      while (!(UCSR3A & (1 << TXC3)));
      break;
#endif
    case 0:
    default:
      while (!(UCSR0A & (1 << TXC0)));
      break;
    }

    // return RS485 transceiver to receive mode
    digitalWrite( u8txenpin, LOW );
  }
  port->flush();
  u8BufferSize = 0;

  // set time-out for master
  u32timeOut = millis() + (unsigned long) u16timeOut;

  // increase message counter
  u16OutCnt++;
}

/**
 * @brief
 * This method calculates CRC
 *
 * @return uint16_t calculated CRC value for the message
 * @ingroup buffer
 */
uint16_t Modbus::calcCRC(uint8_t u8length) {
  unsigned int temp, temp2, flag;
  temp = 0xFFFF;
  for (unsigned char i = 0; i < u8length; i++) {
    temp = temp ^ au8Buffer[i];
    for (unsigned char j = 1; j <= 8; j++) {
      flag = temp & 0x0001;
      temp >>= 1;
      if (flag)
        temp ^= 0xA001;
    }
  }
  // Reverse byte order.
  temp2 = temp >> 8;
  temp = (temp << 8) | temp2;
  temp &= 0xFFFF;
  // the returned value is already swapped
  // crcLo byte is first & crcHi byte is last
  return temp;
}

uint8_t Modbus::validateRequest() {
  // check message crc vs calculated crc
  uint16_t u16MsgCRC =
    ((au8Buffer[u8BufferSize - 2] << 8)
    | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
  if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
    u16errCnt ++;
    return NO_REPLY;
  }

  // check fct code
  boolean isSupported = false;
  for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
    if (fctsupported[i] == au8Buffer[FUNC]) {
      isSupported = 1;
      break;
    }
  }
  if (!isSupported) {
    u16errCnt ++;
    return EXC_FUNC_CODE;
  }

  // check start address & nb range
  uint16_t u16regs = 0;
  uint8_t u8regs;
  switch ( au8Buffer[ FUNC ] ) {
  case MB_FC_READ_COILS:
  case MB_FC_READ_DISCRETE_INPUT:
  case MB_FC_WRITE_MULTIPLE_COILS:
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
    u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]) / 16;
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  case MB_FC_WRITE_COIL:
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  case MB_FC_WRITE_REGISTER :
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  case MB_FC_READ_REGISTERS :
  case MB_FC_READ_INPUT_REGISTER :
  case MB_FC_WRITE_MULTIPLE_REGISTERS :
    u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
    u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]);
    u8regs = (uint8_t) u16regs;
    if (u8regs > u8regsize) return EXC_ADDR_RANGE;
    break;
  }
  return 0; // OK, no exception code thrown
}

uint8_t Modbus::validateAnswer() {
  // check message crc vs calculated crc
  uint16_t u16MsgCRC =
    ((au8Buffer[u8BufferSize - 2] << 8)
    | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
  if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
    u16errCnt ++;
    return NO_REPLY;
  }

  // check exception
  if ((au8Buffer[ FUNC ] & 0x80) != 0) {
    u16errCnt ++;
    return ERR_EXCEPTION;
  }

  // check fct code
  boolean isSupported = false;
  for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
    if (fctsupported[i] == au8Buffer[FUNC]) {
      isSupported = 1;
      break;
    }
  }
  if (!isSupported) {
    u16errCnt ++;
    return EXC_FUNC_CODE;
  }

  return 0; // OK, no exception code thrown
}

void Modbus::buildException( uint8_t u8exception ) {
  uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code

  au8Buffer[ ID ]      = u8id;
  au8Buffer[ FUNC ]    = u8func + 0x80;
  au8Buffer[ 2 ]       = u8exception;
  u8BufferSize         = EXCEPTION_SIZE;
}

void Modbus::get_FC1() {
  uint8_t u8byte, i;
  u8byte = 0;

  // check the answer length
  boolean bEvenOdd =
    ( au8Buffer[ ADD_HI ] % 2 == 0) ?
  false :
  true;

  uint8_t u8WordsNo =
    ( !bEvenOdd ) ?
  au8Buffer[ ADD_HI ] / 2 :
  au8Buffer[ ADD_HI ] / 2 + 1;

  for (i = 0; i < u8WordsNo; i++) {
    au16regs[ i ] = word(
    au8Buffer[ u8byte ],
    au8Buffer[ u8byte + 1 ]);
    u8byte += 2;
  }

  // cut last byte
  if (bEvenOdd) {
    au16regs[ u8WordsNo - 1 ] &= 0xff00;
  }
}

void Modbus::get_FC3() {
  uint8_t u8byte, i;
  u8byte = 3;

  for (i = 0; i < au8Buffer[ 2 ] / 2; i++) {
    au16regs[ i ] = word(
    au8Buffer[ u8byte ],
    au8Buffer[ u8byte + 1 ]);
    u8byte += 2;
  }
}

int8_t Modbus::process_FC1( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8currentRegister, u8currentBit, u8bytesno, u8bitsno;
  uint8_t u8CopyBufferSize;
  uint16_t u16currentCoil, u16coil;

  // get the first and last coil from the message
  uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

  // put the number of bytes in the outcoming message
  u8bytesno = (uint8_t) (u16Coilno / 8);
  if (u16Coilno % 8 != 0) u8bytesno ++;
  au8Buffer[ ADD_HI ]  = u8bytesno;
  u8BufferSize         = ADD_LO;

  // read each coil from the register map and put its value inside the outcoming message
  u8bitsno = 0;

  for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {
    u16coil = u16StartCoil + u16currentCoil;
    u8currentRegister = (uint8_t) (u16coil / 16);
    u8currentBit = (uint8_t) (u16coil % 16);

    bitWrite(
    au8Buffer[ u8BufferSize ],
    u8bitsno,
    bitRead( regs[ u8currentRegister ], u8currentBit ) );
    u8bitsno ++;

    if (u8bitsno > 7) {
      u8bitsno = 0;
      u8BufferSize++;
    }
  }

  // send outcoming message
  if (u16Coilno % 8 != 0) u8BufferSize ++;
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();
  return u8CopyBufferSize;
}

int8_t Modbus::process_FC3( uint16_t *regs, uint8_t u8size ) {

  uint8_t u8StartAdd = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint8_t u8regsno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );
  uint8_t u8CopyBufferSize;
  uint8_t i;

  au8Buffer[ 2 ]       = u8regsno * 2;
  u8BufferSize         = 3;

  for (i = u8StartAdd; i < u8StartAdd + u8regsno; i++) {
    au8Buffer[ u8BufferSize ] = highByte(regs[i]);
    u8BufferSize++;
    au8Buffer[ u8BufferSize ] = lowByte(regs[i]);
    u8BufferSize++;
  }
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;
}

int8_t Modbus::process_FC5( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8currentRegister, u8currentBit;
  uint8_t u8CopyBufferSize;
  uint16_t u16coil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );

  // point to the register and its bit
  u8currentRegister = (uint8_t) (u16coil / 16);
  u8currentBit = (uint8_t) (u16coil % 16);

  // write to coil
  bitWrite(
  regs[ u8currentRegister ],
  u8currentBit,
  au8Buffer[ NB_HI ] == 0xff );

  // send answer to master
  u8BufferSize = 6;
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;

}

int8_t Modbus::process_FC6( uint16_t *regs, uint8_t u8size ) {

  uint8_t u8add = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint8_t u8CopyBufferSize;
  uint16_t u16val = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

  regs[ u8add ] = u16val;

  // keep the same header
  u8BufferSize         = RESPONSE_SIZE;

  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;
}

int8_t Modbus::process_FC15( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8currentRegister, u8currentBit, u8frameByte, u8bitsno;
  uint8_t u8CopyBufferSize;
  uint16_t u16currentCoil, u16coil;
  boolean bTemp;

  // get the first and last coil from the message
  uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
  uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

  // read each coil from the register map and put its value inside the outcoming message
  u8bitsno = 0;
  u8frameByte = 7;
  for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {

    u16coil = u16StartCoil + u16currentCoil;
    u8currentRegister = (uint8_t) (u16coil / 16);
    u8currentBit = (uint8_t) (u16coil % 16);

    bTemp = bitRead(
    au8Buffer[ u8frameByte ],
    u8bitsno );

    bitWrite(
    regs[ u8currentRegister ],
    u8currentBit,
    bTemp );

    u8bitsno ++;

    if (u8bitsno > 7) {
      u8bitsno = 0;
      u8frameByte++;
    }
  }

  // send outcoming message
  // it's just a copy of the incomping frame until 6th byte
  u8BufferSize         = 6;
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();
  return u8CopyBufferSize;
}

int8_t Modbus::process_FC16( uint16_t *regs, uint8_t u8size ) {
  uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code
  uint8_t u8StartAdd = au8Buffer[ ADD_HI ] << 8 | au8Buffer[ ADD_LO ];
  uint8_t u8regsno = au8Buffer[ NB_HI ] << 8 | au8Buffer[ NB_LO ];
  uint8_t u8CopyBufferSize;
  uint8_t i;
  uint16_t temp;

  // build header
  au8Buffer[ NB_HI ]   = 0;
  au8Buffer[ NB_LO ]   = u8regsno;
  u8BufferSize         = RESPONSE_SIZE;

  // write registers
  for (i = 0; i < u8regsno; i++) {
    temp = word(
    au8Buffer[ (BYTE_CNT + 1) + i * 2 ],
    au8Buffer[ (BYTE_CNT + 2) + i * 2 ]);

    regs[ u8StartAdd + i ] = temp;
  }
  u8CopyBufferSize = u8BufferSize +2;
  sendTxBuffer();

  return u8CopyBufferSize;
}

```

# Answer
My testing indicates that the slave **is** responding. I made up a master from http://playground.arduino.cc/Code/ModbusMaster and tested it:

* Channel 0 is master to slave.
* Channel 1 is slave to master.

Zooming in:
> 1 votes

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


# Question
Title: Running both sensor and addressable LED strips at a same time?
I'm trying to obtain the sensors' readings as well as making the LED strips to light up at this particular pattern, if the sensor readings reaches certain values. But since both of these codes are inside the void `loop()`, there will be a problem. How can I do this correctly?

```
void loop()
{
    currentSensorReading = analogRead(sensorPin);
    Serial.println(currentSensorReading );

    if(currentSensorReading is in range of certain values){
        rainbowCycle(20);
    } else { turn LEDs off }
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

```

# Answer
> 0 votes
Rewrite without using `delay()`. Or alternatively, do the test inside the `for` loop as well, eg.

```
void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);

    // ----------- ADD THESE THREE LINES ---------------
    currentSensorReading = analogRead(sensorPin);
    if(currentSensorReading is NOT in range of certain values)
        return;

  }
}

```

---
Tags: arduino-uno, sensors, led, c++
---


# Question
Title: Help Connecting MicroSD Module with Arduino Uno
I am Trying to make a MicroSD .wav file player using Arduino Uno. I have ordered a MicroSD Card Module from ebay today.

Product Link : http://www.ebay.in/itm/Micro-SD-Card-Module-SD-Storage-Board-TF-Card-Memory-Shield-SPI-For-Arduino-/161696480012?

As You can See in the Product Image, there is **not mentioned on the PCB that which Pin Is ground** or VCC Or any other SPI pin. 1. How will I identify the correct pins of the MicroSD Module ? 2. How can I connect a speaker to arduino to play .wav files. Is Amplifier neccessary? I am weak when it comes to electronics.

I have listened that when I connect a Capacitor in series with speaker, it will boost the output volume. There will not be music but only voice recordings in .wav files. I want to listen it clearly only.

# Answer
OMG, what a vile listing!

Anyway, I think you'll probably find they are in the order listed in the description when the connector is facing south. It's probably printed on the rear of the board which they don't show.

That is, from left to right, GND, VCC, MISO, MOSI, SCK, CS.

As for connecting a speaker, that depends if you want low quality (PWM) audio, or high quality (DAC) audio. The latter requires the addition of an audio shield, most of which have an SD card slot on them already thus alleviating the need for this SD card breakout board.

For the former there is a library and instructions here: http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio
> 1 votes

# Answer
I got my MicroSD Module today. The labels were printed At the bottom side. Dont confuse, CLK = SCK. The VCC goes to arduino 5v.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to use a grove speaker without using delayMicroseconds?
is there another way to replace **delayMicroseconds(BassTab\[note\_index\])** as I cannot have delays in my loop due to the need of having multi-tasking in my sketch.

Grove speaker: http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html

```
/*macro definition of Speaker pin*/
#define SPEAKER 8

int BassTab[]={1911,1702,1516,1431,1275,1136,1012};//bass 1~7

void setup()
{
  pinMode(SPEAKER,OUTPUT);
  digitalWrite(SPEAKER,LOW);
}
void loop()
{
    sound(5);
    delay(5000); //Wait 5second and play the sound again
}

void sound(uint8_t note_index)
{
  for(int i=0;i<100;i++)
  {
    digitalWrite(SPEAKER,HIGH);
    delayMicroseconds(BassTab[note_index]);
    digitalWrite(SPEAKER,LOW);
    delayMicroseconds(BassTab[note_index]);
  }
}

```

# Answer
> 1 votes
It's just a small amplifier and speaker - what you put into the SIG pin gets amplified and sent out the speaker.

Instead of doing the audio generation manually like that I would suggest using the `tone()` function which will generate an audio tone at a desired frequency in the background.

---
Tags: arduino-uno, programming, frequency, sound
---


# Question
Title: Speaker not producing the right sound after a led strip was introduced
Hi, I have been working to produce tones on a speaker and it works with the following code

```
    int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3, NOTE_B3, NOTE_C4};
    ...
    ...
    tone(pin, melody[pitch]);

```

After I included my addressable LED strip sketch codes, the speaker does not produce the same tone as normally it does. It sounded distorted this time round.

```
void loop()
{
  strip.Update(); //NeoPatterns strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800, &StripComplete);
}

```

Class:

```
// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPatterns : public Adafruit_NeoPixel
{
  public:

// Member Variables:
    ...
    ...

void (*OnComplete)();  // Callback on completion of pattern

// Constructor - calls base-class constructor to initialize strip
NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
  : Adafruit_NeoPixel(pixels, pin, type)
{
  OnComplete = callback;
}

// Update the pattern
void Update()
{
  if ((millis() - lastUpdate) > Interval) // time to update
  {
    lastUpdate = millis();
    switch (ActivePattern)
    {
      case RAINBOW_CYCLE:
        RainbowCycleUpdate();
        break;
      default:
        break;
    }
  }
}

// Initialize for a RainbowCycle
void RainbowCycle(uint8_t interval, direction dir = FORWARD)
{
  ActivePattern = RAINBOW_CYCLE;
  Interval = interval;
  TotalSteps = 255;
  Index = 0;
  Direction = dir;
}

// Update the Rainbow Cycle Pattern
    void RainbowCycleUpdate()
    {
      for (int i = 0; i < numPixels(); i++)
      {
        setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
      }
      show(); // When I comment this line, the speaker will work properly. What is happening?
      Increment();
    }

```

# Answer
The `tone()` command is interrupt driven.

To get the tight timing needed by the LED strips interrupts are disabled while sending the data.

That means the tone() command stops while you're updating the LED strips and starts again afterwards.

The end result will be the sound is corrupted - maybe sounding like it's bubbly or underwater or just "rough".

The two basically can't work together and I'm not sure what to suggest to make them work together on a low-end MCU like the AVR.
> 0 votes

---
Tags: arduino-uno, led, sound
---


# Question
Title: arduino due-Python interfacing for high speed data rate
Four our project, I want to send data mesured by an Arduino due to a computer via Pyton very vast. So I tried to make a simple benchmark by sending 10240 int datas to determine the time it take. In order to do this, I first try using the programming port and execute this simple script:

```
int i=1;
int maxv=10240;
int value[10240];
int deb, fin;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(250000); //serial initialisation
  for (i=0 ; i<maxv ; i++){
    value[i]=i;
  }
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("starti"); //flag
  deb=micros();
  for (i=0 ; i<maxv ; i++) { // sending loop
      Serial.println(value[i]);
  }
  fin=micros();
  Serial.println("stopi");
  Serial.println((fin-deb)/1000000.0);
  delay(2000); //waiting
}

```

So with this I can mesure the time it take to send all the datas. And I receive it with this Python's script:

```
import numpy as np
import serial
ser = serial.Serial('/dev/ttyACM0', 250000)

value=np.empty(10240)

temp=ser.readline()

while temp!='starti\r\n': #search for the flag
    temp=ser.readline()

for j in range(10240):
    value[j]=int(ser.readline())

ser.readline()

time=float(ser.readline())
print time

```

with this beaudrate, it take nearly 2.4s which too slow for my purpose. If try another baudrate, 500000 for example I read data like this : `�Ë`$Pd@s\`¥š... I have this for all baudrate higher than 250000.

So I tried the native port which normaly send the data as fast as he can, but we this it took nearly 1.3s, and it's again too slow for my purpose.

I checked that it is not python wich is too slow, by doing the same than in the last example:

```
import time
import numpy as np

value=np.empty(10240)

deb1 = time.clock()

for j in range(10240):
    value[j]=j

fin1= time.clock()
print fin1-deb1

```

and it took only 4ms. So is it clearly the arduino wich send the data to slowly.

So how can I increase the data flux? I have seen the serial.write(buf,len) function which seems does not convert the data into ascii caracters. Does this function will be faster by putting the correct arguments? And, if it's the cas, how can I read this with Python?

# Answer
> 1 votes
There's two things you need to know:

1. The Serial.write(buf, len) function sends the raw data - one byte for every "len" count.
2. On the Due integers are 32-bits, so each one takes 4 bytes.

So first you need to define how big the numbers are you'll be dealing with and use data types that are big enough without being wasteful - you have 3 choices: char, short and int - 8, 16 and 32 bits respectively.

* Values between 0 and 255 use an unsigned char (uint8\_t)
* Values between -128 and 127 use a signed char (int8\_t)
* Values between 0 and 65535 use an unsigned short (uint16\_t)
* Values between -32768 and 32767 use a signed short (int16\_t)
* Values between 0 and 4,294,967,295 use an unsigned int (uint32\_t)
* Values between −2,147,483,648 and 2,147,483,647 a signed int (int32\_t)

One very tricky thing with this kind of *binary* data transfer is knowing where a value starts and ends. You don't get that kind of issue with ASCII representations as you have a line feed and/or a carriage return after each full value and the range of valid characters that make up a value is very narrow and can never contain the delimiting character. You don't have that luxury with binary transfers as there is no byte value that can't appear in a data stream. However, there could be byte sequences that could never appear in the data stream - numbers you know you'll never be using that could form part of a synchronizing header (say, in hexadecimal, 0xFF 0xFF 0xFF 0xFF 0x00 0x00 0x00 0x00 - or in signed shorts that would be a sequence of 65535 65535 0 0) - once you see that sequence of bytes you know you're lined up with your data stream and can receive it byte by byte and build up the right sized values from that.

You can estimate your transfer time by working with the baud rate and knowing the data size. For instance, to transfer 1000 short (16 bit) values at 250000 baud should take around:

* 1000 * 2 = 2000 bytes
* 250000 baud = 25000 bytes per second (8 bits for the byte, 2 bits for the start and stop bit)
* 2000 / 25000 = 0.08s

---
Tags: serial, arduino-due, usb, python
---


# Question
Title: Advice on setting up a real-time audio equaliser
First time Arduino user here.

We have a microphone set-up which feeds back loudly on particular frequencies and need an equalizer to (preferably automatically) detect spikes in particular frequency bands and attenuate them before sending them on to the speakers. The dB level that has been cut from that frequency channel would then be displayed on an LED matrix such as this one:

Does the Arduino have the processing capabilities to keep up with the audio without noticeable lag? As the LEDs will only be a visual indication of the affect the attenuation is having on the frequencies, it is not particularly important that these be fast. Unfortunately, as the audio stream will be vocals, even a slight delay will render the thing useless. What delay might I expect with a single mono channel going through the arduino?

I expect that I will eventually have to revert to the less-interesting project of an RTA which takes a split of the audio sends to the speakers and simply displays the frequency band intensities rather than altering them.

I'd appreciate any thoughts.

# Answer
Somewhat possible if you accept that the Arduino won't be doing most of the work:

* Yes, the Arduino can sample audio and perform FFT on it, though not fast and not at high frequencies
* Yes, the Arduino can decide what to do depending on the power of different buckets
* Yes, the Arduino can display the results
* No, the Arduino cannot do realtime audio filtering.

If you accept that the filtering will have to be done with a bank of analogue band-cut filters that the Arduino turns on and off as needed then it may be possible.

The Arduino Due might be a more suitable candidate since it will be able to sample and do the FFT much faster so you'll be able to respond to the peaks much quicker, and the displaying won't get in the way so much, but actively filtering inside the chip really requires a DSP.
> 1 votes

---
Tags: led, audio, signal-processing
---


# Question
Title: How to blink a series of LED alternately only one at a time
I am very much new to Arduino. I recently bought an adruino uno. i can blink an LED alternately. Such as, 1st blink red, then blink green, then blue like that. once only one LED should blink.

I have provided the code blinking an LED. How to modify this to blink multiple LED one after another.

```
void setup() {

  pinMode(13, OUTPUT);

}

void loop() {

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

```

# Answer
You could always copy and paste:

```
void setup() {

  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);

}

void loop() {

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

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

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

```

---

A bit better would be to learn about functions:

```
void setup() {

  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);

}

void blink (const byte which)
  {
  digitalWrite(which, HIGH);
  delay(1000);
  digitalWrite(which, LOW);
  delay(1000);
  }  // end of blink

void loop() {
  blink (11);
  blink (12);
  blink (13);
}

```

---

And you could learn about loops:

```
void setup() {
  for (int i = 11; i <= 13; i++)
    pinMode(i, OUTPUT);
}

void blink (const byte which)
  {
  digitalWrite(which, HIGH);
  delay(1000);
  digitalWrite(which, LOW);
  delay(1000);
  }  // end of blink

void loop() {
  for (int i = 11; i <= 13; i++)
     blink (i);
}

```

---

There is a whole world of stuff to learn. Enjoy the process!
> 3 votes

# Answer
Have you considered connecting another LED and turning one on and the other off sequentially?

```
void setup() {

  pinMode(13, OUTPUT);
  pinmode(NewLEDPin, OUTPUT);

}

void loop() {
  digitalWrite(NewLEDPin,LOW);
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(NewLEDPin,HIGH);
  digitalWrite(13, LOW);
  delay(1000);
}

```
> 0 votes

---
Tags: arduino-uno, programming, led, c++, digital
---


title: Using for loop to set pinMode

text:
# Question
Title: Using for loop to set pinMode
I notice problems with my output pins when I use this method of setting their `pinMode`:

```
int allOutputPins[] = {3, 4, 9, 10, 5, A3, 11, 12, 7, 8, A1, A2};

for(int a = 0; a < sizeof(allOutputPins); a++){
   pinMode(allOutputPins[a], OUTPUT);
  }//end for

```

Am I doing something wrong?

# Answer
> 2 votes
Re “Am I doing something wrong?”, yes :)

The `sizeof(allOutputPins)` expression returns the size of `allOutputPins[]` in terms of bytes, so is 24 because the array contains 12 two-byte integers. The loop's last 12 `pinMode()` calls will be garbage.

Among other ways of fixing the problem, you could change the expression to `sizeof(allOutputPins)/sizeof(int)` \[which has the same value, 12, as `(sizeof allOutputPins)/sizeof(int)`; eg see the syntax entries for the sizeof operator at cppreference.com\] or you could change the base type of the array to `byte` or `uint8_t`.

---
Tags: code-optimization
---


# Question
Title: Inheritance: error in calling the constructor of the base class?
I want to write a library for the RGBDigit shield (http://rgbdigit.com/), which essentially is an Adafruit Neopixel strip, packed as a 7 segment display. The shield also has a DS3231 clock and an IR receiver.

So my plan was to make a class *RGBDigit*, which inherits from the *Adafruit\_NeoPixel* class and add private objects *DS3231* and *IRrecv*.

This is my RGBDigit.h:

```
#ifndef RGBDigit_h
#define RGBDigit_h

#include <Arduino.h>
#include "Wire.h"
#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"

class RGBDigit : public Adafruit_NeoPixel {
    public:
        RGBDigit(int nDigits);
        ~RGBDigit();
    private:
        int _nDigits;
        DS3231 _clock;
        IRrecv* _ir;
};

#endif

```

This is RGBDigit.cpp:

```
#include "RGBDigit.h"

RGBDigit::RGBDigit(int nDigits)
    : Adafruit_NeoPixel(8 * nDigits, 12, NEO_GRB + NEO_KHZ800),
    _nDigits(nDigits)
{
    _ir = new IRrecv(10);
    _ir->enableIRIn(); // Start the receiver
    Adafruit_NeoPixel::begin();
}

RGBDigit::~RGBDigit()
{
    delete _ir;
}

```

And this is my Arduino sketch:

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

RGBDigit display = RGBDigit(4);

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

}

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

}

```

I get al lot of "undefined reference" errors:

```
RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::RGBDigit(int)':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `Adafruit_NeoPixel::Adafruit_NeoPixel(unsigned int, unsigned char, unsigned char)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `DS3231::DS3231()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:25: undefined reference to `IRrecv::IRrecv(int)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:26: undefined reference to `IRrecv::enableIRIn()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:27: undefined reference to `Adafruit_NeoPixel::begin()'
RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::~RGBDigit()':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:30: undefined reference to `Adafruit_NeoPixel::~Adafruit_NeoPixel()'
collect2: error: ld returned 1 exit status

```

But I don' t understand why. What am I doing wrong?

# Answer
> 0 votes
```
#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"

```

What you're doing there is telling the *compiler* where, relative to where it's performing the compiling (or one of its include directories), the header files you list are.

What you're *not* doing is telling the *IDE* where the CPP files are to compile and link with your sketch.

When including *anything* external to the sketch folder that is *more* than *just a header file* you *must* treat it as an Arduino library - that is, place it in one of the standard library folders and name it properly (libraries should be named `LibraryName/LibraryName.h`).

Then you include the libraries properly:

```
#include <Adafruit_NeoPixel.h>
#include <IRremote.h>
#include <DS3231.h>

```

You must do that in *both* your sketch *and* your custom library. That way the IDE knows where to look for the files to compile - the compiler doesn't understand the concept of an Arduino library (and thus the CPP files associated with a header file) - that is purely down to the IDE gathering the data by examining your sketch and locating the right files to then pass to the compiler.

---
Tags: class, rgb-led, neopixel
---


title: error: redefinition of ' '

text:
# Question
Title: error: redefinition of ' '
When I am trying to compile the following code,

```
int delayTime = 1;
int charBreak = 2.1;
#include <MemoryFree.h>

int rled1 = 1;
int rled2 = 2;
int rled3 = 3;
int rled4 = 4;
int rled5 = 5;
int gled1 = 6;
int gled2 = 7;
int gled3 = 8;
int gled4 = 9;
int gled5 = 10;
int bled1 = 11;
int bled2 = 12;
int bled3 = 13;
int bled4 = 14;
int bled5 = 15;

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

int ra[] = {4,288,18464,288,4};
int ga[] = {2,144,9232,144,2};
int ba[] = {1,72,4616,72,2};
int rb[] = {18724,16644,16644,2080,0};
int gb[] = {9362,8322,8322,1040,0};
int bb[] = {4681,4161,4161,520,0};
int rc[] = {2336,16388,16388,2080,0};
int gc[] = {1168,8194,8194,1040,0};
int bc[] = {584,4097,4097,520,0};
int rd[] = {18724,16388,16388,2336,0};
int gd[] = {9362,8194,8194,1168,0};
int bd[] = {4681,4097,4097,584,0};
int re[] = {18724,16644,16644,16388,0};
int ge[] = {9362,8322,8322,8194,0};
int be[] = {4681,4161,4161,4097,0};
int rf[] = {18724,16640,16640,16384,0};
int gf[] = {9362,8320,8320,8192,0};
int bf[] = {4681,4160,4160,4096,0};
int rg[] = {2336,16388,16420,16416,2084};
int gg[] = {1168,8194,8210,8208,1042};
int bg[] = {584,4097,4105,4104,521};
int rh[] = {18724,256,256,256,18724};
int gh[] = {9362,128,128,128,9362};
int bh[] = {4681,64,64,64,4681};
int ri[] = {0,16388,18724,16388,0};
int gi[] = {0,8194,9362,8194,0};
int bi[] = {0,4097,4681,4097,0};
int rj[] = {32,4,16388,18720,16384};
int gj[] = {16,2,8194,9360,8192};
int bj[] = {8,1,4097,4680,4096};
int rk[] = {18724,256,2080,16388,0};
int gk[] = {9362,128,1040,8194,0};
int bk[] = {4681,64,520,4097,0};
int rl[] = {18724,4,4,4,0};
int gm[] = {9362,2,2,2,0};
int bm[] = {4681,1,1,1,0};
int rm[] = {18724,2304,36,2304,18724};
int gm[] = {9362,1152,18,1152,9362};
int bm[] = {4681,576,9,576,4681};
int rn[] = {18724,2304,36,18724,0};
int gn[] = {9362,1152,18,9362,0};
int bn[] = {4681,576,9,4681,0};
int ro[] = {2336,16388,16388,2336,0};
int go[] = {1168,8194,8194,1168,0};
int bo[] = {584,4097,4097,584,0};
int rp[] = {18724,16640,16640,2048,0};
int gp[] = {9362,8320,8320,1024,0};
int bp[] = {4681,4160,4160,512,0};
int rq[] = {2336,16388,16420,2336,36};
int gq[] = {1168,8194,8210,1168,18};
int bq[] = {584,4097,4105,584,9};
int rr[] = {18724,16640,16672,2052,0};
int gr[] = {9362,8320,8336,1026,0};
int br[] = {4681,4160,4168,513,0};
int rs[] = {2048,16644,16644,32,0};
int gs[] = {1024,8322,8322,16,0};
int bs[] = {512,4161,4161,8,0};
int rt[] = {16384,16384,18724,16384,16384};
int gt[] = {8192,8192,9362,8192,8192};
int bt[] = {4096,4096,4681,4096,4096};
int ru[] = {18720,4,4,18720,0};
int gu[] = {9360,2,2,9360,0};
int bu[] = {4680,1,1,4680,0};
int rv[] = {18432,288,4,288,18432};
int gv[] = {9216,144,2,144,9216};
int bv[] = {4608,72,1,72,4608};
int rw[] = {18688,36,2304,36,18688};
int gw[] = {9344,18,1152,18,9344};
int bw[] = {4672,9,576,9,4672};
int rx[] = {16388,2080,256,2080,16388};
int gx[] = {8194,1040,128,1040,8194};
int bx[] = {4097,520,64,520,4097};
int ry[] = {16388,2080,256,2048,16384};
int gy[] = {8194,1040,128,1024,8192};
int by[] = {4097,520,64,512,4096};
int rz[] = {16420,16644,16644,18436,0};
int gz[] = {8210,8322,8322,9218,0};
int bz[] = {4105,4161,4161,4609,0};
int reos[] = {0,4,0,0,0};
int geos[] = {0,2,0,0,0};
int beos[] = {0,1,0,0,0};
int rque[] = {2048,16420,16640,2048,0};
int gque[] = {1024,8210,8320,1024,0};
int bque[] = {512,4105,4160,512,0};
int rexcl[] = {0,18692,0,0,0};
int gexcl[] = {0,9346,0,0,0};
int bexcl[] = {0,4673,0,0,0};

void displayLine(int line)
{
  int myline; myline = line;
  if (myline>=16384) {digitalWrite(rled1, HIGH); myline-=16384;} else {digitalWrite(rled1, LOW);}
  if (myline>=8192) {digitalWrite(gled1, HIGH); myline-=8192;} else {digitalWrite(gled1, LOW);}
  if (myline>=4096) {digitalWrite(bled1, HIGH); myline-=4096;} else {digitalWrite(bled1, LOW);}
  if (myline>=2048) {digitalWrite(rled2, HIGH); myline-=2048;} else {digitalWrite(rled2, LOW);}
  if (myline>=1024) {digitalWrite(gled2, HIGH); myline-=1024;} else {digitalWrite(gled2, LOW);}
  if (myline>=512) {digitalWrite(bled2, HIGH); myline-=512;} else {digitalWrite(bled2, LOW);}
  if (myline>=256) {digitalWrite(rled3, HIGH); myline-=256;} else {digitalWrite(rled3, LOW);}
  if (myline>=128) {digitalWrite(gled3, HIGH); myline-=128;} else {digitalWrite(gled3, LOW);}
  if (myline>=64) {digitalWrite(bled3, HIGH); myline-=64;} else {digitalWrite(bled3, LOW);}
  if (myline>=32) {digitalWrite(rled4, HIGH); myline-=32;} else {digitalWrite(rled4, LOW);}
  if (myline>=16) {digitalWrite(gled4, HIGH); myline-=16;} else {digitalWrite(gled4, LOW);}
  if (myline>=8) {digitalWrite(bled4, HIGH); myline-=8;} else {digitalWrite(bled4, LOW);}
  if (myline>=4) {digitalWrite(rled5, HIGH); myline-=4;} else {digitalWrite(rled5, LOW);}
  if (myline>=2) {digitalWrite(gled5, HIGH); myline-=2;} else {digitalWrite(gled5, LOW);}
  if (myline>=1) {digitalWrite(bled5, HIGH); myline-=1;} else {digitalWrite(bled5, LOW);}

}

void displayChar(char c)
{
  if (c == 'ra'){for (int i = 0; i <5; i++){displayLine(ra[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rb'){for (int i = 0; i <5; i++){displayLine(rb[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rc'){for (int i = 0; i <5; i++){displayLine(rc2[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rd'){for (int i = 0; i <5; i++){displayLine(rd[i]);delay(delayTime);}displayLine(0);}
  if (c == 're'){for (int i = 0; i <5; i++){displayLine(re[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rf'){for (int i = 0; i <5; i++){displayLine(rf[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rg'){for (int i = 0; i <5; i++){displayLine(rg[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rh'){for (int i = 0; i <5; i++){displayLine(rh[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ri'){for (int it = 0; it <5; it++){displayLine(ri[it]);delay(delayTime);}displayLine(0);}
  if (c == 'rj'){for (int i = 0; i <5; i++){displayLine(rj[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rk'){for (int i = 0; i <5; i++){displayLine(rk[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rl'){for (int i = 0; i <5; i++){displayLine(rl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rm'){for (int i = 0; i <5; i++){displayLine(rm[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rn'){for (int i = 0; i <5; i++){displayLine(rn[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ro'){for (int i = 0; i <5; i++){displayLine(ro[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rp'){for (int i = 0; i <5; i++){displayLine(rp[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rq'){for (int i = 0; i <5; i++){displayLine(rq[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rr'){for (int i = 0; i <5; i++){displayLine(rr[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rs'){for (int i = 0; i <5; i++){displayLine(rs[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rt'){for (int i = 0; i <5; i++){displayLine(rt[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ru'){for (int i = 0; i <5; i++){displayLine(ru[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rv'){for (int i = 0; i <5; i++){displayLine(rv[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rw'){for (int i = 0; i <5; i++){displayLine(rw[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rx'){for (int i = 0; i <5; i++){displayLine(rx[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ry'){for (int i = 0; i <5; i++){displayLine(ry[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rz'){for (int i = 0; i <5; i++){displayLine(rz[i]);delay(delayTime);}displayLine(0);}
  if (c == 'r!'){for (int i = 0; i <5; i++){displayLine(rexcl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'r?'){for (int i = 0; i <5; i++){displayLine(rques[i]);delay(delayTime);}displayLine(0);}
  if (c == 'r.'){for (int i = 0; i <5; i++){displayLine(reos[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ga'){for (int i = 0; i <5; i++){displayLine(ga[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gb'){for (int i = 0; i <5; i++){displayLine(gb[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gc'){for (int i = 0; i <5; i++){displayLine(gc2[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gd'){for (int i = 0; i <5; i++){displayLine(gd[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ge'){for (int i = 0; i <5; i++){displayLine(ge[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gf'){for (int i = 0; i <5; i++){displayLine(gf[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gg'){for (int i = 0; i <5; i++){displayLine(gg[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gh'){for (int i = 0; i <5; i++){displayLine(gh[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gi'){for (int it = 0; it <5; it++){displayLine(gi[it]);delay(delayTime);}displayLine(0);}
  if (c == 'gj'){for (int i = 0; i <5; i++){displayLine(gj[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gk'){for (int i = 0; i <5; i++){displayLine(gk[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gl'){for (int i = 0; i <5; i++){displayLine(gl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gm'){for (int i = 0; i <5; i++){displayLine(gm[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gn'){for (int i = 0; i <5; i++){displayLine(gn[i]);delay(delayTime);}displayLine(0);}
  if (c == 'go'){for (int i = 0; i <5; i++){displayLine(go[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gp'){for (int i = 0; i <5; i++){displayLine(gp[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gq'){for (int i = 0; i <5; i++){displayLine(gq[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gr'){for (int i = 0; i <5; i++){displayLine(gr[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gs'){for (int i = 0; i <5; i++){displayLine(gs[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gt'){for (int i = 0; i <5; i++){displayLine(gt[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gu'){for (int i = 0; i <5; i++){displayLine(gu[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gv'){for (int i = 0; i <5; i++){displayLine(gv[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gw'){for (int i = 0; i <5; i++){displayLine(gw[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gx'){for (int i = 0; i <5; i++){displayLine(gx[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gy'){for (int i = 0; i <5; i++){displayLine(gy[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gz'){for (int i = 0; i <5; i++){displayLine(gz[i]);delay(delayTime);}displayLine(0);}
  if (c == 'g!'){for (int i = 0; i <5; i++){displayLine(gexcl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'g?'){for (int i = 0; i <5; i++){displayLine(gques[i]);delay(delayTime);}displayLine(0);}
  if (c == 'g.'){for (int i = 0; i <5; i++){displayLine(geos[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ba'){for (int i = 0; i <5; i++){displayLine(ba[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bb'){for (int i = 0; i <5; i++){displayLine(bb[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bc'){for (int i = 0; i <5; i++){displayLine(bc2[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bd'){for (int i = 0; i <5; i++){displayLine(bd[i]);delay(delayTime);}displayLine(0);}
  if (c == 'be'){for (int i = 0; i <5; i++){displayLine(be[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bf'){for (int i = 0; i <5; i++){displayLine(bf[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bg'){for (int i = 0; i <5; i++){displayLine(bg[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bh'){for (int i = 0; i <5; i++){displayLine(bh[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bi'){for (int it = 0; it <5; it++){displayLine(bi[it]);delay(delayTime);}displayLine(0);}
  if (c == 'bj'){for (int i = 0; i <5; i++){displayLine(bj[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bk'){for (int i = 0; i <5; i++){displayLine(bk[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bl'){for (int i = 0; i <5; i++){displayLine(bl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bm'){for (int i = 0; i <5; i++){displayLine(bm[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bn'){for (int i = 0; i <5; i++){displayLine(bn[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bo'){for (int i = 0; i <5; i++){displayLine(bo[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bp'){for (int i = 0; i <5; i++){displayLine(bp[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bq'){for (int i = 0; i <5; i++){displayLine(bq[i]);delay(delayTime);}displayLine(0);}
  if (c == 'br'){for (int i = 0; i <5; i++){displayLine(br[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bs'){for (int i = 0; i <5; i++){displayLine(bs[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bt'){for (int i = 0; i <5; i++){displayLine(bt[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bu'){for (int i = 0; i <5; i++){displayLine(bu[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bv'){for (int i = 0; i <5; i++){displayLine(bv[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bw'){for (int i = 0; i <5; i++){displayLine(bw[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bx'){for (int i = 0; i <5; i++){displayLine(bx[i]);delay(delayTime);}displayLine(0);}
  if (c == 'by'){for (int i = 0; i <5; i++){displayLine(by[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bz'){for (int i = 0; i <5; i++){displayLine(bz[i]);delay(delayTime);}displayLine(0);}
  if (c == 'b!'){for (int i = 0; i <5; i++){displayLine(bexcl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'b?'){for (int i = 0; i <5; i++){displayLine(bques[i]);delay(delayTime);}displayLine(0);}
  if (c == 'b.'){for (int i = 0; i <5; i++){displayLine(beos[i]);delay(delayTime);}displayLine(0);}
  delay(charBreak);
}

void displayString(char* s)
{
  for (int i = 0; i<=strlen(s); i++)
  {
  displayChar(s[i]);
  }
}

void loop()
{
  displayString("sunil");
  Serial.print("freeMemory()=");
    Serial.println(freeMemory());
}

```

I am getting the following error.

```
sketch_jul17b:63: error: redefinition of 'int gm []'
sketch_jul17b:60: error: 'int gm [5]' previously defined here
sketch_jul17b:64: error: redefinition of 'int bm []'
sketch_jul17b:61: error: 'int bm [5]' previously defined here
sketch_jul17b.ino: In function 'void displayChar(char)':
sketch_jul17b:139: error: 'rc2' was not declared in this scope
sketch_jul17b:164: error: 'rques' was not declared in this scope
sketch_jul17b:168: error: 'gc2' was not declared in this scope
sketch_jul17b:177: error: 'gl' was not declared in this scope
sketch_jul17b:193: error: 'gques' was not declared in this scope
sketch_jul17b:197: error: 'bc2' was not declared in this scope
sketch_jul17b:206: error: 'bl' was not declared in this scope
sketch_jul17b:222: error: 'bques' was not declared in this scope

```

I don't know why this error is occurring.

# Answer
> 2 votes
You have a combination of trying to define the same name twice, for example "gm"

```
int gm[] = {9362,2,2,2,0};
int bm[] = {4681,1,1,1,0};
int rm[] = {18724,2304,36,2304,18724};
int gm[] = {9362,1152,18,1152,9362};

```

And using others such "rc2" which you have never defined.

Your code won't compile and work until you make it self-consistent.

# Answer
> 8 votes
This can also happen if you have saved a version of the code (for example duplicate file for backup) within the current sketch folder.

# Answer
> 3 votes
The first errors happen because you are trying to define a variable with the same name in the same scope twice, like here:

```
int gm[] = {9362,2,2,2,0};
int bm[] = {4681,1,1,1,0};
int rm[] = {18724,2304,36,2304,18724};
int gm[] = {9362,1152,18,1152,9362};

```

gm is defined two times which is not allowed.

The other error happens because you are referencing variables you never declared like here:

```
if (c == 'rc'){for (int i = 0; i <5; i++){displayLine(rc2[i]);delay(delayTime);}displayLine(0);}

```

rc2 isn't defined anywhere.

---

Besides there are some other issues with your code:

```
int charBreak = 2.1;

```

`int` types can only contain whole numbers, so `charBreak` will be set to two and not two point one. You probably wan't to use a `float`.

In `void displayChar(char c)` you try to compare a char with two chars:

```
if (c == 'ra')

```

That won't work. The char type can only contain a single character, so the comparison will always be false. Two chars like this `'ab'` in single quotes are interpreted as 16 bit number. Two chars in double quotes are interpreted as a null-terminated string:

```
char cstring1[] = "ab";
char cstring2[] = {'a', 'b', '\0'};

if (strcmp(cstring1, cstring2) == 0)
  // The two strings are identical

```

`strcmp` returns 0 on match-.

---
Tags: arduino-uno
---


# Question
Title: Serial communication using Arduino and TeraTerm
I wrote a simple serial program using Arduino Mega 2560, it is connected to COMPORT 10. Here is the program I Wrote,

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

void loop()
{
  Serial.println("HELLO");
  delay(1000); //Send every one second
}

```

Now, I tried to send this message "Hello" to TeraTerm (COMPORT 1, for this I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0. Doing this I do receive message in my TeraTerm screen but the received message doesn't make sense, its receiving garbage. Its not the case of mismatch of baud rate I am using 9600 on both the side.

However I do receive message "HELLO" in the serial monitor. Is there something I am doing wrong that I am not receiving message on TeraTerm.

# Answer
> ... I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0.

But neither device knows what voltage they are. You need to connect ground as well so that they have a common reference.
> 1 votes

# Answer
Hello everyone thanks for your reply,

I found the problem :D and was also able to solve it.

I was directly connecting the Tx and Rx pin of Arduino to the Rx and Tx pin of DB9 connector on PC. Since, DB9 on the PC operates on higher voltage than the operating voltage of the Arduino which is 5V. This mis-match of the voltage was causing the problem, So in order to solve this i added a level shifter in between (MAX232) and now it works perfect.

Thanks everyone for replying.
> 0 votes

---
Tags: serial, communication
---


# Question
Title: What are some fun things you can do using the ICSP header?
I bought 10 Arduino Nanos for a project, each with all of their headers soldered in place. Each was going to go into a tiny space, so I found myself needing do desolder the ICSP headers.

This led to a bit of a moral conundrum. What would I lose by removing these useful looking headers. They cover quite a lot of space on the nano, so they must be important right? Am I going to regret removing these things when I finally realize how useful they are (I thought to myself.)

In the end, I did remove the ICSP headers, but the event got my thoughts going. What is this header all about? Why is it there? What can I do with it? I began to search for things that I could do with the ICSP header, but engaging results were not forthcoming ( except for this project: https://www.arduino.cc/en/Hacking/ParallelProgrammer )

Anyway, I was more interesting in things that flash, move, jump, sing, and such, so are there any interesting things that can be done with the ICSP header?

# Answer
1. You can use *every single last byte* of flash on the device.

Since you're performing low-level programming of the device you get the entire chip to play on, without having to worry about bootloaders and such.
2. You can debug (breakpoint, single-step, watch, disassemble, etc.) the code on the chip using software on your computer.

Admittedly the devices you'd need in order to do so are more expensive than a simple ISP programmer and it only works with specific pieces of software, but it can be done.
> 2 votes

# Answer
One interesting thing I just came up with: you could use this header to attach a simple control panel for your Arduino.

Imbed the Arduino in any place/box/machine you like. Then use a cable with a 6 pin connector to connect the header to a small control panel. The panel could have 3 buttons or LEDs, a reset button and a power plug.
> 1 votes

---
Tags: icsp
---


# Question
Title: AVRdude + Arduino leonardo: can't flash over bootloader, not in sync: resp=0x3f
I would like to program an arduino leonardo board with atmega32u4 on win8.1 x64. I have the latest AVRdude. I installed the necessary drivers, after reset it can be enter programming mode, and I can program with **arduino studio**. But now, the avrude gives this:

```
    C:\>avrdude -carduino -P COM5 -n -p m32u4 -b19200 -v

avrdude: Version 6.1-svn-20131205, compiled on Dec  5 2013 at 17:34:22
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "c:\GNU_GCC_ARM\bin\avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x3f

avrdude done.  Thank you.

```

I tried also with 57600 baud. Any idea? Thanks.

# Answer
You're specifying the wrong bootloader protocol via -carduino. The Arduino bootloader is for boards using the Diecimila bootloader. The Leonardo uses the "AVR109" bootloader - named after the Atmel Application Note which describes its protocol.

Try this command on for size:

```
avrdude -cavr109 -P COM5 -n -p m32u4 -b57600 -v

```

Don't forget to press the reset button (or open and close COM5 at 1200 baud) first to run the bootloader.
> 1 votes

---
Tags: avrdude
---


# Question
Title: Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)
I’m sorry if I sound ignorant and naive, but I’m brand new to Arduino; very keen, but know very little.

I started with a Sainsmart Arduino Uno clone board. I downloaded the software, which opened OK (or at least seemed to), but the Serial Monitor kept telling me that there was a communication error, and a yellow light kept flashing on the Sainsmart board.

I got hold of a genuine Arduino (from Jameco), uninstalled everything Arduino, and started again from scratch.

Now I get the message:

```
Arduino: 1.6.5 (Mac OS X), Board: "Arduino/Genuino Uno"
Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)
  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

```

And after enabling the verbose output, got:

```
Arduino: 1.6.5 (Mac OS X), Board: "Arduino/Genuino Uno"
Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)

```

Tried again, and:

```
Arduino: 1.6.5 (Mac OS X), Board: "Arduino/Genuino Uno"
Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)

```

I’m using a MacBook Pro, using Yosemite 10.10.5.

# Answer
> 3 votes
You are not selecting the correct port to upload to - hence the strange message about the Bluetooth modem. Start by unplugging your Uno and running Arduino. Select Tools -\> Port from the menu bar. You should see a list of options. Now plug in your Uno and do the same again. You should see an extra port listed now - this will be the Uno. Select it. You will need to check this every time you connect a board.

Also, before you click Upload, make sure you have Arduino Uno selected under Tools -\> Board in the menu bar.

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


title: Arduino Serial Monitor

text:
# Question
Title: Arduino Serial Monitor
I am currently trying to see the result of a query to a thingspeak field. This works great when I just use a empty sketch and type the commands manually, but using the following sketch I cannot see the value of +IDP,0,1:1 This means, at field 1, the value 1 is stored. If 0 was stored, it would be +IDP,0,1:0 How it is possible to "ask" if "+IDP,0,1:0" exists at the serial message from the ESP8266? Serial.find does not work....

Here my sketch:

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

SoftwareSerial monitor(2,3); //rx tx
#define SSID "WLAN-0E0265"
#define PASS "2738564673200634"
int ledPin = 13;
String c;
void setup() {
  Serial.begin(9600);
  monitor.begin(9600);
  monitor.println("AT");
  delay(1000);
  monitor.println("AT+CIPMUX=1");
  delay(1000);
  monitor.println("AT+CWJAP=\"WLAN-0E0265\",\"2738564673200634\"");
  delay(5000);
  if(monitor.find("OK"))
    Serial.println("JAP worked");

  monitor.println("AT+CIPSTART=0,\"TCP\",\"api.thingspeak.com\",80");
  delay(2000);
  if(monitor.find("OK"))
    Serial.println("CIPSTART worked");
  monitor.println("AT+CIPSEND=0,110");
  delay(2000);
  if(monitor.find(">"))
    Serial.println("CIPSEND worked");
  monitor.print("GET https://api.thingspeak.com/channels/54209/fields/1/last \r\n");
  delay(10000);
  monitor.println("GET https://api.thingspeak.com/channels/54209/fields/1/last");
  delay(2000);
  String readString;
  ledPin = 13;
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//SEARCH FOR THE :0 or :1                           <-- Here is the problem, rest works fine
  if(Serial.find(":0")){
 //turn pin off
}
  if(Serial.find(":1")){
 //turn pin on
}

}

void loop(){

}

```

# Answer
The problem is that you can't use serial's `find` function to look for one thing *or* another. It is a greedy function and it will consume everything coming in to the serial port until it finds what it's looking for or until it times out. That includes the `:1` if you are using `find` to look for the `:0` at the time.

Instead you either need to receive the whole string into memory and examine the string to see what it contains, or you need to manually process the data as it comes in character by character to decide what there is.
> 1 votes

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


# Question
Title: Measuring power consumption on Arduino off of DC supply
I am working on a project involving the Uno, and I would like to benchmark the power requirements of Arduino. I am using the external 9V supply option.

Specifically, the Uno will be in to states,`power-intensive` and `power-save`. In the first mode, I am doing some heavy processing tasks (RF and some sensors are the only external loads), and the Arduino typically runs `loop()` without any delays. In the second mode, `loop()` is execued about every 10-40 seconds.

I am interested in benchmarking how much power is consumed in both states (I need this to estimate the size of the battery required for the 9V supply).

Obviously, googling yielded me solutions that involved measuring current using chips in series with the supply (I probably can pull this off with a multimeter). What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

# Answer
> What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

The Uno cannot measure its own power consumption. Indeed, a Uno which has a voltage regulator, power LED, and USB interface chip is not your ideal solution for low-power applications.

See Power saving techniques for microprocessors
> 1 votes

---
Tags: arduino-uno, power
---


title: Arduino microphone

text:
# Question
Title: Arduino microphone
I have an arduino schematic from here

http://www.arduino-hacks.com/arduino-vu-meter-lm386electret-microphone-condenser/

I have a problem, the output of the circuit (the pin which is going to connect to the analog pin of the Arduino), from what I have measured has 4.5 V (I think it is a bit high). If I print on the serial it gives me something like 827, 826. However when I clap my hands near the microphone or put music on, the data that I get doesn't change a lot (like 1 -2 units). Should I worry about the schematic or about my microphone?

EDIT: After I rebuilt the circuit and when playing a song at a medium volume, I get values like this: 419-670. I think it is working, though I would like more opinions about these values (the output voltage is now around 3.20 V).

# Answer
The schematic seems to have both inputs of the opamp at 0V (the one connected to the microphone would actually swing a small amount ±). The opamp also seems to be running open loop, with no feedback and would have a very high gain.

This is poor circuit design, ideally the inputs should be biassed at Vcc/2. At best the output would be severely distorted.

I suggest you search for a more suitable circuit.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Wifi.status() always returns WL_NO_SHIELD
I've an Arduino Mega 2560 R3 and recently bought a Wifi Shield CC3000 from ebay http://www.ebay.de/itm/201405512301 They write that the firmware has the version ServicePack 1.11.1. The WiFi shield is connected to the Arduino and green status light is on.

I try to run this example code:

```
void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
}

// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
  Serial.println("WiFi shield not present");
    // don't continue:
  while(true);
}
...

```

It seems that Wifi.status() always returns WL\_NO\_SHIELD. What can I do?

Thanks for help.

# Answer
The problem is solved now.

* I imported the Adafruit\_CC3000 library which can be downloaded here: https://github.com/adafruit/Adafruit\_CC3000\_Library
* I run the example but the output was chinese nonsense
* Instead of

Serial.begin(115200);

I used

Serial.begin(9600);

then the examples run without any problem

Thanks @Majenko. His question was very helpful.
> 1 votes

---
Tags: arduino-mega, wifi
---


title: Drive 12V Piezo Buzzer (Arduino)

text:
# Question
Title: Drive 12V Piezo Buzzer (Arduino)
I want to drive this 12V piezo buzzer: http://www.conrad.com/ce/en/product/130256/Kemo-L001-High-Freqeuncy-Piezo-Speaker-Component-12-24-V

This is the circuit I am using.

The Arduino is powered by a 12V DC adapter trough the DC IN jack.

I have tested the following code:

```
void setup() {
}

void loop() {
  int pinOut = 9;
  int freq = 10;
  int duration = 100;
  while(1)
  {
    for(int i=0; i<1000 ; i++)
    {
      tone(pinOut, freq*i, duration);
      delay(duration * 1);
      noTone(pinOut);
    }
  }
}

```

When run I can hear the tones changing but is really really low. I have measured the voltage between buzzer pins and it is 12V (as expected) so the MOSFET seems to be properly working.

This piezo buzzer should be louder (I have tested it with this 12V tone generator http://www.kemo-electronic.de/en/Car/Modules/M048N-Ultrasonic-Generator.php )

I am making any mistake? Thanks in advance!

# Answer
> 2 votes
The piezo element acts like a capacitor, not like a more-or-less resistive element as in a conventional speaker. You need to discharge the capacitor during the 'off' time or you just get a click and little sound after that. That's why your resistor helps. Push-pull would be much better, and an H-bridge would give you much more output (maybe too much for the speaker).

Also the IRZ44 is not specified to be driven from 5V (it's specified at 10V Vgs) so you may not get much current. Further, if you're trying to get 10's of kHz, you won't be able to drive the MOSFET gate that fast with a 1K resistor, in fact the Arduino may not be able to source enough current and you may have to use a gate driver.

If you can measure the capacitance and provide the frequency of interest, more specific recommendations would be possible. At 2kHz about 3K would be okay with a 10nF element, but that resistance would decrease with increasing resistance and with increasing capacitance, and at some point the power dissipation in the resistor will become excessive.

Edit: You can do something like the below with a 10nF/20kHz requirement:

simulate this circuit – Schematic created using CircuitLab

You could even duplicate the above circuit and add an inverter in series with one of the halves and get 24Vpp across the piezo, but you might want to use somewhat beefier transistors (Zetex perhaps).

# Answer
> 0 votes
The usable frequency range of the speaker is 2500 - 45000 Hz. In your script, you sweep from 10Hz to 10kHz which is a bit low. Try to change the start frequency to a higher value:

```
void setup() {
}

void loop() {
  int pinOut = 9;
  int freq = 2500;
  int duration = 100;
  while(1)
  {
    for(int i=0; i<1000 ; i++)
    {
      tone(pinOut, freq+(i*50));
      delay(duration);
      noTone(pinOut);
    }
  }
}

```

---
Tags: arduino-uno, piezo, buzzer
---


title: Newbie Question with 4 pin button

text:
# Question
Title: Newbie Question with 4 pin button
I suspect this is a very Naive question.
But the answer will teach me a lot.

Why does this circuit work when I connect the Digital Input (Digial Pin 2) to Pin 4 of the push button. But does not when I connect the push button to Pin 3. I missing something about how power flows when the button is pushed.

Ray K

# Answer
> 4 votes
Internally those little tactile switches look like this:

That means that the two pins on the same *long* side are connected together. So you can use, when you hold the switch vertically as in the image on the page you link to the two left-hand pins are linked together, and the two right-hand pins are linked together.

So you can use either both the top pins, both the bottom pins, or the top left and bottom right or the top right and bottom left.

Using either both left hand pins or both right hand pins will be as if you were sat on the button and it was permanently pressed.

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


# Question
Title: Problem with reading multiple potentiometer values on Arduino Uno
I'm working on an Arduino sketch that will read in values from two potentiometers. The code for this is below:

```
int lastPotentiometerOneValue = 0;
int lastPotentiometerTwoValue = 0;

void setup() {
  // initialize serial communication at 57600 bits per second:
  Serial.begin(57600);
}

void loop() {
  delay(10);
  readAndSendPotentiometerDataIfChanged();
}

void readAndSendPotentiometerDataIfChanged(void) {

  //Potentiometer One
  int newPotentiometerOneValue = analogRead(A0) / 10.2;
  if (newPotentiometerOneValue == lastPotentiometerOneValue) return;

  Serial.print("!pos1");
  Serial.print(newPotentiometerOneValue);
  Serial.print(";");
  lastPotentiometerOneValue = newPotentiometerOneValue;

  //Potentiometer Two
  int newPotentiometerTwoValue = analogRead(A1) / 10;
  if (newPotentiometerTwoValue == lastPotentiometerTwoValue) return;

  Serial.print("!pos2");
  Serial.print(newPotentiometerTwoValue);
  Serial.print(";");
  lastPotentiometerTwoValue = newPotentiometerTwoValue;
}

```

The schematic for my circuit is below (I've left out the code for reading the state of the push-button in my listing above, as that's in a separate method from the method that reads in the potentiometer data):

However, there seems to be a rather subtle error I'm experiencing. If I turn Potentiometer One, it will display the correct output in the serial monitor. If I turn Potentiometer Two, no value will be displayed. *However*, if I remove Potentiometer Two from the circuit board and turn Potentiometer One, then the serial monitor will display the Potentiometer Two as having the same data as Potentiometer Two.

I'm sure the problem is with my circuit, but I'm not quite sure what I'm doing wrong. Does anyone have some insight? Thank you!

# Answer
One problem is that if the value for pot1 has not changed, the value for pot2 will never be sent, even if it has changed, due to the early return when checking the value of pot1. You could fix this by changing to:

```
void readAndSendPotentiometerDataIfChanged(void) {

  //Potentiometer One
  int newPotentiometerOneValue = analogRead(A0) / 10.2;
  if (newPotentiometerOneValue != lastPotentiometerOneValue) {
      Serial.print("!pos1");
      Serial.print(newPotentiometerOneValue);
      Serial.print(";");
      lastPotentiometerOneValue = newPotentiometerOneValue;
  }

  //Potentiometer Two
  int newPotentiometerTwoValue = analogRead(A1) / 10.2;
  if (newPotentiometerTwoValue != lastPotentiometerTwoValue) {
      Serial.print("!pos2");
      Serial.print(newPotentiometerTwoValue);
      Serial.print(";");
      lastPotentiometerTwoValue = newPotentiometerTwoValue;
  }
}

```
> 2 votes

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


title: Arduino GPSlim 236

text:
# Question
Title: Arduino GPSlim 236
I'm looking to connect an old GPSlim236 device to my Arduino via serial comms. I have seen references online on how to connect the device but in the data sheet it says TTL level between 3V - 5V. Does this mean that the GPS can automatically switch between logic level 5V -3V when needed?

Here is the link to data sheet for the GPS - http://www.holux.com/JCore/UploadFile/3205400.pdf

# Answer
The datasheet says:

> Power Supply
>
> External Voltage: 5VDC +/- 10%

So I take that to mean you supply 5V to it.

---

Later on it says:

> Transmit Data. From organizer to peripheral. (Voltage Level is 3.3V ~ 5.0V)

I presume that means that it will supply (or accept) 3.3V to 5V as a high level, and less than 3.3V as a low level. This is perfectly normal for an Arduino.

---

> Does this mean that the GPS can automatically switch between logic level 5v -3v when needed ?

No I would not read it like that. If you read the datasheet for the Arduino processor chips it states things like an output high is a range of voltages, similar to what this device is saying. A "high" is not necessarily 5V exactly, it might be 4.7V, for example. However the Arduino input pins are similarly designed to take a range of voltages.

---

> My confusion here is that the datasheet says 3-5v but what if I connect the device to a raspberry pi which (I think) only accepts 3v, would it still work?

Well, the datasheet says 5V +/- 10% for charging the internal battery. I'm not sure what your situation is if you are trying to run it from a Pi.
> 1 votes

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


title: Arduino programmers for hire?

text:
# Question
Title: Arduino programmers for hire?
How do I best connect with Arduino programmers who are willing to design small projects for some extra cash?

# Answer
> 1 votes
The Arduino Forum has a Gigs and Collaborations section where such questions are welcome.

---
Tags: programming
---


# Question
Title: Loop though array values at end of each for loop cycle
I'm using the NeoPixel Ring from Adafruit and trying to pulse though and array of colors. However, I'm having trouble with having the loop go to the next color at the end of each pulse (end of loop). Here is what I currently have:

```
uint32_t color[] = {red, green, blue,yellow,teal,magenta};

void pulseUp(uint8_t speed){
  int fadeAmount = 10; //how much to increase each loop
  int n = 0; //get first color
  for(int b = 100; b >= 10; b = b - fadeAmount) { //start pulse for loop
    for (int i = 0; i < strip.numPixels(); i++) { //select all pixels
      strip.setPixelColor(i, color[n]); //set color from our array
      }
    strip.setBrightness(b); //set brightness based on b
    strip.show(); // send the changes to the strip
    delay(speed); //wait before running again
    //if at the end of the loop (brightness is 10) change color
    if (b == 10){
      if( n > 6){ //if we are at last color in our loop start over
        n = 0;
      }
      else{
        n++; //auto increment color value
      }
    }
  }
}

```

I'm sure the problem is with the if statements but not sure how to fix it.

# Answer
> 1 votes
I can't quite make out what your `if` test is supposed to be doing, but don't you want a loop within a loop? Like this?

```
uint32_t color[] = {red, green, blue,yellow,teal,magenta};

void pulseUp(uint8_t speed)
  {
  const int fadeAmount = 10; //how much to increase each loop
  for (int currentColor = 0; currentColor < 6; currentColor++)
    {
    for (int i = 0; i < strip.numPixels(); i++)
      { //select all pixels
      strip.setPixelColor(i, color[currentColor]); //set color from our array
      }
    for(int brightness = 100; brightness >= 10; brightness -= fadeAmount)
      { //start pulse for loop
      strip.setBrightness(brightness); //set brightness based on brightness
      strip.show(); // send the changes to the strip
      delay(speed); //wait before running again
      }  // end of brightness loop
    }  // end of colour loop
  }  // end of pulseUp

```

---
Tags: neopixel
---


# Question
Title: Arduino Uno and Agilent ADNS-3080 not reading from SPI
I am trying to interface with a mouse sensor and am not able to get data back. datasheet link I have it still soldered to the original PCB but have cut the traces to pins 1-4,6,7 (NCS \[SS\], MISO, SCLK, MOSI, RESET, NPD \[power down {set to 3.3v}\])

PLEASE LET ME KNOW IF ANYTHING SEEMS WRONG HERE.

According to the Datasheet, by default the sensor is setup with the pull-up resistors enabled \[pg. 29\] which enables the open-drain, allowing me to directly connect NCS,MISO,SCLK,MOSI directly to the 5v microcontroller \[pg. 15\]. This also requires the SPI speed set to 500khz \[pg. 10\]. RESET is in a (10k)(10k+10k) resistor bridge.

SPI should be set to Mode3 as SCLK is normally high and data should be captured on the rising edge of the clock pulse \[pg. 16\]

Here is my code:

```
#include <SPI.h>
const int MOUSEVERSION = 0x00; //mouse version
const int CSmouse = 10;
const int mouseReset = 2;
char val;

void setup() {
  Serial.begin(9600);
  SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE3));
  pinMode(CSmouse, OUTPUT);
  pinMode(mouseReset, OUTPUT);
  digitalWrite(CSmouse, HIGH);
  //pull reset pin high for a half second to make sure mouse is ready to go after powering on [pg. 22]
  digitalWrite(mouseReset, HIGH);
  Serial.println("setup");
  delay(500); //half a second
  digitalWrite(mouseReset, LOW);
  Serial.println("end setup");
}

void loop() {
  Serial.println("Start loop");
  digitalWrite(CSmouse, LOW); //CS enable
  SPI.transfer(MOUSEVERSION); //0x00 = read register Product_ID, should reply 0x17
  delayMicroseconds(75);
  Serial.println(SPI.transfer(0)); //actually just gives 0
  delay(500);
}

```

# Answer
You have `SPI.beginTransaction` but no `SPI.begin()`.

`SPI.begin()` is needed to initialize the SPI hardware.

More details about SPI at SPI - Serial Peripheral Interface - for Arduino.
> 0 votes

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


title: Arduino reads bogus from serial

text:
# Question
Title: Arduino reads bogus from serial
Recently I've started playing around with an Arduino Uno (rev 3), and I've set up a communication bridge between the Arduino and my computer using Python. So I send a command in Python ("ping" for instance), which is then read and interpreted. I've had it working before, using the Python commands to control a motor, but today it became non-responsive. However, only if I boot the serial monitor from the Arduino IDE, it suddenly accepts my commands again. Further inspection reveals that the Arduino is probably reading empty or corrupted data, interpreting it as `ð`, `à` and `ÿ` and such.

Here is an excerpt of the Python code I'm using:

```
import sys, glob, serial, time, re

class interface:

     timeout = 2    # 10 second time-out

    def __init__(self):
        port = "/dev/ttyACM0"
        self.connect(port)
        pass

    def connect(self, port="/dev/ttyACM0"):
        global arduino
        arduino = serial.Serial(port, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0.1)  # Establishing connection
        time.sleep(3) # Allowing the connection to settle
        arduino.flush()
        print "Connection established..."

    def ping(self):
        arduino.flush()
        arduino.write("ping")
        msg = self.listen_arduino()
        print msg
        if msg == "ping_ok":
            print "pinged"
            return True
        return False

    def listen_arduino(self):
        timeout = self.timeout
        matcher = re.compile("\n")
        buff = ""
        t0 = time.time()
        buff += arduino.read(128)

        while (time.time() - t0) < timeout and (not matcher.search(buff)):
            buff += arduino.read(128)
        return buff.strip()

```

And here is the Arduino C code:

```
String readString;

void setup() {
    Serial.begin(115200); // use the same baud-rate as the python side
}

void loop() {
    readString = listen(); // listen for any commands
    if (readString.length() > 0) {

        Serial.println(readString); // print the command

        if(readString == "ping") {
          Serial.write("ping_ok");
        }
    }
}

String listen() {
    String readString;
    while (!Serial.available());
    while (Serial.available()) {
        delay(1); // Allow the buffer to fill
        if (Serial.available() > 0) {
            char c = Serial.read();
            readString += c;
        }
    }
    return readString;
}

```

I suspect there is something fishy with the connection I'm making on the Python side, as the Arduino IDE serial monitor works just fine. I hope anyone can spot the problem in this code, I'm willing to provide more details on request.

Thanks

# Answer
> 0 votes
I've discovered that there was another program trying to access the Arduino, interfering with the code above and causing corruption of the signal. After terminating the intrusive program, the code worked just fine.

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


# Question
Title: Function not successfully reading sensor registers
I'm trying to write a library for an accelerometer/magnetometer sensor. The sensor is a LSM303D chip (https://www.pololu.com/file/0J703/LSM303D.pdf).

I've written a function, `readRegister()` (below) that's supposed to get the data from the sensor. However, I put in many different registers into the function into the function, but it always returns the same number. That number changes every time I unplug my Arduino from my computer.

```
byte fp::readRegister(byte register_address, int numBytes) {
  Wire.requestFrom(register_address, numBytes);
  byte c;
  Serial.println(Wire.read());
  while (Wire.available()) {
    c = Wire.read();
  }
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

```

Here's an example of the problem output:

```
0x8 190 2
0x9 190 3
0xA 190 11

```

And here is something more like what I'd expect:

```
0x8 193 [time]
0x9 189 [time]
0xA 195 [time]

```

Here is the Git repo with the rest of the code: https://github.com/fpdotmonkey/fp\_accel

Thank you in advance for your help.

# Answer
```
  Wire.requestFrom(register_address, numBytes);
  byte c;
  Serial.println(Wire.read());
  while (Wire.available()) {
    c = Wire.read();
  }

```

This has a number of problems. For one thing your (I presume) debugging print consumes the data from Wire.read, so when you go to get it into c, you have already printed it. In other words, you are reading byte #1 and printing it, but using byte #2. This seems an odd thing to do.

Next, what is this doing?

```
  while (Wire.available()) {
    c = Wire.read();
  }

```

You are reading an indefinite number of bytes, and retaining the last one. Why?

Possible rework:

```
byte fp::readRegister(byte register_address, int numBytes) {
  Wire.requestFrom(register_address, numBytes);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

```

---

> Here is the Git repo with the rest of the code: https://github.com/fpdotmonkey/fp\_accel

From your linked code:

```
  byte xlm = readRegister(fp::OUT_X_L_M, 1);
  byte xhm = readRegister(fp::OUT_X_H_M, 1);
  byte ylm = readRegister(fp::OUT_Y_L_M, 1);
  byte yhm = readRegister(fp::OUT_Y_H_M, 1);
  byte zlm = readRegister(fp::OUT_Z_L_M, 1);
  byte zhm = readRegister(fp::OUT_Z_H_M, 1);

```

You have the wrong end of the stick here.

```
  Wire.requestFrom(register_address, numBytes);

```

You request from the **I2C address** \- that is the device address. The register is something else.

Judging by the datasheet you first have to send the register address, and then request the data. Something along the lines of:

```
byte fp::readRegister(byte register_address, int numBytes) {
  Wire.beginTransmission (DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.endTransmission (false);  // repeated start
  Wire.requestFrom(DEVICE_ADDRESS, 1);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

```

Similarly for writing to a register:

```
void fp::writeRegister(byte register_address, byte val) {
  Wire.beginTransmission(DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.write(val);
  Wire.endTransmission();
}

```

This is untested because I don't have the device here, but I know that what you had won't work. To check the actual device address run the I2C scanner I mentioned before.
> 1 votes

---
Tags: arduino-uno, sensors, i2c, accelerometer, wire-library
---


title: Sampling rate issue

text:
# Question
Title: Sampling rate issue
I have an Arduino code which runs decently.

```
// Read in 10-bits Magnetic Encoder AEAT-6010-A06  into Arduino Uno
// Sampling

// Declarate

const int CSn = 4; // Chip select
const int CLK = 7; // Clock signal
const int DO = 8; // Digital Output from the encoder which delivers me a 0 or 1, depending on the bar angle..
int analogPin = 3;
int val = 0;
unsigned int sensorWaarde = 0;

void setup() {
  Serial.begin(115200);
  //Fix de tris

  pinMode(CSn, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(DO, INPUT);

  //Let's start here
  digitalWrite(CLK, HIGH);
  digitalWrite(CSn, HIGH);
}

void loop() {

  val = analogRead(analogPin);
  // val = val - 670;
  sensorWaarde = readSensor();
  delayMicroseconds(1); //Tcs waiting for another read in
}

unsigned int readSensor() {
  unsigned int dataOut = 0;

  digitalWrite(CSn, LOW);
  delayMicroseconds(1); //Waiting for Tclkfe

  //Passing 10 times, from 0 to 9
  for (int x = 0; x < 10; x++) {
    digitalWrite(CLK, LOW);
    delayMicroseconds(1); //Tclk/2
    digitalWrite(CLK, HIGH);
    delayMicroseconds(1); //Tdo valid, like Tclk/2
    dataOut = (dataOut << 1) | digitalRead(DO); //shift all the entering data to the left and past the pin state to it. 1e bit is MSB
  }

  digitalWrite(CSn, HIGH); //
  Serial.print(dataOut);
  Serial.print("");
  Serial.print(" ");
  Serial.println(val);
  Serial.print(" ");

  delay(2);
  return dataOut;

}

```

From the delay data i assumed that i will be having approximately a sampling rate of 500 Hz, however it seems that the sampling rate is approximately 300+- Hz, without a proper confirmation.

My system is to be run in a Magnetic Encoder by Avago, but i have difficulties determining the sampling rate.

If possible, may i know what code should i use to indicate the time and sampling number?

# Answer
> 3 votes
At 115200 baud your serial prints will take 1/11520 seconds per byte.

---

```
Serial.print("");

```

What does that do?

---

I count 14 bytes here:

```
  Serial.print(dataOut);  // 5 bytes, say
  Serial.print("");       // zero bytes, lol
  Serial.print(" ");      // one byte
  Serial.println(val);    // 5 bytes + cr/lf = 7 bytes
  Serial.print(" ");      // 1 byte

```

Multiply 1/11520 (0.0000868) by 14 and you get 1215 µs.

---

Now add in your delays:

```
  delay(2);  // 2000 µs

```

---

And this:

```
 for (int x = 0; x < 10; x++) {
    ...
    delayMicroseconds(1); //Tclk/2
    ...
    delayMicroseconds(1); //Tdo valid, like Tclk/2
  }

```

Another 20 µs.

---

```
  val = analogRead(analogPin);   // 104 µs
  ...
  delayMicroseconds(1); // 1 µs

```

---

Total:

```
1215 + 2000 + 20 + 104 + 1 = 3340 µs

```

Inverse:

```
1 / 0.003340 = 299

```

---

So yes, I would expect around 299 iterations per second. That isn't counting the time for the other code to execute.

---

### Suggestions

* Get rid of the serial prints
* Get rid of `delay(2)`

---
Tags: rotary-encoder
---