# Question
Title: Cannot read from 2 I2C slaves consecutively
I am currently trying to communicate between 3 Arduinos using I2C. One of them acts as a master, while the rest act as slaves.

I can request data correctly from the master. But if I were to do 2 consecutive requests, I will only get data for the last request. Please assist.

Master:

```
#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.println("Reading from slave 1 now..");
  //Wire.beginTransmission(BLUNO_SLAVE);
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  //Wire.endTransmission();
  Serial.println("Reading from slave 2 now..");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
}

void loop () {
  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

```

Slave 1:

```
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x09);  //slave address
  Serial.println("Serials initialized");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  Wire.write("received master's request");
}

```

Slave 2:

```
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x0A);  //slave address
  Serial.println("initialized!");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  delay(60000);  //60 * 1000 = 60 seconds
  Wire.write("Lat: 103.123456, Lon: 1.098765");
}

```

Output on the master:

```
Initialized as Master
Reading from slave 1 now..
Reading from slave 2 now..
Lat: 103.123456, Lon: 1.098765

```

On top of that, I do not understand why the 1 minute delay was not executed before the slaves write the GPS coordinates.

I figured out from http://playground.arduino.cc/Main/WireLibraryDetailedReference that each call to the `requestFrom()` method, RESETS the read buffer. I looked at my code back and I saw a silly mistake on the master code. So, I corrected the master code:

```
#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.print("Slave 1: ");
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  readData();
  //each call to requestFrom, RESETs the read buffer index
  Serial.println();
  Serial.print("Slave 2: ");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
  readData();
}

void loop () {
}

void readData () {
  while(Wire.available()) {
  char c = Wire.read();
  Serial.print(c);
 }
}

```

But still, I don't understand why slave2 writes the data immediately instead of waiting for 1 minute?

# Answer
> 2 votes
I recommend you to just set a semaphore inside your handler. When your handler is called, set it, nothing more. In your main loop, poll for this semaphore and do your communication when true. When you receive this semaphore you can easily wait as long as you like without breaking interrupt handling. As interrupt service routines should always be as short as possible, both in terms of time and code, it is generally a bad idea to do complex communication from within or wait for something.

And don't forget the "volatile" keyword for your semaphore.

---
Tags: arduino-uno, programming, c++, i2c, c
---


# Question
Title: Need help to send serial data from arduino to XBee and to another XBee wirelessly?
I try to send serial data RPM to XBee series1 and then from XBee to another XBee wirelessly in API with Escapes Mode. I think I have to send the data Frame.But not very sure. Any help?

Following is the code to read RPM and send to XBee?

```
#include <XBee.h>
#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

XBee xbee = XBee();

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;

uint8_t start_data[] = { 0x7E, 0x00, 0x50, 0x01, 0x01, 0xff, 0xff,0x00, 0x05, 0x00,0x01,0x03, 0x84, 0x00 };

void setup()
{
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("I am ready to send some RPM!");
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()
{

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

  Serial.write(0x03);

  delay(2000);
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;

  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}
}

```

# Answer
You are using it as in non-API mode when data are passed to Xbee wireless transparently. To use Xbee in API mode use e.g. Xbee-Arduino library.
> 1 votes

---
Tags: arduino-uno, xbee
---


# Question
Title: Arduino Yun - Sensor Data logging to MYSQL on External Server
I want to log data from Sensors (Say Temperature, moisture or humidity) to a MYSQL database (provided by a online hosting company). Is it possible to establish communication between Arduino Yun and that database and log the data to it

# Answer
Yes, you can do that using python as well as other languages, or you can use Temboo: there's an example bundled with the Arduino IDE, it's called "SendDataToMySQL"
> 1 votes

---
Tags: arduino-yun
---


title: How to convert byte array to float

text:
# Question
Title: How to convert byte array to float
How can I convert a byte array to float?

Code:

```
void send_data() {
    CCPACKET data;
    data.length=2;

    float lon=26.533255;
    float lat=27.533463;

    data.data[0]=lon;
    data.data[1]=lat;

    if(cc1101.sendData(data)){
    Serial.println(data.data[0]);
    Serial.println(data.data[1]);

    Serial.println(" sent ok ");
    return true;
    }else{
    Serial.println("sent failed ");
    return false;
    }

 }

```

The problem is when I print those two variables it just prints lon 26.00 and lat 27.00 but not lon 26.533255 lat 27.533463 as I expected.

Here is the header file for CCPACKET I use:

```
#ifndef _CCPACKET_H
#define _CCPACKET_H

#include "Arduino.h"

/**
 * Buffer and data lengths
 */
#define CC1101_BUFFER_LEN        64
#define CC1101_DATA_LEN          CC1101_BUFFER_LEN - 3

/**
 * Class: CCPACKET
 *
 * Description:
 * CC1101 data packet class
 */
class CCPACKET
{
  public:
    /**
     * Data length
     */
    byte length;

    /**
     * Data buffer
     */
    byte data[CC1101_DATA_LEN];

    /**
     * CRC OK flag
     */
    boolean crc_ok;

    /**
     * Received Strength Signal Indication
     */
    byte rssi;

    /**
     * Link Quality Index
     */
    byte lqi;
};

#endif

```

I was trying to fix it by this part of code, but without success:

```
float lon=26.533543;

*((float *)data.data[0]) = lon;

```

Can someone help me to convert the byte array to float?

# Answer
> 3 votes
You can choose to treat the byte array as a float array by typecasting. Your attempt isn't far from a solution:

```
((float *)data.data)[0] = lon; // uses data.data[0] ... data.data[3]
((float *)data.data)[1] = lat; // uses data.data[4] ... data.data[7]

```

When printing you should also treat the data array as float array:

```
Serial.println(((float *)data.data)[0]);

```

It looks like you are sending the data over some interface. Then of course you need to typecast the binary data back into a float at the receiving end (if you want to do something useful with it) - similar to what is done above when it is passed to Serial.println.

# Answer
> 0 votes
> /\** *Data buffer*/ byte data\[CC1101\_DATA\_LEN\];

That line of code declares an array of datatype byte. I suggest you review variable declaration for Arduino.

A byte will store an 8-bit unsigned number with a range of 0 to 255, no decimal points. I also suggest you review truncation to understand how computer systems handle mathematic calculations that produce decimal results when the result is being stored in a variable type that doesn't store decimals.

A float stores a 32-bit value with decimal point.

The quick answer to your problem is to change the above quoted code from byte to float.

---
Tags: programming, c++, data-type
---


# Question
Title: Where can I find beginner resources on using voltage regulators with Arduino circuits?
I'm trying to concurrently learn electronics and Arduino, and have recently moved from simply powering LEDs to servos. In all my attempts with servos and reading about them (especially multiple ones, and when using external power supply plugged into the board), experienced users often mention you use voltage regulators.

I've seen some Arduino schematics with servos and voltage regulators, most that include some capacitors, but I can't seem to find any tutorials or resources that explain why, when and how to use these parts when learning electronics & Arduino. (I'd like to go from there to transistors, mosfets, etc.)

# Answer
> 1 votes
My understanding is that the capacitors smooth the signals. This helps the internal workings of the regulator not overshoot when compensating for a change in the input or the output. If the capacitors are not there then there is a chance of oscillation.

A search of google for Voltage Regulator Tutorial will give you quite a few results, here is one that I found (obviously this could change so if it does just do a search and go from there)

regulator basics

The link above is a good explanation that is not too in depth. But as stated in the comments look at the datasheet for specific values needed.

I also did a search for 'what are the capacitors for on a voltage regulator' and found some good info about why they are needed.

# Answer
> 2 votes
In order to get a smooth signal to your power regulator you should use some capacitors before and after the voltage regulator. It will look something like this when you use the 7805 voltage regulator.

Note: This schematic is from a dutch website. Uin means Vin and Uuit means Vout. C2 and C3 are bipolar capacitors.

It's also smart to put a diode before the voltage regulator to make sure the voltage flows only to one direction. The values of C1, C2, C3 and C4 and pretty standard and coul be used for the other Voltage regulators as well.

The voltage Regulators come in different fixed values and tey have a minimum and maximum voltage they can handle. Here's a small table of the most common VR's with their minimum input voltages.

```
Part Number     Output Voltage (V)      Minimum Input Voltage (V)
7805            +5                      7.3
7806            +6                      8.3
7808            +8                      10.5
7809            +9                      11.5
7810            +10                     12.5
7812            +12                     14.6
7815            +15                     17.7
7818            +18                     21.0
7824            +24                     27.1

```

Also note that the output currents of these Voltage Regulators listed above is max 1A. When they're called like 78S05 or 78S09 it'll be a 2A Voltage Regulator.

Another thing that could be important when you're using the minimum input voltages. If you put a diode before the Voltage Regulator there will be a small voltage drop. For a 1N4007 the voltage drop will be around the 0.5V. The voltage drop will only occur before the voltage regulator though, so when you don't use the minimal input values you don't have to mind about it.

---
Tags: voltage-level, servo, electronics
---


# Question
Title: Is there a way to detect if Arduino, Stino or another IDE/toolchain is in use?
I've noticed some irritating differences between the Arduino IDE and Stino (mainly around including certain header files). These are likely bugs that need following up with one or both of the parties, but in the meantime, I would like my code to compile with both of them without editing. This is because I do not want to lock any users out of using my code.

Are there any macros or similar that are readily available (as in, require no modification of the toolchain or IDE) that would allow me to detect which is in use?

For example, in many libraries, there is this snippet:

```
#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

```

However both Stino and Arduino define this.

# Answer
As Stino claims to use the installed Arduino IDE you already have, which means you can not differentiate at compile time.
> 1 votes

---
Tags: ide, build
---


# Question
Title: How to pass rx/tx led outputs to a shield
I have an Arduino Uno. I am building a custom shield and was wondering how I would connect two of the LEDs on the shield to the TX / RX LEDs on the Uno. Digital pins 0 and 1 seem obvious, but after further research, it appears that they are not for this.

In better terms, I want two LEDs on my shield that replicate the TX / Rx LEDs on the Arduino Uno.

How would I do this?

# Answer
> 4 votes
The TX/RX LEDs on the Uno are not connected to the main MCU but are instead connected to the USB communication chip, be it a FTDI or ATmega16U2. You would need to solder wires to the appropriate connections on the board and then connect them to the shield in question.

# Answer
> 2 votes
If you need just indicate data on TX/RX you can make simple circuit on shield bound to TX/RX lines.

---
Tags: arduino-uno, serial, led, shields
---


title: Modbus master slave

text:
# Question
Title: Modbus master slave
I need Help in two thing Here. 1)My main project is i have 23 hallsensors with analog output. There are connected to arduino UNO analog pins using 16:1 Mux or 8:1 mux circuit. The currently i can receive data properly with proper switching. Which are floating point values. Second stage: Now this has to communicate via MODbus protocol .(here only transmission is pending)

2) Now I am in to transmission data. Here i am using basic library downloaded from \[Download link modbus library\]\[1\]

Now my setup is like this I have arduino Board. RS485 sheild and USB to RS485 converter. Qmodbus software to view data.

I have uploaded the below code.

```
#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[16] = {
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus slave(1,0,0); // this is slave @1 and RS-232 or USB-FTDI

void setup() {
  slave.begin( 9600 ); // baud-rate at 19200
}

void loop() {
  slave.poll( au16data, 16 );
}

```

so i am expecting this answer if i am not wrong.

```
uint16_t au16data[16] = {
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };

```

But i am getting data as below.

questions:

1) Whats making wrong to get below data?? 2)If i want to store float values how can name uint16\_t au16data\[16\] or changes to be made 3) Is there any working code ON modbus!\[OUTPUt of MODBUS\]\[2\]

**Finally i got it working i can read The values. Now i am in second part. I have totally 20 values . currently i stored them as integer only. But my values are flaoting point.How to split real & floating value store in au16data\[16\] register.???**

Assume i got my Sensor value converted as *

```
CS=30.10
Int_CS=int(CS)
FLOAT_CS=(Int_CS-CS)*100
How to store the Int_CS & FLOAT_CS values in au16data[0]??

```

*

# Answer
> 1 votes
In Modbus protocol, `coils` are bits and `registers` are 16-bit unsigned integers.

Hence if you ask Modbus to read your `au16data` array as coils, and not as registers (which is what they actually are), then you'll get the binary representation for them with QModbus:

Your first register is `3` which is `0000 0000 0000 0011` in binary. Then when you read it as an array of 16 cils, you get these bit values, in reverse order (bit 0 is the lowest order bit and bit 15 is the highest order bit of your register); this is exactly what QModbus shos you:

* First 2 bits are 1
* All other bits are 0

Now regarding `float` values, if I remember correctly this is just not possible with Modbus protocol, hence you cannot do it out of the box.

What you can do, however, is to **cast one float as 2 registers** and transmit it this way, then it is up to the Modbus client to cast it back to a float; but QModbus will not do that for you as it strictly follows Modbus standard.

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


title: Multiple Stepper Motors in One Shield?

text:
# Question
Title: Multiple Stepper Motors in One Shield?
I need to construct 4 reactors for an experiment requiring mixing. We want to automate the mixing and at the same time reduce cost. can we connect multiple stepper motors with 5 or 6 wires on one shield version 2?

# Answer
Depending on the shield you can connect an external powersource through mosfets or transistors (Depending on the size of the steppermotor).

But if it is smaller motors with a 12v powersource, i really don't se why you would do that, since stepper motor controllers cost about $2-$4 each. Being cost effective i think that writing this question would cost more than actually just go and buy 6-8 controllers. (Don't buy the shield ones, they are overly expensive)
> 1 votes

---
Tags: arduino-mega, motor, shields
---


# Question
Title: Which side should I connect the resistor on?
I understand that when connecting an LED and a resistor in series; the resistor can be placed on any side of the LED as the current will remain same in a series connection. Please correct me if I'm wrong, but I was under the impression that conventionally the electrons flow from positive to negative. So shouldn't the resistor be placed before an LED to limit the flow of charge.

In this scenario the negative is connected ground and the positive to a power source. So I don't understand the chain Link analogy as well. Where the whole chain moves as a whole because here the flow ends with the GND right ?

# Answer
Another way to look at it is this:
Imagine the current flowing through the LED toward the resistor to be greater than the current flowing out of the resistor toward ground. The only way this could happen is if some of the charge - the difference due to the different currents - accumulated in the resistor. But that cannot happen forever, and not even for any appreciable length of time. (If it could, and did, the device would eventually fail - spectacularly!) So, because charge in must equal charge out over time (and over a very short period, at that) current in has to equal current out.
> 1 votes

# Answer
Resistor on any side of led will intercept current flow. Just use another analogy with water, tube and water tap.
> 1 votes

---
Tags: led, resistor
---


title: sprintf trouble

text:
# Question
Title: sprintf trouble
```
char cTime[22];

sprintf(cTime, "%04s/%02s/%2s:%02s:%02s:%02s", year(), month(), day(), hour(), minute(), second());

```

This `sprintf` line causes this error:\**B0100000063f694Š

Could someone help me debug this? Thank you.

# Answer
*%s* is string macro but output of *year(),...* is probably an integer type. Use *%d* or *%u* macros in format.
> 1 votes

# Answer
Yes - try making each of the %-specifiers match the kind of conversion you want for each variable in the rest of the call. F/ex, %d converts an integer to a string in decimal radix, %f converts a double to a number with a decimal fraction, etc. In all cases, the output will be as characters; you don't need to specify that.
> 0 votes

---
Tags: string
---


title: Breakout vs Shield

text:
# Question
Title: Breakout vs Shield
I would like to extend my arduino uno with WIFI and I am checking different options.

These are:

Adafruit-CC3000-Breakout-with-Onboard-Ceramic-Antenna

Arduino WiFi Shield (integrierte Antenne)

Viewing the price, obviously I understand that the shield will have more functions, I think also it is more "friendly" for programming and the breakout requires more low level code(I am not afraid of it...)

I already have an arduino yun but it is busy with a project, so I need something for the uno.

For what kind of projects could be better each of them? and what are the main differences between a shield and a breakout?

Also in the future I would do some projects with gsm, so this question could be similar ... gsm shield vs breakout.

# Answer
If you prototyping for a device intended for production then use breakout board with supposed WiFi module. Also if space is constraint then shield might be problem. For a hobby system use WiFi shield, which uses rather complicated circuit with AVR32 MCU, but you just plug-in and uses prooved libs. For production MCU would mean one more firmware flashing, upgrades, maintainance and higher price - from my point of view useless.
> 2 votes

# Answer
Shields are in a form factor suited for direct attachment to the Arduino, but have fixed functionality for their connections. Breakout boards require more wiring work, but allow you to connect to any appropriate pins.
> 4 votes

# Answer
A breakout board usually has the sole purpose of making a single chip (gross generalization here...) available to the experimenter by "breaking out" its signal lines on to dedicated pins - header pins, for instance. It is only large enough for the chip and the printed circuit wiring to do this, and seldom adds any function beyond what the chip itself provides.

A "shield" is a larger board that usually plugs directly onto an Arduino board, matches its form factor, and is built for a dedicated more complex function, like a complete GPS system or cellular communication system (although some shields are left mostly blank to provide you the space to build your own device). They probably have several chips engineered and built into a complete plug-and-go sub-system.

One is to learn to use a chip or other device without having to solder up your own board, especially with surface mount devices. The other is a ready-to-go system building block.
> 3 votes

---
Tags: arduino-uno, wifi, shields
---


# Question
Title: Homebrew Arduino using ATMEGA328P, ISP or ICSP?
I plan on creating a homebrew Arduino breakout board using the ATMEGA328P smd version. I'm geeting confused by the wealth of information out there as to whether I should be using ICSP or ISP to program it. It is a blank chip, aka no Arduino bootloader on it yet. I'd rather not have to buy a specialized programmer to burn the bootloader, I do have another Arduino I could use to burn the bootloader and upload sketches to it with.

So the question is; Do I use ISP or ICSP, or both?

# Answer
> 1 votes
To program it you could use an ISP programmer. In which case you would not need the bootloader. You can use an Arduino as an ISP programmer, but that's not really a long term solution, as you can no longer use the arduino for anything else.

The other option is to program it using a usb-to-serial. In this case you do need the arduino bootloader. To program this bootloader (once) you can use the above method, using an arduino board.

Third option would be implement USB into the bootloader, just like the *completely Open Source* Pro Trinket (bootloader and schematic). You'd have to add some resistors, zener diodes and a usb plug (just strip an old usb cable). A bit more technical and challenging, but definitely the cheapest

# Answer
> 2 votes
ICSP is used for PICs, not AVRs. Use ISP, which can be performed either by an Arduino via ArduinoISP or by a dedicated programmer.

---
Tags: bootloader, atmega328, isp, icsp
---


# Question
Title: Adafruit CC3000 WiFi Module working together with MFRC522 RFID Module Issues both SPI over Arduino
I'm asking if how can I implement this one. I'm aware about multiple devices being connected over SPI, like having to select individual SS pin for each. Adafruit's CC3000 works fine alone along with the default Adafruit library. CC3000 uses SPI. MFRC522 RFID module by sonmicro (bought at Sparksfun) uses SPI too. It works fine too, independently. But whenever I connect them together, only WiFi works perfectly. I dont want to turn on and off the wifi to make way for the RFID to communicate since it takes some time for it to be connected in a wireless network. I want the two to work synchronously (or having to be scheduled but really fast that's unnoticeable by the user)

here's my code as of now. i cannot post it here as strange things happen i don't know why haha https://drive.google.com/file/d/0B0bZsYo0xMH8YV9uWXJaRFdPT3M/view?usp=sharing

I'm thinking of replacing the RFID with SonMicro's SM130 RFID Module w/ SparkFun Eval board with UART (convertible to I2c) or Adafruit's PN532 with I2c by default. Are these okay to be paired with SPIs like the CC3000? Or should I change CC3000 with the Official WiFi module (UART) or WiFly Module (SPI-to-UART)

# Answer
I couldn't get your code to download so this might be wrong, but it sounds like the modules are running different SPI modes: http://en.wikipedia.org/wiki/Serial\_Peripheral\_Interface\_Bus#Mode\_numbers

I had this problem a few years ago. You'd expect SPI to be SPI, but it comes in four different flavours and they won't talk to each other on the same bus. Unfortunately there's no solution but to replace the modules; the Arduino can only run one SPI bus, so can only talk to one of these modules at a time.

However you can run UART and I2C or UART and SPI concurrently by using SoftwareSerial (don't use the native Tx/Rx pins, bad things happen).

So your best bet is to switch to modules that use I2C or UART. Personally I'd use UART, simply for the simplicity of having two separate connections and a higher data rate.
> 1 votes

---
Tags: wifi, spi, rfid
---


title: Modbus slave data into word

text:
# Question
Title: Modbus slave data into word
I have simple code. The library downloaded from github:smarmengol/Modbus-Master-Slave-for-Arduino.

I wanted to store floating point. In the code blow, I type casted to integer value. As I know `uint16_t au16data[30];` is integer

```
#include <avr/wdt.h>
#include"glob.h"

#define ID   1
int8_t state = 0;
Modbus slave(ID, 0, 0);
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[30];

void Take_Reading()
{
  for(row=0;row<9;row++)
  {
  int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(SO_enable,array[row][1]);
    digitalWrite(S1_enable,array[row][2]);
    digitalWrite(S2_enable,array[row][3]);
   //delay(100);
    Sensor_Value0=analogRead(A0);
    Sensor_Value1=analogRead(A5);
   Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
   Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

   Current_Value1[row]=  (Mux1_array[row]*40)-98;
   Current_Value2[row]=  (Mux2_array[row]*40)-98;

  }
}

void setup()
{
     wdt_enable(WDTO_8S);
   slave.begin( 9600 );
  tempus = millis() + 100;
  pinMode(3,OUTPUT);
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
  pinMode(A0, INPUT) ;
  pinMode(A5, INPUT) ;

//  Serial.begin(9600);
}

void loop()
{
  digitalWrite(3,HIGH);
// wdt_reset();
 Take_Reading();
 state = slave.poll( au16data,30 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

Modbus_call();

}

void Modbus_call()
{

/*reading of coil where i can succefully read value*/
  au16data[0]=(int)Current_Value1[0];
  au16data[1]=(int)Current_Value1[1];
  au16data[2]=(int)Current_Value1[2];
  au16data[3]=(int)Current_Value1[3];
  au16data[4]=(int)Current_Value1[4];
  au16data[5]=(int)Current_Value1[5];
  au16data[6]=(int)Current_Value1[6];
  au16data[7]=(int)Current_Value1[7];
  au16data[8]=(int)Current_Value1[8];
  au16data[9]=(int)Current_Value2[0];
  au16data[10]=(int)Current_Value2[1];
  au16data[11]=(int)Current_Value2[2];
  au16data[12]=(int)Current_Value2[3];
  au16data[16]=(int)Current_Value2[4];
   au16data[17]=(int)Current_Value2[5];
   au16data[18]=(int)Current_Value2[6];
   au16data[19]=(int)Current_Value2[7];
 uint16_t calcCRC( au16data[15]);
     au16data[13] = slave.getInCnt();
  au16data[14] = slave.getOutCnt();
  au16data[15] = slave.getErrCnt();

 }

```

Conversion method as below.

```
CS=30.10
Int_CS=int(CS)
FLOAT_CS=(Int_CS-CS)*100

```

How to store the `Int_CS` & `FLOAT_CS` values in `au16data[0]`??

---

I have change code accordingly.

But I get zero. After some time its values don't even show

```
#include <avr/wdt.h>
#include"glob.h"

#define ID   1
int8_t state = 0;
Modbus slave(ID, 0, 0);
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[5];
float auFloatData[30];
void Take_Reading()
{
  for(row=0;row<9;row++)
  {
  int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(SO_enable,array[row][1]);
    digitalWrite(S1_enable,array[row][2]);
    digitalWrite(S2_enable,array[row][3]);
   //delay(100);
    Sensor_Value0=analogRead(A0);
    Sensor_Value1=analogRead(A5);
   Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
   Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

   Current_Value1[row]=  (Mux1_array[row]*40)-98;
   Current_Value2[row]=  (Mux2_array[row]*40)-98;

  }
}

void setup()
{
     wdt_enable(WDTO_8S);
   slave.begin( 9600 );
  tempus = millis() + 100;
  pinMode(3,OUTPUT);
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
  pinMode(A0, INPUT) ;
  pinMode(A5, INPUT) ;

//  Serial.begin(9600);
}

void loop()
{
  digitalWrite(3,HIGH);
// wdt_reset();
 Take_Reading();
 state = slave.poll( au16data,5 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

Modbus_call();

}

void Modbus_call()
{

/*reading of coil where i can succefully read value*/
  auFloatData[20]=Current_Value1[0];
  auFloatData[21]=Current_Value1[1];
  auFloatData[22]=Current_Value1[3];
  auFloatData[4]=Current_Value1[4];
  auFloatData[5]=Current_Value1[5];
  auFloatData[6]=Current_Value1[6];
  auFloatData[7]=Current_Value1[7];
  auFloatData[8]=Current_Value1[8];
  auFloatData[9]=Current_Value2[0];
  auFloatData[10]=Current_Value2[1];
  auFloatData[11]=Current_Value2[2];
  auFloatData[12]=Current_Value2[3];
  auFloatData[16]=Current_Value2[4];
   auFloatData[17]=Current_Value2[5];
   auFloatData[18]=Current_Value2[6];
   auFloatData[19]=Current_Value2[7];
uint16_t calcCRC( au16data[3]);
     au16data[1] = slave.getInCnt();
  au16data[2] = slave.getOutCnt();
  au16data[3] = slave.getErrCnt();

 }

```

# Answer
1. Sizes

Integer Types (int, long and long long)

Size of Boolean type is 1 byte(s)

Number of bits in a character: 8 Size of character types is 1 byte Signed char min: -128 max: 127 Unsigned char min: 0 max: 255 Default char is unsigned

Size of short int types is 2 bytes Signed short min: -32768 max: 32767 Unsigned short min: 0 max: 65535

Size of int types is 4 bytes Signed int min: -2147483648 max: 2147483647 Unsigned int min: 0 max: 4294967295

Size of long int types is 4 bytes Signed long min: -2147483648 max: 2147483647 Unsigned long min: 0 max: 4294967295

Size of long long types is 8 bytes Signed long long min: -9223372036854775808 max: 9223372036854775807 Unsigned long long min: 0 max: 18446744073709551615 Note that int and long are the same size and if you want a 64 bit integer then you need to use long long (or unsigned long long).

2. What do you want to achieve with

.

```
CS=30.10 // 30.10
Int_CS=int(CS) // 30
FLOAT_CS = (Int_CS-CS)*100 //-10.00 because 30 - 30.10 = -0.1 and -0.1 * 100 = -10.00

```

CS is already float, why you want to convert it to int and back to float? If value of int is higher than 255 you have to save it in 2 bytes(highByte and lowByte), float is 32bit(4bytes) value.

I think you have to do like this:

```
float CS = 30.10;
au16data[0]= (int)(CS*100);//3010.00 > 3010

```

And for better way use :

```
float auFloatData[30]; //
...
auFloatData[0]=Current_Value1[0];

```
> 1 votes

---
Tags: arduino-uno, data-type, modbus
---


# Question
Title: Problem with piezo readings and Arduino Due
I'm using 1mOhm resistor in parallel to a piezo that is connected to analog1 pin on the Due,

and the following code to observe the readings in the serial monitor:

```
int piezo = A0;
int threshold = 200;//anything over 200 means I've hit the piezo

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

//this part checks if the threshold has been reached and then writes the strenght of the signal

void loop(){
    int piezoVal = analogRead(piezo);

    if (piezoVal>threshold){
        Serial.println(piezoVal);

        delay(10); //delay is used to prevent from getting multiple values one after another, usually 3-4
    }
}

```

The things that bother me are:

* if I do not use threshold, then I am constantly getting readings from the piezo, even if the threshold is slightly below 200.
* if I do not use delay, then I'm getting getting multiple values one after another
* and the strangest thing is while I hit the mouse pad that covers the piezo, the readings in the serial monitor are not matching the force being used to trigger the piezo. Sometimes they stay the same, sometimes they reach 6-700 after I directly touch the piezo, sometimes I hit really hard and I only get some slight increase (for ex. from 225 to 229).

This doesn't make sense to me. I think the stronger the vibration, the higher the values should be. Cause I've tried with two different piezos and different resistors (1mOhm, 1.2 mOhm and 1.5 mOhm) and I'm still getting the same result. I bought the Due few days ago in order to build a drum kit, and I have no problem with sending midi notes to a DAW, but this piezo sensitivity thing is driving me crazy. Any suggestions?

# Answer
> 2 votes
The problem is timing. When you tap or hit the sensor it produces an impulse response: a signal that increases to a peak, then decays back to zero. You are expecting the code to capture the peak value. Your code is spinning in loop() as quickly as possible, but captures just the first point above the threshold. The signal can still be increasing when you capture and print.

So imagine this stream of signal values

```
time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190      190
 2     190
 3     199
 4     210
 5     220      220 - trips threshold, prints and then waits
 6     230
 7     260
 8     280
 9     320      (this point occurs during delay())
 10    280
 11    260

```

The same exact signal, but at a slightly different time could be read different by the code:

```
time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190
 2     190
 3     199      199
 4     210
 5     220
 6     230
 7     260      260
 8     280
 9     320      (closer, but still did not read the peak)
 10    280
 11    260

```

So the strategy of catching the first point above the threshold makes it unlikely you can capture the peak value. There are two ways forward: hardware or software.

You could use electronics that latches the maximum value. If you search "peak hold circuit" you will find many circuits that would capture and hold the peak. That frees the Arduino to somewhat lazily spin in the loop and still be able to accurately capture the peak. Once it sees the value is no long increasing, it resets the peak hold and goes back to waiting.

You could use code to capture the peak. Something along the lines of this psuedo code:

```
lastreading = analogread()
if(lastreading > threshold) {
  peakreading = lastreading
  keeplooking = true
  while(keeplooking) {
    nextreading = analogRead()
    if(nextreading > lastreading) {
      // the signal is increasing, save this and see if next point is even higher
      peakreading = nextreading
      lastreading = nextreading
    }
    else {
      //signal is decreasing, the peak is over
      keeplooking = false
    }
  }

```

This software approach could still miss a sharp peak that occurs between analogRead()'s, but may be good enough for your use.

---
Tags: arduino-due, analogread
---


# Question
Title: How to use output from Arduino in C++ code?
I am a complete novice in Arduino and moderately experienced with the language C++. What if I want to use the output from the serial monitor in C++ code in real time?

Also how can I write to the serial monitor. Which libraries are available for this? Also please give me links to sites where I can learn more about this topic. I am using Arduino Uno.

# Answer
> 2 votes
Unfortunately, C++ doesn't have native support for serial I/O.

You could use the Windows API directly if you're feeling adventurous. It can be a little complicated to get to grips with, but not insurmountable. You can get basic information about it here. There's an example of using it with Arduino here.

As an alternative, you could use a 3rd party library. This one looks good, although I haven't actually used it myself.

# Answer
> 1 votes
```
#include <windows.h>
#include <string>
#include <stdio.h>
#define ARDUINO_WAIT_TIME 2000
using namespace std;

string portNumber;
HANDLE hSerial;
bool connected;
COMSTAT status;

bool connectPrinter(char *portName){

    //Connects to the port.
    hSerial = CreateFileA(portName,
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

    if(hSerial==INVALID_HANDLE_VALUE)
    {
        if(GetLastError()==ERROR_FILE_NOT_FOUND){
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);
            return false;
        }
        else
        {
            //If port is in use by another program or did not closed previous process.
            printf("ERROR!!! \n");
            CloseHandle(hSerial);
            return false;
        }
    }
    else
    {

        DCB dcbSerialParams = {0};

        if (!GetCommState(hSerial, &dcbSerialParams))
        {
            printf("failed to get current serial parameters!");
            return false;
        }
        else
        {
            // Set Serial Port specifications.
            dcbSerialParams.BaudRate=CBR_115200;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;

             if(!SetCommState(hSerial, &dcbSerialParams))
             {
                printf("ALERT: Could not set Serial Port parameters");
                return false;
             }
             else
             {
                 connected = true;
                 printf("Connection Successful for :%s !!! \n" ,portName);
                 //Wait 2s as the arduino board will be reseting
                 return true;
                 Sleep(ARDUINO_WAIT_TIME);
             }
        }
    }

}

int readData(char *buffer,unsigned int nbChar){

    DWORD bytesRead;
    DWORD dwCommModemStatus;

        //Set the type of data to be caught.(RXCHAR -> Data available on RX pin.)
        SetCommMask (hSerial, EV_RXCHAR );

        while (hSerial != INVALID_HANDLE_VALUE)
        {
          // Wait for an event to occur for the port.
          WaitCommEvent (hSerial, &dwCommModemStatus, 0);

          if (dwCommModemStatus & EV_RXCHAR )
          {
                //unsigned int toRead;
                //ClearCommError(this->hSerial, &this->errors, &this->status);
                do
                {
                  // Read the data from the serial port.
                    ReadFile (hSerial, buffer, 1, &bytesRead, 0);
                  // Display the data read.
                      printf ("%s" ,buffer);

                } while (bytesRead > 0);
          }
        }
    //}
    //If nothing has been read, or that an error was detected return -1
    return -1;
}

    int main()
    {

        char* buffer = new char[32768];
        int nbChar= 32768;
        string str="COMx"; // Use your port number to connect

        char * writable = new char[str.size() + 1];
        std::copy(str.begin(), str.end(), writable);
        writable[str.size()] = '\0';

        connectPrinter(writable);
        delete []writable;
        readData(buffer,nbChar);
        return 0;
    }

```

try this one, it should work. Comment below if it does not work. You might reset Arduino to read data in method `void setup()` in Arduino code. I recommend you to use C#, Java or Python for efficiency.

# Answer
> 0 votes
@Peter has already posted library links.

I recommend that you use Node.js (node-serialport) or Python (serial), which have excellent native serial support.

Both of these use C++ internally to communicate over Serial (Serial.h). Try going through the code Node.js uses internally, and if you are willing to write that much, by all means use the library.

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


# Question
Title: Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react
Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.

```
int button_prev = 0;
int button = 0;

void loop(){

    button_prev = button;

    button = digitalRead(12);

    if (button_prev != button) {

      digitalWrite(act_pin[j], HIGH);

      j = (j+1) % 5;

    }
}

```

I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on. But I don't see where the behavior of j comes from...

\[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.\]

\[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.

But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button. `Serial.println` as well just spits out one character, similiar looking to a `d`.\]

Can anyone point out my mistake to me?

This is the circuit

and this is the *old code* of the sketch

```
int act_pin[6] = {A0, A1, A2, A3, A4};

int j = 0;

void setup(){

  Serial.begin(9600);

  for (int k = 0; k < 5; k++) {

     pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output

     digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off

     pinMode(12, INPUT); //sets pin connected to button as input

}

}

void loop(){

  char button = {digitalRead(12)}; //stores if the button was pressed

  Serial.println(button);

  if(button == HIGH){

    digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press

    j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4

    button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
}

}

```

# Answer
I think you're looking for the action (in pseudo-code):

```
ONCE (Button Pressed):
    Light LED j;
    j++

```

But you have an IF(button) in a Loop{}. Something like:

```
WHILE (Button Pressed):
    Light LED j;
    j++

```

So when you press the button j will increment every iteration of Loop {} (very fast) and you won't be able to see the LEDs changing. Your 'button = LOW' is not effective because 'button' gets set again the next time if the button is still pressed.

Try printing j instead of button at the line:

```
Serial.println(j);

```

and that should highlight the problem.

I would implement a ONCE(Button Pressed) function by observing the previous button state and checking it has changed from LOW to HIGH.

```
    button_prev = button;
    button = digitalRead(12);
// Check if button changed from LOW to HIGH
    if (!button_prev && button) {
    ...code
    }

```

EDIT: Dealing with Contact Bounce

Switches are mechanical so they don't switch cleanly. This is called contact bounce and means the switch switches on/off very rapidly for about 10ms or so after the contact has been pressed or released.

See Measuring Switch Bounce

You can deal with it quite simply in the code as follows (pseudo code) just by waiting for the bounce to dissapear and checking the button is still pressed:

```
ONCE (Button Pressed):
   WAIT(20ms)              // wait for the bounce to stop
   IF(Button Pressed):     // Ensure the button is still pressed
    ...code...

```

Try the following Arduino Code:

```
    button_prev = button;
    button = digitalRead(12);
// Check if button changed from LOW to HIGH
    if (!button_prev && button) {
       delay(20);                 // Wait for debounce
       if(digitalRead(12))  {     // Make sure the button is still pressed
        ...code
       }
    }

```
> 1 votes

# Answer
Your code has a serious bug here:

```
if(button == HIGH){

    digitalWrite(act_pin[j], HIGH);

    j = j+1;

    button = LOW;
}

```

You increment `j` without any boundary so it will have the following cycling values:

```
0, 1, 2, 3 ... 32767, -32768, -32767 ... -1, 0 ...

```

Hence, quickly `act_pin[j]` will return garbage...

The solution is easy, you must limit `j` to `[0,1,2,3,4]`, just replace the `j = j + 1` line as follows:

```
j = (j + 1) % 5;

```

`%` is the modulo integral operation that will give you the reminder of dividing j by 5, which is always strictly less than 5, and it cycles as you want.
> 2 votes

# Answer
> ```
> if(button = HIGH)
>
> ```

Oops.

```
if (button == HIGH)

```

And see the Debounce example sketch to learn how to debounce inputs.
> 1 votes

---
Tags: led, sketch, button, debounce
---


# Question
Title: Debouncing results in no reaction at all
Update:

I changed the code to this, but it does not work either.

\`if ((millis() - lastDebounceTime) \> debounceDelay) {

```
   if (button) {
 //DEBOUNCING

     if (!button_prev && button) {

      int e = input[j];`

```

I am trying to debounce a button and integrated this code http://arduino.cc/en/Tutorial/Debounce into my sketch. The result is, that there is no reaction to the button at all. I can't figure out the mistake, but maybe someone else sees what I overlook.

Circuit

Parts marked with `//DEBOUNCING` are only for the purpose of it, parts marked `//DEBOUNCE relevant` are necessary for the code to run as well when there is no debouncing.

```
void setup() {

  Serial.begin(9600);

  //setting button pin as input and LOW

  pinMode(8, INPUT);
  digitalWrite(8, LOW); //DEBOUNCE relevant

  //setting input pins as output

  int act_pin[6] = {A0, A1, A2, A3, A4};

  int k = 0;

  for (k = 0; k < 5; k++) {

      pinMode(act_pin[k], OUTPUT);

    }

  //setting state pins as output

  int z_pin[5] = {2, 3, 4, 5};

  int a = 0;

  for (a = 0; a < 4; a++) {

      pinMode(z_pin[a], OUTPUT);

   }

  //setting output pins as output

  int out_pin[6] = {9, 10, 11};

  int b = 0;

  for (b = 0; b < 3; b++) {

      pinMode(out_pin[b], OUTPUT);

   }

  //setting input

  for(k = 0; k < 5; k++) {

      randomSeed(analogRead(5));

      int i = random(2);

      if(i == 1){

         digitalWrite(act_pin[k], HIGH);

         input[k] = 1;

         Serial.print(input[k]);

      }

       else{

         digitalWrite(act_pin[k], LOW);

         input[k] = 0;

         Serial.print(input[k]);

      }

    }

   //setting initial situation

   digitalWrite(2, LOW);
   digitalWrite(3, HIGH);
   digitalWrite(4, LOW);
   digitalWrite(5, LOW);

   }

//DEBOUNCING

long lastDebounceTime = 0;  // the last time the button pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int buttonState;

//DEBOUNCING

boolean button_prev = 0;

boolean button = 0;

int j = 0; //value shows current lamp being processed

//setting initial state

char z[4] = "z_0";

void loop() {

    button_prev = button;

    button = digitalRead(8); //DEBOUNCE relevant

    // DEBOUNCING
    if (button != button_prev) {

    lastDebounceTime = millis();

    }

    if ((millis() - lastDebounceTime) > debounceDelay) {

       if (button != button_prev) {
     //DEBOUNCING

         if (!button_prev && button) {

          int e = input[j];

           //provides a nice output
            Serial.println(" ");
            Serial.print("Current lamp being processed:");
            Serial.println(j);
            Serial.println(" ");
            Serial.print("Current input:");
            Serial.println(e);

             delta(e, z);

            Serial.print("State outside function:");
            Serial.println(z);

            lamda(e, z);

             j = (j+1) % 5;

      }

    }

   }
}

```

# Answer
> 1 votes
It's difficult to tell without seeing your circuit, but it looks like there could be a mix up between pin 12 and pin 8. Can see that you initialize the pinMode for pin 12 in setup, but it isn't used in the loop. You didn't initialize pin 8 (not completely necessary) in setup, but it is used in the loop. If you don't feel this is relevant, please provide some more detail.

# Answer
> 0 votes
If the button has stopped bouncing then (button\_prev == button) and the inner if (button != button\_prev) will fail. Basically you're trying to ensure the button is steady but then you're checking that it changed.

Try this:

```
    if ((millis() - lastDebounceTime) > debounceDelay) {

       if (button) {     // Check the button is still pressed
       ... code...
}

```

# Answer
> 0 votes
You've probably fixed this already but pin 8 is always grounded, regardless of the button state. Pin 8 should be connected between the button and the pull-down resistor.

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


# Question
Title: Arduino program only works when run as root
Uploading simple sketches seems to work when I run the Arduino program as root (`sudo`). I would like to run it as a regular user. Has anyone faced the same problem before and fixed it?

Here is what I obtained from `lsusb`:

```
$ lsusb
Bus 002 Device 022: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

```

And the Arduino program identifies it as `/dev/ttyACM0`. Here are its permissions:

```
$ ls -l /dev/ttyACM0
crw-rw---T 1 root dialout 166, 0 Mar 14 22:03 /dev/ttyACM0

```

Here is the output from `id`

```
groups=1000(abhiram),20(dialout),24(cdrom),25(floppy),29(audio),
30(dip),44(video),46(plugdev),105(scanner),110(bluetooth),112(netdev)

```

When I upload an sketch from the examples, as a regular user, I encounter this error:

```
avrdude:stk500_recv(): programmer not responding

```

Any suggestions are welcome.

# Answer
The easiest solution is to add yourself to the `dialout` group.

First make a note of the output from `id`. Save it in file (not in `/tmp` as that gets cleaned out on a reboot). If you look at the output, you'll notice that your user is signed up for several groups and those groups represent extra privileges on the system. By default your Arduino is assigned to the group `dialout` because it registers as a serial interface and in the old days these were often used to ... dial out, using a modem.

To add yourself to the `dialout` group, issue the following command:

```
sudo usermod -a -G dialout $USER

```

Don't forget the `-a` flag (for appending groups rather than replacing) or you will have entirely different problems. This is the reason for making a copy of the `id` output to a file, so in case you do mess up at least you know what your user was configured like before.

Then log out and log in and it should work from that point.

Optionally you can double check the output for `id` against the output you saved before.
> 13 votes

# Answer
The oft-repeated advice to "just do `sudo usermod -aG dialout <username>` never worked for me, and I finally figured out why. On my machine, `/dev/ttyUSB0` is of the group `serial` and not `dialout`, so adding my username to `dialout` did nothing.

```
# ls -l
# crw-rw---- 1 root serial 188, 0 Mar 31 20:52 /dev/ttyUSB0
                    ^^^^^^ (group-name)

```

Finally: `sudo usermod -aG <group-name> <username>` fixed it for me.

Embarrassingly, this is also explicitly mentioned here under "SET THE PERMISSION". Sigh.
> 9 votes

# Answer
This happens to me. In my case, I had upgraded the version of arduino and seems the preferences file was causing the problem. Just delete ~/.arduino/preferences.txt file (with Arduino IDE closed).

Steps:

1. Close Arduino IDE
2. execute this:

rm ~/.arduino/preferences.txt
3. Launch Arduino IDE

This worked for me, hope it works for someone else. I am using Linux Mint 17 and I upgraded from Arduino 1.05 to Arduino 1.06 by extracting the Arduino IDE, I am not using the one in the repo. (Of course, after adding your user to the corresponding group as mentioned by others, but if that wont help you try this)
> 0 votes

---
Tags: arduino-uno, arduino-ide, linux
---


title: Led on when not supposed to be

text:
# Question
Title: Led on when not supposed to be
So I made a program that controls two LED's when two buttons are pressed, but one of the LED's comes on when the button isn't pressed. And what's weird is that if I literally move around the breadboard the LED might turn off for a little, and if hold the button down while doing it the LED remains solid. I have done a lot of taking out and switching wires without any unexpected effects. However, if I switch the LED wires the other LED turns and stays on while the first one turns off, so I am pretty sure that it is a programming error. Here is my code:

```
const int ledPin1 = 8;
const int buttonPin1 = 1;
const int ledPin2 = 9;
const int buttonPin2 = 2;

int buttonState1 = 0;
int buttonState2 = 0;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin2, INPUT);
}

void loop()
{
buttonState1 = digitalRead(buttonPin1);
buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == LOW)
  {
    digitalWrite(ledPin1, HIGH);
  }
  else
  {
    digitalWrite(ledPin1, LOW);
  }

  if (buttonState2 == LOW)
  {
    digitalWrite(ledPin2, HIGH);
  }
  else
  {
    digitalWrite(ledPin2, LOW);
  }
}

```

# Answer
The behavior you describe is symptomatic of a floating input.

I guess you have directly wired your buttons between input pins and +5V (or GND, that won't change the observed behavior).

The problem is when you don't push the button, the input pin is left floating and can be read as HIGH or LOW based on strange factors.

The solution to this is to use pullup (if you connect the other side of the button to GND) or pulldown (if your button is connected to +5V) resistors.

The following image, off the arduino website, shows such a circuit with a pulldown resistor, i.e. connect the switch to +5V and the resistor to GND:

An even simpler way is to connect the buttons to GND and use `pinMode(pin, INPUT_PULLUP);` in `setup()`.
> 5 votes

# Answer
I don't think it is necessary to do the declaration of int buttonstate1 = 0; and int buttonstate2 = 0; seeing that in your loop the buttonstates gets read by you using digitalRead. Also I don't think the buttons is inverted, because you aren't using a pull up resistor if I'm correct.

Hopefully this helped.

Also something that I found helped a lot is that if you use a lastbuttonstate variable too. Than your if statement might look something like this:

```
if(buttonstate1 == HIGH && previousbuttonstate1 == LOW)
{
digitalWrite(ledPin1, HIGH);
previousbuttonstate1 = buttonstate1;
}

else if(buttonstate1 == HIGH && previousbuttonstate1 == HIGH)
{
digitalWrite(ledPin1, HIGH);
}

else if(buttonstate1 == LOW && previousbuttonstate1 == HIGH)
{
digitalWrite(ledPin1, LOW);
previousbuttonstate1 = buttonstate1;
}

else
{
digitalWrite(ledPin1, LOW);
}

```

Basically adding the previousbuttonstate1 just gives it a more accurate way of checking the button state(I'm typing under correction).

Sorry for the sloppy answer, but hopefully it helps.
> 0 votes

---
Tags: programming, led, button
---


title: Reading a tachogenerator

text:
# Question
Title: Reading a tachogenerator
I'm trying to read a tachogenerator from a washing machine. It outputs an alternating current, with multiple periods per revolution. The voltage for my test case (constant rpm) reads 5.5V. I attached the tachogenerator to Digital 2 and GND and ran this sketch, just to see if a change is detected:

```
int ledPin = 13;
volatile int state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  attachInterrupt(0, blink, RISING);
}

void loop() {
  digitalWrite(ledPin, state);
  delay(500);
}

void blink() {
  if (state == LOW) state != state;
}

```

Unfortunately, the LED does not light when I start the motor. When I measure the voltage while it is connected to the Arduino, it shows only about 0.7V, which would explain why the LED is not reacting. But why is this?

# Answer
> 3 votes
There's an obvious code problem in your `blink()` function:

```
state != state;

```

The above statement will never modify your state variable. The `!=` operator in C/C++ does not perform an assignment (unlike operators such as `+=` and `-=`). It's a comparison operator which just tests for inequality. You presumably meant to do this:

```
state = !state;

```

That may not fix your problem entirely though. You might find that the interrupt doesn't get reliably triggered anyway because it's not designed to handle AC. I'd recommend using an external comparator circuit to generate a clean digital signal, such as a Schmitt trigger.

---
Tags: sensors, interrupt
---


title: How to parse array to x,y positions?

text:
# Question
Title: How to parse array to x,y positions?
I have 16x16 LED matrix and I want to show some custom characters on it. I saw font made with array like this.

```
const byte zero[16] = { // Create byte array number 0
        B0111110,
        B1111111,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1111111,
        B0111110
    };

```

But I dont know how to parse it to x, y positions. Can someone help me? Do you know better way to store characters that is easily readable by human? Thanks

# Answer
To get the value at a particular location, use this code:

```
boolean val = zero[y] & ((B1 << maxX) >> x);

```

where `y` is the y position from 0 to `zero.length`, `maxX` is the length of the binary constants minus one (in this case, it would be 6), and `x` is the x position from 0 to `maxX`.

For more information, see BitMask.
> 2 votes

# Answer
Th example looks like the character '0', 8 bits wide and 16 bits high, though it could be the 16x8 due to '0's symmetry. Find the '2' array, for instance and plot the 1-bits on a piece of graph paper (even a hand-drawn grid will do). Once you should see the character shape you'll know how the bits/dots are arranged in the array.

If your LED array has a square pitch (same spacing vertically and horizontally), 16-bit high characters may appear rather tall and skinny. If so, you could re-plot the characters to suit yourself. If you do decide to hand code them, look at your display hardware. It probably (but not necessarily) accepts 8 horizontally-adjacent bits at a time. But regardless, you can simplify your display code if one array-byte contains 8 bits that will be output at once.

--------- Update:

There's a lot missing from your question but I'll pick some assumptions to base an answer on.

```
Y = array_index;
X = (6-bit_position) + (is_right_hand_character ? 8 : 0);

```

based on assumptions that:

* you want the display coordinates of a given bit in the array;
* the origin (0,0) of your display is the upper left hand corner LED;
* the first character starts in column 0; the second in column 8; The leftmost bit to display is in bit-6 of each byte and bit 7 (MSb) is not used;
* you'll use zero-based coordinates.

The 'Y' coordinate is pretty straight-forward - byte-0 is the first byte. The 'X' coordinate is found by subtracting the position of the bit of interest from 6, and maybe adding 8, since bit-6 goes into column-0 or column-8 for the left or right character, respectively.
> 0 votes

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


# Question
Title: Rotary encoder on Uno and interrupts issue
This question is regarding a project using an Arduino Uno.

I have one of these quadrature rotary encoders.

I'm using a slightly modified version of the code from the article, Quadrature Encoder too Fast for Arduino (with Solution), which uses a library called digitalwritefast.

My version of the code on pastebin \- I modified to use different pins for the Uno and a single encoder:

```
#include <digitalWriteFast.h>  // library for high performance reads and writes by jrraines

#define c_LeftEncoderInterrupt 0
#define c_LeftEncoderPinA 2
#define c_LeftEncoderPinB 3

volatile bool _LeftEncoderBSet;
volatile long _LeftEncoderTicks = 0;

void setup()
{
  Serial.begin(115200);
  pinMode(c_LeftEncoderPinA, INPUT);
  digitalWrite(c_LeftEncoderPinA, LOW);
  pinMode(c_LeftEncoderPinB, INPUT);
  digitalWrite(c_LeftEncoderPinB, LOW);
  attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
}

// Interrupt service routines for the left motor's quadrature encoder
void HandleLeftMotorInterruptA()
{
  _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB);   // read the input pin
  _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
}

void loop()
{
  Serial.print(_LeftEncoderTicks);
  Serial.print("\n");
  delay(20);
}

```

I am attaching output A of the encoder to pin 2 and output B to pin 3.

This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying `c_LeftEncoderPinB` accordingly).

I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).

# Answer
OK embarrassingly it turns out my wiring was wrong! I was going astray as it was working in both directions as described, even when only one of the outputs was connected, as long output B was connected to an interrupt. Once the wiring was sorted everything worked perfectly, in both directions, using just one of the interrupt ports.
> 0 votes

# Answer
When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.

What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.
> 2 votes

# Answer
My first thought is that something else is off because there is no reason that shouldn't work. It will of course only count 1/4 of the ticks since that's how it was designed to work for very fast motors. I can't comment yet but to Gerben above, I think it is meant to be bidirectional as indicated by the ternary operator. My guess is the problem is with the digitalReadFast library and I would be interested to know if this works when using digitalRead() instead.

My second thought is that this is usually not the best way to do things. Firstly, you would need a really fast motor for the read fast function to matter. Secondly, you're sacrificing resolution by only using one interrupt instead of two. The more generally accepted method is to attach both pins of the encoder to an interrupt. Alternatively, you could use pin change interrupts which allow any pin to be used as an interrupt. However, there are only 3 interrupt service routines on the Uno, one for each port of pins. Whenever one pin on that port triggers, the ISR triggers and you need to keep track of the pin states in order to do anything with it. Here's a good example of the first and info on the second method.
> 0 votes

---
Tags: arduino-uno, rotary-encoder
---


# Question
Title: Many "expected `)' before ';' token" errors
As the title suggests, I have many "expected \`)' before ';' token" errors. The issue is, I have this stuff in. So now I am confused, why am I getting this if the things are there.

I am new here and had an issue with adding code, so here is the pastebin link to it: http://pastebin.com/4WXxsXkB

And here is the the pastebin link to the error: http://pastebin.com/QyehP86M

Does anyone understand how this could happen?

# Answer
> 5 votes
You have two #define statements at the top of your code

```
#define trigPin 3;
#define echoPin 2;

```

The way `#define` works is that it replaces every instance of the name with everything after it on the line so `trigPin` is being replaced with `3;` as opposed to `3` as intended.

Fixing this should solve some of your problems.

---
Tags: programming, sketch
---


# Question
Title: Flashing a ATmega328 that came from an Arduino to not use an external oscillator
I have a ATmega328p chip from a kit that was supposed to be an Arduino compatible thing. I decided to go beyond Arduino and try to program the chip directly. I setup an UNO as an Arduino ISP, more or less like the image here, but added some LEDs to pins 8, 9 and 10 for feedback.

This image has this caption.

> Because no external clock source is connected, the ATmega must be configured to use its internal clock.

I think this chip was flashed with whatever tells it to use an external oscillator. And I do not have an external oscillator.

So how can I tell the chip to again use an internal oscillator when using an UNO as my programmer?

```
» avrdude -p m328p -c avrisp -b 19200 -P /dev/cu.usbmodem1d11121

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

I assume a device id of zero means the chip is not responding with data? because it's core is not cycling?

Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

# Answer
> 5 votes
> Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

Yes, yes you do.

Pick up a 8-16MHz crystal (*not* an oscillator) and two 15pF capacitors and use **very, very short** wires to connect them to the chip as shown in the "System Clock and Clock Options" section of the '328P datasheet. You will then be able to reprogram the fuses using AVRDUDE.

# Answer
> 1 votes
Even though an answer has been accepted, I just want to add for future viewers that you can google for arduino breadboard internal oscillator and get the text to copy into the boards.txt file. That will allow you to use the Arduino IDE to burn the fuses. You will be able to find versions to run at both 8mhz and 1mhz.

Also, if you have an extra Uno laying around, you could always pop the chip in there and reset the fuses, then take it out and use it on a breadboard.

---
Tags: avrdude, oscillator-clock
---


# Question
Title: TCS3200 color sensor not reading with delay lower then 4000 ms using TimerOne.h
I'm trying to get the color sensor TCS3200 to give color values with a delay lower than 4000 ms. I've found a library to interface the TCS3200 from this link.

I've modified the code to serve my needs and its works fine, almost! The before mentioned library uses TimerOne.h, which can not accept a delay lower than 4000 ms.

My question is therefor, if it is somehow possible to modify my code, so I can lower the delay?

This is my code:

```
#include <TimerOne.h>

#define S0     6
#define S1     5
#define S2     4
#define S3     3
#define OUT    2

int   g_count = 0;    // count the frequecy
int   g_array[3];     // store the RGB value
int   g_flag = 0;     // filter of RGB queue
float g_SF[3];        // save the RGB Scale factor

// Init TSC230 and setting Frequency.
void TSC_Init()
{
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(OUT, INPUT);

  digitalWrite(S0, LOW);  // OUTPUT FREQUENCY SCALING 2%
  digitalWrite(S1, HIGH);
}

// Select the filter color
void TSC_FilterColor(int Level01, int Level02)
{
  if(Level01 != 0)
    Level01 = HIGH;

  if(Level02 != 0)
    Level02 = HIGH;

  digitalWrite(S2, Level01);
  digitalWrite(S3, Level02);
}

void TSC_Count()
{
  g_count ++ ;
}

void TSC_Callback()
{
  switch(g_flag)
  {
    case 0:
         TSC_WB(LOW, LOW);              //Filter without Red
         break;
    case 1:
         g_array[0] = g_count;
         TSC_WB(HIGH, HIGH);            //Filter without Green
         break;
    case 2:
         g_array[1] = g_count;
         TSC_WB(LOW, HIGH);             //Filter without Blue
         break;
    case 3:
         g_array[2] = g_count;
         TSC_WB(HIGH, LOW);             //Clear(no filter)
         break;
   default:
         g_count = 0;
         break;
  }
}

void TSC_WB(int Level0, int Level1)      //White Balance
{
  g_count = 0;
  g_flag ++;
  TSC_FilterColor(Level0, Level1);
  Timer1.setPeriod(1000000);             // set 1s period
}

void setup()
{
  TSC_Init();
  Serial.begin(115200);
  Timer1.initialize();             // defaulte is 1s
  Timer1.attachInterrupt(TSC_Callback);
  attachInterrupt(0, TSC_Count, RISING);

  delay(4000);

  for(int i=0; i<3; i++)
    Serial.println(g_array[i]);

  g_SF[0] = 255.0/ g_array[0];     //R Scale factor
  g_SF[1] = 255.0/ g_array[1] ;    //G Scale factor
  g_SF[2] = 255.0/ g_array[2] ;    //B Scale factor

  Serial.println(g_SF[0]);
  Serial.println(g_SF[1]);
  Serial.println(g_SF[2]);
}

void loop()
{
  g_flag = 0;

    int R = int(g_array[0] * g_SF[0]);
    int G = int(g_array[1] * g_SF[1]);
    int B = int(g_array[2] * g_SF[2]);

    if((R>245) && (R<265) && (G>245) && (G<265) && (B>245) && (B<265))    // White
    {
      Serial.println("Color is white");
    }else if((R>24) && (R<44) && (G>56) && (G<76) && (B>95) && (B<115))  // Blue
    {
      Serial.println("Color is blue");
    }else if((R>56) && (R<76) && (G>107) && (G<127) && (B>80) && (B<100))  // Green
    {
      Serial.println("Color is green");
    }else if((R>171) && (R<191) && (G>154) && (G<174) && (B>71) && (B<91))  // Yellow
    {
      Serial.println("Color is yellow");
    }else if((R>77) && (R<97) && (G>46) && (G<66) && (B>43) && (B<63))  // Brown
    {
      Serial.println("Color is brown");
    }else if((R>39) && (R<59) && (G>38) && (G<58) && (B>36) && (B<56))  // Brown dark
    {
      Serial.println("Color is brown dark");
    }else if((R>20) && (R<40) && (G>43) && (G<63) && (B>48) && (B<68))  // Turkis
    {
       Serial.println("Color is turkis");
    }else if((R>39) && (R<59) && (G>77) && (G<97) && (B>55) && (B<75))  // Green
    {
       Serial.println("Color is green");
    }else
    {
      Serial.print("Red = ");
      Serial.println(R);
      Serial.print("Green = ");
      Serial.println(G);
      Serial.print("Blue = ");
      Serial.println(B);

    };

   delay(4000);
}

```

I've searched all over the net and didn't find any good solutions, where I can still specify the colours by hex degree.

All help would be highly appreciated!

# Answer
You can increase the frequency (x10) by setting S0 HIGH and S1 LOW. Then you can change the timerone frequency from once a second to once every 100ms (Timer1.setPeriod(100000);). Then you can change your delay to delay(400).

PS I think you only need to wait for a bit over 3 timerone cycles, so delay(350) should also work.
> 2 votes

---
Tags: arduino-uno, sensors, library, timers
---


# Question
Title: Stack arduino, motor shield and lcd shield
I made arduino-stack which consists of arduino r3, robotdf motor shild and robotdf lcd shield. But motor shield and lcd use same pins 4 and 5, so we have a conflict of pins. Can i use other pins?

# Answer
Stack one shield on top of the Arduino itself and connect the other shield using wires. This way you can pick your own pin assignment for the 'external' shield.

Be careful when using a specific library though, sometimes the used pins are hard-coded in the library itself. Modifying the .h and .cpp files for the library is possible, so you could (hard code) assign your own used pins.
> 0 votes

---
Tags: motor, lcd
---


# Question
Title: High frequency audio sampling and storage
I want to use an arduino **duemilanove atmega168** for audio signal processing. I can sample the signal at around 38.5kHz using this code. I want to send the sampled data over the serial to a computer for processing.

* Data acquisition rate: 38.5 kbps (using 8-bit precision)
* Maximum serial communication rate: 115200 bps (I don't know exactly how this relates to the transfer rate of the actual data (without any overheads), but anyhow the limit is 13.94 kbps)
* Arduino flash memory: 16 kB

I would like to transmit around 4-5 seconds of the audio signal to the computer. Is there a way to achieve this?

# Answer
> 3 votes
After doing some reading here Serial.begin(): Why not always use 28800? and looking at the manual for the 168. You should be able to achieve the baud rate you want by directly programming the USAR.

According to the answer there you should be able to use miniterm to keep up with a high baud rate.

As stated there you might run into problems with computer power.

Read chapter 20 here http://www.atmel.com/images/doc2545.pdf.

Basically you can set up the USART speed (UDR0) and the control registers (UCSR0A,UCSR0B and UCSR0C) such that you can send data pretty fast.

Let me know if you can't access that link and if you need me to explain some more about these things.

---
Tags: serial, audio, signal-processing
---


# Question
Title: How do I activate emulation in the Coddeblocks Arduino IDE
I stumbled upon this question here, so I tried the Codeblocks alternative. After opening an Arduino Project, and leaving all options to default, I ran the Arduino version of the Hello World. A popup opened that requests a serial port to move on. What error did I do?

If more details are needed I'll answer the comments. Thanks in advance!

# Answer
I have not done extensive testing with the simulator but here is what you do open code blocks start a new project. Then under the target choose simulator. See the picture for details.

I just tested it out for the simple program but this looks pretty cool.
> 1 votes

---
Tags: arduino-uno, emulation
---


# Question
Title: Sending Serial Hex Command from Pin 1 (Tx)
Using Arduino Uno with 3.5mm Jack connected to ground and pin 1 for TX

Need to send two commands I want to send 0XAA13FE010113 for Mute on, and 0XAA13FE010012 for Mute off.

Simple Serial Command to turn Monitor Mute on and off every 5 seconds....

tried everything byte character, array, write with hex, print :(

Thx for a helping a rookie I want to impress my team

---

Ideal quick answer below. thx to @martynas

```
uint8_t muteON[] = { 0xAA, 0x13, 0xFE, 0x01, 0x01, 0x13 };
uint8_t muteOFF[] = { 0xAA, 0x13, 0xFE, 0x01, 0x00, 0x12 };
....
void loop() {
 Serial.write( muteON, sizeof(muteON) );
 delay(5000);               // wait for 5 second
 Serial.write( muteOFF, sizeof(muteOFF) );
 delay(5000);               // wait for 5 second
}

```

# Answer
there are 6 bytes just make

```
byte muteON[] = {0xAA,0x13,0xFE,0x01,0x01,0x13};
byte muteOFF[] = {0XAA,0x13,0xFE,0x01,0x00,0x12};
...
/* To send mute ON comand */
for(byte i =0;i<sizeof(muteON);i++)(Serial.write(muteON[i]));
/* To send mute OFF comand */
for(byte i =0;i<sizeof(muteOFF);i++)(Serial.write(muteOFF[i]));

```
> 1 votes

---
Tags: arduino-uno, serial, programming, sketch
---


# Question
Title: How would I establish a serial connection with python without using the serial monitor?
How would I establish a serial connection with python without using the serial monitor?

What I want to do is give my python script some input and have the arduino do something (blink for example)

I also want to be able to read in data with the arduino to give it to my python script.

What modules for python would be useful? I'm just starting out and don't have much of an idea for this one.

I am using a windows7 machine with python 2.7.6 and have an UNO board and a Leonardo board that I want to be able to use.

# Answer
This question is about **Python** not Arduino... Before asking here please ask **GOOGLE**

Anyway...

This is the answer Arduino and Python

Python code:

```
## import the serial library
import serial

## Boolean variable that will represent
## whether or not the arduino is connected
connected = False

## open the serial port that your ardiono
## is connected to.
ser = serial.Serial("COM11", 9600)

## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True

## Tell the arduino to blink!
ser.write("1")

## Wait until the arduino tells us it
## is finished blinking
while ser.read() == '1':
    ser.read()

## close the port and end the program
ser.close()

```

Arduino code:

```
// Open a serial connection and flash LED when input is received

void setup(){
  // Open serial connection.
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Serial.write('1');
}

void loop(){
  if(Serial.available() > 0){      // if data present, blink
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    delay(500);
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    Serial.write('0');
  }
}

```
> 1 votes

---
Tags: arduino-uno, serial, arduino-leonardo, python
---


title: Attiny13 + Arduino

text:
# Question
Title: Attiny13 + Arduino
I started my first try in programming an ATTINY13 with my Arduino 2560.

Everything seemed fine, however when I wanted to run the blink example, my LED did not blink, it keeps lighting.

I am using 5V as input voltage.

I did not change the blink example except for the correct pin number.

All the wiring seems correct, when I change the pin number the LED stays dark, so my program is arriving propperly on the ATTINY.

If I start playing with the delays (delaymicroseconds) I get the LED to become darker.

The documentation of the ATTINY13 (www.atmel.com/images/doc2535.pdf) mentions a maximum clock frequency of 20MHz. When I choose the ATTINY13 from the Arduino IDE board menu it is listed with a 9.6MHz clock.

Could this be a reason? How can I adjust or take care of that?

----------- Edit:

I was starting with the default blink example (`delay(1000)`).

I played with both, the normal `delay` and the `delayMicroseconds`.

The following codes dimmed the LED:

```
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  digitalWrite(3, HIGH);
  delayMicroseconds(10);
  digitalWrite(3, LOW);
  delayMicroseconds(1000);
}

```

Which makes me believe the LED is blinking very fast. A similar sketch with normal `delay` does not make the LED dim:

```
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  digitalWrite(3, HIGH);
  delay(1);
  digitalWrite(3, LOW);
  delay(100);
}

```

And as mentioned with the default blink sketch the LED nothing happens as well.

I also made the delay a ever increasing variable to see if something is happening, no luck. And I have 2 ATTINYs to test, same result for both...

--- Edit2:

Another try:

```
int led = 3;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
  delayMicroseconds(100);
  digitalWrite(led, LOW);
}

void loop() {
}

```

Now I moved switching the LED on and off into the setup function. Strangely enough, by changing the delay between 1000 and 100 micro seconds, the LED gets lighter and darker...

---- Edit 3:

Here is my circuit:

And this is the ATTINY specific code I added to the Arduino IDE:

```
attiny13.name=ATtiny13 (internal 9.6 MHz clock)
attiny13.bootloader.low_fuses=0x7a
attiny13.bootloader.high_fuses=0xff
attiny13.upload.maximum_size=1024
attiny13.build.mcu=attiny13
attiny13.build.f_cpu=9600000L
attiny13.build.core=arduino:arduino
attiny13.build.variant=tiny8

```

# Answer
> 1 votes
I switched to a different ATTINY 13 driver and core definition in the Arduino IDE and this made it work.

Unfortunately by playing around I lost track of the old driver.

I am now using smeezkekitty's core13 which I found here: http://elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/

# Answer
> 2 votes
> The documentation of the ATTINY13 (www.atmel.com/images/doc2535.pdf) mentions a maximum clock frequency of 20MHz. When I choose the ATTINY13 from the Arduino IDE board menu it is listed with a 9.6MHz clock.
>
> Could this be a reason? How can I adjust or take care of that?

I don't think it is the reason, as it is totally fine to underclock your chip. In fact, most Arduino boards are underclocked. In fact, the Arduino Uno's chip can do 20MHz, but it is only ran at 16MHz.

As mentioned in the comments, your oscillator might be off. *However*, it should still blink. If you're saying changing the pin makes it go dark, then some code is running.

My guess is your delay is way to short. You said you were using `delayMicroseconds()`. Emphasis on *microseconds*, not milliseconds. (1 second = 1,000 milliseconds; 1 millisecond = 1,000 microseconds) If you meant to be using milliseconds, it is very possible that you are changing the power to the LED at 1,000 times a second, instead of 1. This would make the LED dimmer than directly to power, but it would still appear lit.

Try this code:

```
void setup() {
  pinmode(LEDPIN, OUTPUT);
}

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

```

Of course, replace the `LEDPIN` with the right value.

# Answer
> 1 votes
Pin 1 is active low reset. Try connecting it to 5V to run the program.

---
Tags: arduino-mega, led, attiny
---


title: Servo limitations vs SoftwareServo

text:
# Question
Title: Servo limitations vs SoftwareServo
I heard that Servo library cannot send and receive from other arduinos without inturrupting the timer and messing up the motors. SoftwareServo is supposedly the answer to this. Is this true? Neither libraries are working for this problem at the moment.

# Answer
> 1 votes
I'm not sure which SoftwareServo library you are talking about, but with regards to the built in "Servo.h", no, it will not disrupt the arduino's other communication abilities, and they will not disrupt it.

I've used servos simultaneously with Serial, I2C, and SPI before and never had any problems.

The servo library does use a timer, but it will only conflict with an external library or code that uses the same timer. Which timer it uses depends on the board, just look in libraries/Servo/src/avr/ServoTimers.h to see which it uses, in what order as they fill up. Filling one up takes effort though, by default it puts up to 12 servos on each timer. The processing overhead is very low since they only update at 50Hz, so that will not become a problem.

---
Tags: servo
---


# Question
Title: Using XBee and OLED screens with Timer Interrupts
I have an Arduino board with a sensor, an OLED screen and an XBee module. I've setup the timer interrupts in timer1 to sample the sensor every one second. I've done the following:

* tried to update the OLED screen with the reading and it works.
* tried sending the reading from inside loop over XBee and it works.
* tried doing both of the above and the Arduino seems to shut down after a bit.
* tried sending the reading from inside the timer interrupt handler and it doesn't work.

Are there limitations on what interrupt handlers can do that I'm not aware of? (Other than using time delays)

**Source code**

```
#include <XBee.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

XBee xbee = XBee();
ZBRxResponse response = ZBRxResponse();
ZBTxRequest sensorml_level_0_zbTx = ZBTxRequest(addr64, sensorml_payload_level_0,sizeof(sensorml_payload_level_0));
ZBTxRequest keepalive_level_0_zbTx = ZBTxRequest(addr64, keepalive_payload_level_0,sizeof(keepalive_payload_level_0));

union u_tag {
   uint8_t b[4];
   float fval;
}
u;

void setup() {
   display.begin(SSD1306_SWITCHCAPVCC);
   Serial.begin(9600);
   xbee.setSerial(Serial);
   noInterrupts();
   TCCR1A = 0;
   TCCR1B = 0;
   TCNT1  = 0;
   OCR1A = 62500;
   TCCR1B |= (1 << WGM12);
   TCCR1B |= (1 << CS12);
   TCCR1B |= (1 << CS10);
   TIMSK1 |= (1 << OCIE1A);
   interrupts();
}

ISR(TIMER1_COMPA_vect){
   reading =  analogRead(SENSORPIN);
   reading = (1023 / reading)  - 1;
   reading = SERIESRESISTOR / reading;
   reading = -0.15784 * reading + 305.17;
   sendObservation(reading,00);
}

void sendObservation(float value, int id){
   char idBuffer[] = "00";
   sprintf(idBuffer,"%02d",id);
   uint8_t frame[] = {'0','1','|','0','0','#','0','0','0','0'};
   frame[3] = idBuffer[0];
   frame[4] = idBuffer[1];
   u.fval = value;
   for (int i=6;i<10;i++){
      frame[i]=u.b[i-6];
   }
   ZBTxRequest request = ZBTxRequest(addr64, frame, sizeof(frame));
   xbee.send(request);
}

```

I skipped most variable declarations to keep the code short.

# Answer
I suspect `send()` is blocking.

`XBee::send()` calls `_serial->flush()` (see code). `Serial.write()` buffers data to be written, sets `transmitting = true`, clears `TXC0` and enables the USART data register empty (DRE) interrupt. Bytes will be sent out when the DRE interrupt triggers. However, since you are currently in interrupt context, this will not happen until your ISR returns. `flush()` spins until `TXC0` is set, but since the DRE interrupt never triggers, it spins infinitely. I am basing this on this code.
> 1 votes

---
Tags: arduino-mega, xbee, interrupt, timers
---


title: Ruby and Arduino over Serial

text:
# Question
Title: Ruby and Arduino over Serial
I'm trying to send data over serial and pick it up in a ruby script. I'm using the serialport gem (https://rubygems.org/gems/serialport) as stated in the Arduino docs (http://playground.arduino.cc/Interfacing/Ruby).

My question is, I'm trying to print out some gyroscope data, particularly the x, y, and z. This is what my arduino sketch looks like:

```
void setup() {
  Serial.begin(9600);
  // ... do some gyro stuff here
}

void loop() {
  gyro.read();

  Serial.print((int)gyro.g.x);
  Serial.print(" ");
  Serial.print((int)gyro.g.y);
  Serial.print(" ");
  Serial.print((int)gyro.g.z);

  delay(500);
}

```

My ruby script is pretty straight forward as well:

```
require "serialport"
port_str = "/dev/tty.usbmodemfa141"
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE

sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
while true do
  message = sp.gets
  if message
    message.chomp!

    puts message
  end
end

```

However, the output that I get is choppy. What I mean by that is that the numbers don't come out as a single line as I intend:

```
52 9
5
250
 -28
 85
25
9 -5
1 69

```

Even if I replace it with "Hello World", it'll come out as:

```
He
llo
Wor
ld

```

or similar.

Any ideas why? Thanks in advance for any help.

# Answer
Firstly, let's look into documentation for Ruby IO#gets:

> Reads the next "line" from the I/O stream; lines are separated by sep ...

Secondly, look into documentation for Arduino Serial.print:

> Prints data to the serial port as human-readable ASCII text ...

Finally, you don't print new line char `\n` in your "arduino sketch" above.

I recommend you to use `Serial.println` in the last line from your sketch:

```
void setup() {
  Serial.begin(9600);
  // ... do some gyro stuff here
}

void loop() {
  gyro.read();

  Serial.print((int)gyro.g.x);
  Serial.print(" ");
  Serial.print((int)gyro.g.y);
  Serial.print(" ");
  Serial.println((int)gyro.g.z);

  delay(500);
}

```
> 1 votes

# Answer
Yes Arduino code is fine although your should use println() as a terminator.

I think you should read the message into a tmpMessage var. If tmpMessage is empty then break out the loop otherwise concatenate tmpMessage into the message var.

Then print the message var after the loop when no more data arrives.

It must be ruby inserting the line breaks when you use puts
> 0 votes

---
Tags: programming, serial, gyroscope
---


title: Unable to upload sketch to Leonardo

text:
# Question
Title: Unable to upload sketch to Leonardo
I'm really at my wits end. For a couple of hours I have been programming a custom board that uses everything as on the Arduino Leonardo. A few hours ago I am not able to upload anymore.

I get the following error:

```
   avrdude: error: buffered memory access not supported.
   Maybe it isn't a butterfly/AVR109 but a AVR910 device?

```

I've tried everything from re-installing the IDE, re-installing the board in Device Manager, changing the COM Port. I really just don't know anymore.

Here is some more data that might be relevant or useful:

```
     Using Port                     :\\.\COM6
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53

```

\[EDIT\] I've now checked the battery (yes with a multimeter), it is fully charged, as it charges when the USB is connected. I've also tried a different computer, along with a different USB cable.

# Answer
> 1 votes
Try this:

First: you must find the COMx used for your "Arduino Leonardo" in the "Device Manager" of Windows.

Second: make double click to see the properties of the device, and go to the "Port configuration tab"

Third: enter in "Avanced Options" and deactivate "Use FIFO buffers", and accept all changes.

---
Tags: uploading, arduino-leonardo
---


title: Arduino Nano and a 3.3v Ethernet shield

text:
# Question
Title: Arduino Nano and a 3.3v Ethernet shield
I plan on purchasing a Nano clone, an Ethernet shield (ENC28J60), an LCD and a DHT22 humidity + temperature sensor. This will be used in a wine cellar to monitor relative humidity and temperature.

The DHT sensor, LCD and Nano all operate on 5V logic. The Ethernet shield does not operate at 5V, but rather at 3.3V.

Does the Nano have a way to connect the two, will they work anyway (probably not), or should I use a CD4050 that is recommended on adafruit?

Any guidance is appreciated; I'm still amazed in what $10 in parts can do.

Also, in regards to the DHT22 sensor, what do I need in terms of a resistor? I've seen some people say you absolutely need a 4.7K resistor on the data pin for "pull up", and others who say it's unnecessary. Can someone give a definite answer, either way?

Edit, wrong link on my nano clone.

# Answer
Just get one with a 3.3v regulator on it. PS logic levels are allowed to be 5v.

DHT22 and LCD will also work fine on 3.3v so, alternatively, you could also get a 3.3v Nano.

The resistor value for the DHT22 depends on the length of wire between the DHT and Nano. Just buy them to be sure, or get a breakout board that already has them on the board (along with a capacitor, which is nice).
> 0 votes

---
Tags: sensors, shields, lcd, arduino-nano, ethernet
---


# Question
Title: Sample code for using adafruit servo shield?
I would like to control 16 motors with a servo shield, however, I have found scant to nothing sample code online. The one I was able to find is...strange to say the least

https://github.com/kachok/arduino-libraries/blob/master/Adafruit\_PWMServoDriver/examples/servo/servo.pde

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

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)

uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("16 channel Servo test!");

  pwm.begin();

  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop() {
  // Drive each servo one at a time
  Serial.println(servonum);
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);
  for (uint16_t pulselen = SERVOMAX; pulselen > SERVOMIN; pulselen--) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);

  servonum ++;
  if (servonum > 15) servonum = 0;
}

```

Im used to controlling motors using servo.write, but with the shield, it doesn't seem very intuitive as to how I should control the motors. How does Servomin and Servomax map to 0 degree and 180 degree?

Someone please elucidate!

# Answer
The 2 values SERVOMIN and SERVOMAX define the pulse length, which tells the servo what angle to go to. The example uses 150 for SERVOMIN and 600 for SERVOMAX. When running the code, the servos travel 180 deg. I changed the code to read:

```
#define SERVOMIN  262 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  488 // this is the 'maximum' pulse length count (out of 4096)

```

and the servo now moved only 90 deg. centered at the same place as the original code.

the tutorial provided by Adafruit describes a way to define the movement by angle:

```
pulselength = map(degrees, 0, 180, SERVOMIN, SERVOMAX);

```

found here: https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library

hope this helps
> 2 votes

# Answer
Adafruit's guide for the shield is here: https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library

I'm not sure how much the library you linked and the official one differ. They seem to be used the same way, but you should probably stick with the official one.

You are going to have to use setPWM(pin, on, off) since the arduino is not generating the signals like it would with servo.write(), the arduino is sending commands to a chip on the shield that generates the signals for you.

Adafruit recommends calibrating SERVOMIN and SERVOMAX yourself with whatever brand of servo you plan on using, but those default values should be pretty close.
> 1 votes

---
Tags: arduino-uno, servo, adafruit
---


title: Connect multiple I2C to an Uno

text:
# Question
Title: Connect multiple I2C to an Uno
Is it possible to use more than 1 device that needs to use SDA for I2C with a mini? Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

# Answer
> 3 votes
> Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?

Yes, provided they have unique I2C addresses.

> Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

No. All of the devices must be tied to both SDA and SCL. You may need a smaller resistor depending on how many devices there are; see NXP document UM10204 for details.

---
Tags: i2c, arduino-pro-mini
---


title: Over-the-air upgrades?

text:
# Question
Title: Over-the-air upgrades?
I'd like to be able to upgrade software on an arduino without physically touching the device or stringing a cable. Can it be done?

Will pick wireless protocol that makes that easiest.

# Answer
> 6 votes
The best and easiest solution I've found is to use the Bluefruit EZ-Link from Adafruit. They have a module you plug into the Serial/Power/reset pins (link here) or a shield for the uno (link here). They've also got a great description and how-to guide (link here) that is pretty good. It basically appears as a serial bluetooth link in the arduino IDE and you program it like normal. It has the added benefit of being of use not only for programming, but also for sending and receiving data.

# Answer
> 4 votes
We have implemented remote updates on a Arduino Pro Mini (ATMega328P) by putting a "boot" command into the normal firmware. How it works is:

* The host sends the command "boot" to the remote Arduino.
* The Arduino jumps to the boot loader (program address 0x3C00 for the Pro Mini)
* The host sends the new firmware over the link using avrdude (AVR109 protocol)

This doesn't require a new boot loader or hardware. It is not a good solution for commercial devices though, as if the uploaded firmware is corrupted the board will not be able to be put into boot loader mode without a hard reset.

Some wireless comms devices, such as XBees, have GPIO that can be toggled remotely. Connecting this to the Arduino reset pin will allow the board to be reset into the boot loader instead.

# Answer
> 3 votes
The Arduino Yun can be remotely reflashed (either via wifi or network cable): you'll have to select its IP address under the "Tools \> Boards" menu of the Arduino IDE and then press the upload button as usual.

# Answer
> 2 votes
It's possible to write a bootloader running in RAM (or even in Flash, maybe in a special boot block - depends on the microcontroller).
This bootloader has to be able to establish the wireless communication, understand the protocol and to erase/write Flash memory.
There are basically two approaches for software upgrading:

1. The bootloader looks at startup for a "software upgrade" command. If it is received, it waits for the programming sequence. If it is not received, it starts the application.
2. The application is able to receive such a command and gives control to the bootloader then.

What protocol you choose is almost irrelevant. Just make sure that there are enough resources for keeping it in RAM/Flash. On an Arduino Due - for instance - there are more than enough resources for any such implementation.

# Answer
> 1 votes
Yes, it can be done. Lowpowerlab.com has Moteino which can be programmed OTA.

# Answer
> 1 votes
Spark.io boards are also very nice for OTA programmable Arduino-like devices. I have one and have found it to be fairly easy to work with.

https://www.spark.io/

---
Tags: wifi, bluetooth
---