# Question
Title: Here is my code and i keep getting this error expected primary-expression before'}' token
```
#include <QTRSensors.h>
#define NUM_SENSORS 8
#define TIMEOUT 2500
#define EMITTER_PIN QTR_NO_EMITTER_PIN
QTRSensorsRC qtrrc((unsigned char[]) {10,7,6, 5, 4, 2,16,14},
NUM_SENSORS, TIMEOUT, EMITTER_PIN);

unsigned int sensorValues[NUM_SENSORS];
int dirB = 12;
int speedB = 3;
int brakeB = 8;
int dirA = 13;
int speedA = 11;
int brakeA = 9;
int e=4;
int MzSensor=17;
int xp=4;

void setup() {
delay(500);
int i;
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);
for (i = 0; i < 200; i++)
{
  qtrrc.calibrate();
}
digitalWrite(13,LOW);
Serial.begin(9600);
delay(100);
Serial.println("Robot");
for (i = 0; i < NUM_SENSORS; i++)
{
  Serial.print(qtrrc.calibratedMinimumOn[i]);
  Serial.print(' ');
}
Serial.println();
{
  Serial.print(qtrrc.calibratedMaximumOn[i]);
  Serial.print(' ');
}
Serial.println();
Serial.println();
delay(100);
}
void loop() {
Serial.print('ogeday');
unsigned int position = qtrrc.readLine(sensorValues);
unsigned char i;
for (i = 0; i <NUM_SENSORS; i++)
{
  Serial.print(sensorValues[i] * 10 / 1001);
  Serial.print(' ');
}
Serial.print("   ");
Serial.println(position);
delay(200);
if (digitalRead(MzSensor)==0) {
  while(digitalRead(MzSensor)==0) {
    digitalWrite (dirA, HIGH);
    analogWrite(speedA, 76);
    digitalWrite(dirB, HIGH);
    analogWrite(speedB, 76);
    xp == 5;
    Serial.println("durdu");
    delay(100);
  }
  delay(800);
  Serial.println("CIKTI");
}
else
if (position >= 3250 &&position <= 3750)
{
  if(sensorValues [1] < 500 )
  {
    e=7;
    xp=3;
  }
  if(sensorValues [8] < 500 )
  {
    e=1;
    xp=3;
  }
  if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
  Serial.println("ILERI"),
  digitalWrite(dirA, HIGH),
  digitalWrite(brakeA, LOW),
  analogWrite(speedA, 72),
  digitalWrite(dirB, HIGH),
  digitalWrite(brakeB, LOW),
  analogWrite(speedB, 72),
  e=4,
  xp=3,

  delay (1),

}

 else if (position > 4050 || sensorValues [8] <500)
  {
    Serial.println("EN SAG");
    digitalWrite(dirA, LOW);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 19);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 45);
    e=1;
    xp=3;
  }
  else if (position <- 4050 &&position >- 3900)
  {
    Serial.println("SAG");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 51);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 60);
    e=1;
    xp=3;
  }
  else if (position >= 2950 &&position <= 3100)
  {
    Serial.println("SOL");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 60);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 51);
    e=7;
    xp=3;
  }
  else if (position < 2950 || sensorValues [1] < 300 )
  {
    Serial.println("EN SOL");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 45);
    digitalWrite(dirB, 45);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 19);
    e=7;
    xp=3;
  }
  else if (e==7) {
    Serial.println("Cizgi SOLLL");
    if (xp!=1){
      digitalWrite(dirA, LOW);
      digitalWrite(brakeA, LOW);
      analogWrite(speedA, 30);
      digitalWrite(dirB, LOW);
      digitalWrite(brakeB, LOW);
      analogWrite(sppedB, 30);
      xp=1;
      delay(1);
    }
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 66);
    digitalWrite(dirB, LOW);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 48);
    e=7;
  }
  else if (e==1) {
    Serial.pirntln("{Cizgi SAGGG");
    if(xp!=1) {
      digitalWrite(dirA, LOW);
      digitalWrite(brakeA, LOW);
      analogWrite(speedA, 30);
      digitalWrite(dirB, LOW);
      digitalWrite(brakeB, LOW);
      xp=1;
      delay(1);
    }
    digitalWrite(dirA, LOW);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 48);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 66);
    e=1;
  }
  else if (e==4) {
    Serial.println("ILERI GIDIYOR");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 30);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 30);
    e=4;
  }
  //delay(300)
}

```

# Answer
> 3 votes
Change `delay (1),` to `delay (1);`

# Answer
> 1 votes
In this part:

```
if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
Serial.println("ILERI"),
digitalWrite(dirA, HIGH),
digitalWrite(brakeA, LOW),
analogWrite(speedA, 72),
digitalWrite(dirB, HIGH),
digitalWrite(brakeB, LOW),
analogWrite(speedB, 72),
e=4,
xp=3,

delay (1),

```

There's a lot of ',' instead of ';'. Change then to ';'.

Also, the 'if' is incomplete. Check the 'if' statement.

# Answer
> 0 votes
```
if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
  Serial.println("ILERI"),

```
1. `if()` condition is not complete
2. `;` not `,`

A little advice. Use functions so that your code is easy to read and easy to debug (looking for errors).

Something like :

```
void func(String text, boolean mDirA, boolean mBrakeA, int mSpeedA,
    boolean mDirB, boolean mBrakeB, int mSpeedB){

    Serial.println(text);
    digitalWrite(dirA, mDirA);
    digitalWrite(brakeA, mBrakeA);
    analogWrite(speedA, mSpeedA);
    digitalWrite(dirB, mDirB);
    digitalWrite(brakeB, mBrakeB);
    analogWrite(speedB, mSpeedB);

}

```

---
Tags: arduino-uno
---


title: Weight sensor / load cell not working

text:
# Question
Title: Weight sensor / load cell not working
I just got all my parts together that I needed for my project and put everything together like said here: https://web.archive.org/web/20140303140445/http://cerulean.dk/words/?page\_id=42 but the serial monitor gives me all random outputs:

```
analogValue: 865.52
             load: 43.27584
analogValue: 865.54
             load: 43.27717
analogValue: 865.50
             load: 43.27517
analogValue: 865.43
             load: 43.27151
analogValue: 865.32
             load: 43.26601
analogValue: 865.45
             load: 43.27255
analogValue: 865.45
             load: 43.27241

```

So I can't calibrate everything to even continue, what is wrong? I checked all my connections like 50 times and everything is wired up like shown in the tutorial.

Here are my parts:

Thank you in advanced, Greetings

# Answer
> -1 votes
You might be driving the amplifier to its limits, and getting a value at its limits.

The INA125 isn't a rail-to-rail amplifier, so if you are wiring it up to ground and +5V as described, its output is limited to be between 0+1V=+1V and 5V-1.7V=+3.3V, so it would be easy to saturate it and bump up against those limits and give you a constant value.

If you are using the 10ohm resistor as the INA125 gain, the gain G=4+60000/10=6004x so the input voltage difference needs to be between 0.00016V and 0.00055V volts to be unsaturated within its output linear range. If it is outside of those limits, the amplifier will act as a comparator.

You could check this by putting a voltmeter on the output of the amp and measuring what is is and if it changes. If it isn't near 2.5V when the scale is unloaded and is saturated at the limit of the amp, then you might need to balance the loadcell closer to zero so it doesn't peg the scale, or reduce the amplification.

---
Tags: sensors
---


# Question
Title: What type of sensor could I use to determine the mass of a small object (under 1 kg)?
I'm building a robot that needs to pick up a piece of material and then determine its mass. My robot will retrieve the material using a scoop at the ended of a mechanized arm. Once the material is in the scoop, the arm will tilt upwards until the material slides down the arm and into the chassis. I hope to weigh the material while its in the chassis, but I'm not sure how to do this. I've found that load sensors are useful for taking masses, but I'm not clear on how they're implemented. For example, I've found load beam cells, but how would I implement one in my design? Does it require a metal plate of some sort (like a weighing pan) on top of it like a laboratory scale? The sensor must be able to communicate with an Arduino.

My robot needs to be under 6 lbs and have a footprint of 35 x 35 cm. Thanks!

# Answer
Just a little brainstorming:

If you have a spring, then you can easily calculate the physical force (mass) needed to stretch the spring to a certain extent. The law is called: Hookes's Law \- you could then just measure the increase in distance between the initial position and the position with load. Use a servo or any distance measure.
> 1 votes

# Answer
A load beam cell would be good. Put it as one leg of your robot, and calibrate it with the arm in a particular location dangling over the cell. You'd need the beam load cell, and an instrumentation op amp, or HX711 (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide) to do the interfacing.

Also good would be the cells from a bathroom scale as the four feet -- you could hook them up like https://electronics.stackexchange.com/a/199907/30711 or https://electronics.stackexchange.com/a/199470/30711

One thing cool about using the robot feet for measurement is that you could calibrate for more sensitive measurements while reaching far from the base, and rougher measurements closer. You could also calculate how far you could reach without toppling over.
> 0 votes

---
Tags: arduino-uno, sensors, robotics
---


# Question
Title: Arduino ADC Reference Voltage if it is Battery Powered
I am looking to possibly monitor battery power to the Arduino using its ADC. This is fairly straight forward and simple (especially if using the Arduino API); however, if the battery is powering the Arduino and is unregulated externally, won't the ADC reference voltage constantly be dropping with the battery? In other words, wouldn't the ADC value would constantly read the same value (the max value) even though the battery would actually be decreasing in voltage?

If this is the case, it would be both inefficient and pointless to measure the battery voltage.

# Answer
> ... won't the ADC reference voltage constantly be dropping with the battery?

Yes, which is why you either use or measure an internal bandgap reference instead.

Use the `analogReference()` function to select a reference appropriate for the board in use. Note that you will need to use a voltage divider to reduce the battery voltage to a value below that of the selected reference if you wish to measure it.

To measure the bandgap voltage instead (using AVCC as a reference and working "backwards") you will need to set `MUX[3:0]` in `ADMUX` to 0b1110 and then perform an ADC reading directly (set `ADSC` in `ADCSRA` and wait until it resets, then read from `ADC[H:L]`).

As always, see the MCU datasheet for details.
> 4 votes

# Answer
@ryeager's link to http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/#comment-71836 has this code for reading the Arduino's battery voltage:

```
long readVcc() {
  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
    ADMUX = _BV(MUX5) | _BV(MUX0);
  #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
    ADMUX = _BV(MUX3) | _BV(MUX2);
  #else
    ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  #endif

  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
  uint8_t high = ADCH; // unlocks both

  long result = (high<<8) | low;

  result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return result; // Vcc in millivolts
}

```

The trick here is that it measures its internal reference of 1.1V using the battery voltage, and then inverts it to calculate the unknown reference voltage.

The ADMUX magic in this code can enable other interesting ADC readings, such as differential measurements, and differential ADC measurements with gain, depending on the component and datasheet.
> 1 votes

---
Tags: arduino-uno, battery, analogread
---


# Question
Title: On the Uno, why does VIN require 7-12 volts and the USB only 5 volts?
I'm just wondering why the VIN would require 7-12 volts when the USB port itself only requires 5 volts? What happens if you power an Uno on VIN with 5 volts?

# Answer
> 3 votes
USB's Vcc pin is assumed to be a stable, 5v supply, and is directly connected to the 5v bus on the Arduino board with no further regulation. Vin is assumed to be an unknown and unregulated voltage in the range of 7-12 volts.

The 7v minimum is a requirement of the design of the on-board voltage regulator which needs the 2v "head room" to maintain its output at 5v. A 5v power supply could be designed with a larger input range, even including voltages less than 5v, but the simple design used on the board covers a range of sources at a lower cost than a higher-performance power supply.

# Answer
> 0 votes
The UNO takes your input power supply (7-12 volts) and then regulates the voltage down to 5 volts. This way, the UNO operates at a constant voltage regardless if your input power supply wanders about from 7 to 12 volts.

The USB port, BY DEFINITION and International Standards, needs to operate at 5 volts.

If you apply 5 volts power supply, the UNO won't be able to regulate to 5 volts. The voltage regulator itself will have a voltage drop, and the UNO will operate at less than 5 volts. The UNO may or may not operate properly. The USB will likely suffer from more problems than the UNO if you apply 5 volts. Good news is that the UNO will not likely suffer permanent damage.

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


title: Powering an Arduino UNO through 5V

text:
# Question
Title: Powering an Arduino UNO through 5V
I have a bench supply which I can use to power a breadboard at 5 V. Is it a bad idea to power the the Arduino by going directly to the 5 V pin? It sounds like both this method, and the USB are unregulated, so there would be no difference. Is it safe? Are there any caveats to this?

> 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

They say they "don't advise it", but why?

# Answer
> 1 votes
They wouldn't advise it because they provide on board regulation. By feeding it directly you're circumventing their own protection. If however, you're providing your own regulated supply there is no reason why you can't supply it directly.

In a perfect environment, USB should already be regulated. However given the cheap imported USB hubs and plug packs that are available on the market, I would certainly argue that a good bench power supply is no problems in this regards.

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


# Question
Title: Suggest me some good seller for Arduino UNO
I want to start a new project with arduino uno and want to make some amazing mini projects, but i am confused that from where should i buy. So please suggest me some affordable robotic stores.

# Answer
> 2 votes
I recently bought some arduino nano V3 on Aliexpress. It cost me €1.75,- so I immediately bought 4 :P arrived within 10 days. Also the arduino uno R3 (non-official) is only €3,-. Worth the try? I would say definitely, because if you need it for a project you want to leave it in not take it out because you have another idea. Hope this helps.

# Answer
> 2 votes
***I would comment, but my rep is not high enough so consider this a comment:***

Welcome to StackExchange. You should maybe take a look at some guidelines on how to ask good questions.

**First of all:** mind your tune! ASAP in capitals is very impolite and implies a request we MUST fulfil - no we don't. Try to use please and thank you and everyone will be happy.

**Second:** this is a Q&A Site to help people now and in the future, so most of the time questions like: where can I buy this or what book is good are not what this is made for because they won't be valid for very long and have been asked many times before (but answers lost their validity as mentioned above).

**and last but not least:** Google it. Ebay, Aliexpress, Amazon... whatever you fancy. There are many Arduino clones for low prices around. I bought a few UNOs for like 6€ each. They work fine.

With that in mind: welcome again. I hope you find many useful answers around.

---
Tags: arduino-uno, robotics, project
---


title: Popen command restarts arduino

text:
# Question
Title: Popen command restarts arduino
So I am trying to make a Mac OSX program with Cocoa that will be able to control my Arduino via serial. I currently have the C command

```
popen("echo 7 > /dev/cu.usbmodem1411", "r");

```

to try to send the number 7 over serial to the Arduino. I know that the path /dev/cu.usbmodem1411 is correct because the Arduino is responding, however it seems to "crash" or simply restart whenever this command is received from the Mac. Sorry this may be a question for StackOverflow, but I thought I would start here.

# Answer
I think the problem is more going to be that you don't have a serial connection to the arduino. ie, if you look in the Arduino IDE, you assign a serial port to the application. When you upload your sketch, a connection is made, the arduino resets (by design) and your sketch is uploaded.

What it appears you are doing here is opening a new connection and sending the character (which is `ASCII`) which in turn sends the arduino into reboot to look out for a sketch being uploaded.

I'm not familiar with `popen` and maybe you can use it and keep the connection open and even monitor the data stream, but I would say instead of writing directly to the device as you've done, use an application that will initialise the port properly (ie open it and leave it open) so that you can continue to use/monitor it.

A quick google search has brought up Mike's PBX Cookbook which has some good info about it. I've personally used `minicom` (a guide for installing minicom) and `CoolTerm`, I have used `Screen` but it was so long ago I don't remember why I moved on.

*edit: I just followed the link submitted by the first commenter (sorry name not available in the edit screen), and although you've responded with "that's not it", it actually is, you just haven't realised it since your `popen` command is actually opening the port and triggering the RTS mentioned in that post*
> 0 votes

---
Tags: serial, c, mac-os
---


# Question
Title: Problem with analog pins' name when trying to connect Arduino board and Processing
I am trying to use Processing with Arduino Uno board to read the change of voltage done by a potentiometer. The code is simple:

```
import processing.serial.*;
import cc.arduino.*;

Serial myport;
Arduino arduino;

color off = color(4, 79, 111);
color on = color(84, 145, 158);
int val=0;
float value=0;
void setup() {
  size(600, 600);
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(0, Arduino.INPUT);
}

void draw() {
  stroke(on);
  value = arduino.analogRead(0);
  println(value);
  ellipse(300,300,value,value);
  delay(100);
}

```

My question is: For analog pins in Arduino IDE one should type A0, A1, ... but here in Processing IDE it is an error to type so. Is it possible that Processing reads the wrong pin? Because in Serial output I always get zero, however, for the same circuit in Arduino IDE the values change as I turn the potentiometer knob. Thanks

# Answer
> 0 votes
(as suggested in comments to bump it down)

your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing

If it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0

---
Tags: processing-lang
---


# Question
Title: How can I see the mySerial.print( ) through the serialmonitor on IDE?
I made an object named "mySerial" like this.

```
SoftwareSerial mySerial(2,3) //pin 2 = RX, pin 3 = TX

```

also I made pin 13 periodically(0.5 seconds) blink(HIGH/LOW), then the signal from pin 13 goes directly to pin 2 and pin 0(basic RX pin of UNO). I connected pin 0,2,13 directly with jumper wire.

and in the setup(), I wrote

```
Serial.begin(9600);

mySerial.begin(9600);

```

and in the loop(), I wrote

```
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);

if(mySerial.available()){
    mySerial.println("mySerial!");
}
if(Serial.available()){
    Serial.println("Serial!");
}

```

when I compile this code and operate arduino, I can only see the "Serial!" on the serialmonitor. I think this means that the pin 0 can recognize the signal but the pin 2 cant' How can I solve this problem?

I can't find what I've missed. Please help me guys!

# Answer
Not the most scientific of approaches, and fundamentally flawed at any rate.

You've toggled the input twice over the period of one second, hardly an emulation of any serial port transmission and so one is letting you know there's been a change of state, the other is letting you know that it hasn't received any valid data.

In any case, when you attempt to read the port both will/should correctly give you nothing as a result because there was never anything there to begin with, nor is there anything coming in at the time.

If you want to test serial port comms like this, you are going to have to make a sketch for each scenario and use a real device to test it (like your actual serial port thru the Arduino IDE). Run some test, print the results and upload your second sketch and do it again.

You could even get a bit fancy and have a bit of fun with this and send a command to the arduino to turn off one serial port and turn the other one on, but that's got nothing to do with what you asked, so I won't be writing the code for that here ;)
> 1 votes

---
Tags: softwareserial
---


title: Drawing amperage with Arduino code

text:
# Question
Title: Drawing amperage with Arduino code
I'd like to preface this by saying I'm a complete beginner, but I have learned a ton already on this project, and I feel like I'm almost there.

I'm using an Arduino Uno and an Adafruit motor shield. I am working on a project for mechanical engineering and I need lots of amps for lots of torque for my mechanism. I'm including my code although I know it doesn't work, I haven't had the chance to debug it yet, and I'm really not sure if I'm on the right track.

So I know that it's possible to draw more amperage than is strictly allowed from the Arduino. What I don't know for sure is how to code it. Attached is my preliminary attempt.. I kind of assumed that the maximum speed would be the maximum allowable speed of the motor, regardless of the Arduino's capabilities, and scaled the output `MAXampDrawSpeed` as a function of that. To be specific, my motor can draw up to 20 amps, which would be too much for the Arduino to handle, so I scaled it down accordingly, with 255 being that maximum 20 amp output. I'm not sure if I'm on the right track there.

So the other problem is - the TA for my class made a simplified code reference file, sort of predefining a lot of the things that I manually defined in my code (or tried to at least). I didn't realize this, and when I asked him a question, he sort of shot me down and said "you should use my reference code" -- but his code doesn't compile for me. I had some problems with libraries (I fixed them!), but this isn't a library. It's a reference file, like the tabs up at the top. But it won't even compile for me. My feeling is that I may have annoyed him with my many many stupid questions up until this point and he's just kind of like "girl, get it together"... So the question there is -- am I almost there with my track or should I figure out what's wrong with his code and try to fix it his way so that I can ask him questions without being such a bother to him? And also is that likely to be a hindrance on drawing the extra amperage that I really really want? I am prepared to use heat dissipation methods as are necessary, and any advice you could give me there would also be appreciated.

If you need any more information, about my mechanism or anything I'd be glad to share that as well. I'm parallel mounting one motor to the four dc motor mounts on my Arduino in order to draw maximum current in that way as well. I have two switches controlling the output, one of the switches will engage the program for the maximum distance competition and the other for the accuracy competition.

So again, this code isn't right. I haven't even started on debugging it, because I didn't want to waste my time. Maybe you'll be able to follow my logic. I know there aren't many notes. If you need me to add notes for clarity I would also be glad to take the time to do that.

Thanks!

```
#include <Stepper.h>
#include <AccelStepper.h>
#include <Servo.h>
#include <Adafruit_MotorShield.h>
#include <Wire.h>
#include "Arduino.h"

#define STEP_TYPE_1   SINGLE
#define STEP_TYPE_2    SINGLE
#define STEPS_1    200
#define STEPS_2    200

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);
Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  int i = analogRead(A0); //Reads the value on the analog pin and saves     this as variable "i"
  AFMS.begin(); //Initializes the motorshield board
  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;

  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0,HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1,HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
}

void loop()  {
  int distancepin = 0; //Just integer quantities, i like to have too     many of them
  int accuracypin = 0;
  int inPin1 = 0; //switch pin values
  int inPin2 = 0;
  int MAXampDrawTime = 75;
  int MAXampDrawSpeed = 178;
  int NORMampDrawTime = 225;
  int NORMampDrawSpeed = 61.2;
  int DrawTime = MAXampDrawTime+NORMampDrawTime;
  int ServoTime = 450;
  long previousMillis =0;
  long intervalMAXamps = 100;
  long intervalNORMamps = 400;
  DC1->setSpeed(MAXampDrawSpeed);
  DC2->setSpeed(MAXampDrawSpeed);
  DC3->setSpeed(MAXampDrawSpeed);
  DC4->setSpeed(MAXampDrawSpeed);
  inPin1 = digitalRead(A0);
  inPin2 = digitalRead(A1);
  if (inPin1 == HIGH){
    unsigned long time_zero = millis();
    unsigned long current_time = millis();
    digitalWrite(1,HIGH); //turn motor on to maximum draw amperage
    digitalWrite(2,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(4,HIGH);
    while((millis()-time_zero)<(400000)){
      if( millis() >= (time_zero+NORMampDrawTime)){
      DC1->setSpeed(NORMampDrawSpeed); //set motor on to normal draw     amperage
      DC2->setSpeed(NORMampDrawSpeed);
      DC3->setSpeed(NORMampDrawSpeed);
      DC4->setSpeed(NORMampDrawSpeed);
      digitalWrite(1,HIGH); //turn motor on to normal draw amperage
      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
      digitalWrite(4,HIGH);
    }
    if ( millis() >= (time_zero+DrawTime)); {
      digitalWrite(1,0); //turn off motors
      digitalWrite(2,0);
      digitalWrite(3,0);
      digitalWrite(4,0);
    }
    if (millis() >= (time_zero+ServoTime));{
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }
}
if (inPin2 = HIGH);{
  int MAXampDrawTime = 75;
  int MAXampDrawSpeed = 59;
  int NORMampDrawTime = 225;
  int NORMampDrawSpeed = 20;
  int DrawTime = MAXampDrawTime+NORMampDrawTime;
  int ServoTime = 250;
  unsigned long previousMillis =0;
  unsigned long intervalHIamps = 100;
  unsigned long intervalNORMALamps = 400;
  DC1->setSpeed(MAXampDrawSpeed);
  DC2->setSpeed(MAXampDrawSpeed);
  DC3->setSpeed(MAXampDrawSpeed);
  DC4->setSpeed(MAXampDrawSpeed);

  unsigned long time_zero = millis();
  unsigned long current_time = millis();
  digitalWrite(1,HIGH);
  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
  digitalWrite(4,HIGH);
  while((millis()-time_zero)<(500)){
  if( millis() >= (time_zero+MAXampDrawTime)){
    DC1->setSpeed(NORMampDrawSpeed);
    DC2->setSpeed(NORMampDrawSpeed);
    DC3->setSpeed(NORMampDrawSpeed);
    DC4->setSpeed(NORMampDrawSpeed);
    digitalWrite(1,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(4,HIGH);
  } else( millis() >= (time_zero+DrawTime)); {
    digitalWrite(1,0);
    digitalWrite(2,0);
    digitalWrite(3,0);
    digitalWrite(4,0);
  }
  if (millis() >= (time_zero+ServoTime));{
    int  time_check = millis();
    while (millis() - time_check < 400000) {
      inPin1 = digitalRead(A0);
      if (inPin1 == HIGH ) {
        Servo1.write(0);
        delay(400);
        Servo1.write(90);
      }
    }
  }
}
}}

```

# Answer
> 1 votes
Firstly your formatting is horrible, but that's probably just the this editor, if it isn't please fix it.

In loop() you are wasting time if you are re declaring constants, move them outside the loop.

Why have you got 4 on switches? Could you not gang them altogether? Join the wires and use just one pin?

you are repeating blocks of code, break these out into functions, this means less code to debug. I.e. SetMotorSpeed.

```
If (inPin2 = HIGH)

```

This will always be true, because an assignment is C\C++ always returns true, you meant ==

You TA is being paid to help you, don't be afraid to p##s them off, it's there job to get p'd off at students, and their choice. At least you are doing it by asking questions not d##king around. That said the most likely cause of you problems with his example is missing libraries or IDE version differences. Or even library versions, if you add the first 5 errors as a comment I might be able to point you in the right direction.

# Answer
> 0 votes
I'm going to echo what Matt said but you have way too many constants declared like variables.

A constant in C should be done like this

```
#define MYCONSTANT 666

```

right at the top of your code and outside of any setup loop or main function

Also think about the integer types you are using remember that Arduinos are 8 bit processors only use longs (32bit) where you really really have too and especially do not declare a constant as a long or int the way you have inside your loop.

This

```
int NORMampDrawSpeed = 61.2;

```

is just wrong you are saying that an int is a float, which it cannot be.

I personally avoid using floats altogether in Arduinos but if you must then declare it as a float or a constant (if it is a constant)

```
float NORMampDrawSpeed = 61.2;

```

or

```
#define NORMampDrawSpeed 61.2

```

be very careful when doing arithmetic with floats and ints because it will always return a float unless specifically typecast

better still since your new to programming just don't use them

And yes as Matt said write your own functions for stuff you need to do a lot such as

```
void setMotors( byte on_off ){
    for( uint8_t i=1; i <= 4; i++){
        digitalWrite(i,on_off);
    }
}

```

declare this function above the setup function an use it to turn all your motors on or off (1 or 0) like

```
setMotors(1);

```

# Answer
> 0 votes
You reeeally don't want to draw current through your controller board. It's best to use a transistor power circuit, or 741 op-amp, or relay. Keep your power delivery separate from your control system.

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


title: Convert INT to Array of Strings

text:
# Question
Title: Convert INT to Array of Strings
My sensor outputs an int. I would like this to be an array of strings so I can send it with my 433MHz transmitter.

Converting an int to a string to an array of strings seems to be extremely complicated. I've tried multiple approaches.

The error is always:

> array must be initialized with a brace-enclosed initializer

```
#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;
int mostureSensor = 0;

void setup()
{
  // Initialise the IO and ISR
  vw_set_tx_pin(transmit_pin);
  vw_set_rx_pin(receive_pin);
  vw_set_ptt_pin(transmit_en_pin);
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(1000);   // Bits per sec
}

byte count = 1;

void loop()
{
  // read the input on analog pin 0:
  String sensorValue = String(analogRead(mostureSensor));

  char charBuf[7];
  char msg[7] = sensorValue.toCharArray(charBuf, 7);

  //char msg[7] = {'h','a','l','l','o',' ','#'};
  Serial.println("sending");
  msg[6] = count;
  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  delay(1000);
  count = count + 1;
}

```

# Answer
> 1 votes
toCharArray is a method. It will copy the value from SensorValur to charBuff, it won't return the char array.

Line:

```
 char msg[7] = sensorValue.toCharArray(charBuf, 7);

```

Should be:

```
 sensorValue.toCharArray(charBuf, 7);

```

charBuf will already have the sensorValue copied.

Check more about "toCharArray" method :

https://www.arduino.cc/en/Reference/StringToCharArray

---
Tags: arduino-nano
---


title: Matlab to Arduino communication

text:
# Question
Title: Matlab to Arduino communication
I am doing some computations on Matlab and I need to send those values to an Arduino Leonardo through USB serial connection. I need to send 2 variables which can vary from -400 to +400. I'm saying their values because I was able to do this with small positive values (unsigned byte), but not larger and negative numbers. Please help! Thank you

# Answer
You cannot send larger values because byte only covers the range from 0-255.

To send larger values, you can break your int variable into 2 byte variables. Here's an example:

```
// On Arduino
int myVar = -123;
byte myVar_HighByte = myVar>>8; // get the high byte
byte myVar_LowByte = myVar; // get the low byte
// x86 compatible machines are little-endian so we send the low byte first
Serial.write(myVar_LowByte);
Serial.write(myVar_HighByte);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'int16')

```

Disclaimer: Syntax might not be entirely correct, since I have no MATLAB or Arduino near me when I typed this. But you should get the idea. ;-)

Edit: On second thought, it might be easier to use a pointer.

```
// On Arduino
float myFloat = 3.14159265359;
byte* ptr = (byte*) (&myFloat);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'float')

```

Having said that, you will still have to take care of the endianness, if you use a different microcontroller.
> 1 votes

# Answer
If you want to send your data directly from Matlab to the Arduino, you can try using the "Matlab Arduino Support package". It lets you read/write pins on the arduino directly from Matlab command line or script just like you would with a VERY LOW END Data Acquisition card.

This has the advantage of removing the burden of managing the serial communication. I don't know how it handles large numbers though.

http://www.mathworks.com/hardware-support/arduino-matlab.html?refresh=true
> 0 votes

---
Tags: serial, arduino-leonardo, variables, matlab
---


title: Arduino sketch does not repeat

text:
# Question
Title: Arduino sketch does not repeat
I have a Problem with my code.

My Goal is to receive a Ethernet message via UDP and send the message back via CAN.

It works fine but only with the first packet I send. When I send the same packet again there is no Response as you can see in the screenshot. I´m using the Arduino Due with a Transceiver. The Programm which sends and reads the Messages is Vector Canoe

```
#include "variant.h"
#include "due_can.h"
#include "Arduino.h"

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

EthernetUDP Udp;

void setup() {

Can0.init(250000);
Serial.begin(9600);

Ethernet.begin(mac, ip);
Udp.begin(localPort);

}

void loop() {

    int packetSize = Udp.parsePacket();
    Udp.read(packetBuffer,packetSize);

   if (packetSize)
  {

    int Canframestosend= packetSize/8;    //Divides the Ethernet packet by 8 to match with CAN packet
    int count =0;
    int Rest=packetSize%8;                //Needed if the Ethernet packetsize isn´t a multiple of 8

    for(int j=0;j<=Canframestosend;j++){

    CAN_FRAME NewFrame;                   //CAN frames which are sent
    NewFrame.id=0xFA;                     //ID of the frames
    NewFrame.length=8;                    //Maximum of bytes a Can frame can have

    for (int i=0;i<8;i++){

       NewFrame.data.byte[i] = packetBuffer[count]; //Write the Ethernet info byte by byte on the CAN frames
       count++;
       }
    if(packetSize<count){
      NewFrame.length=Rest;                         //Shortens the last frame to avoid unnessecary zeros
      }
       Can0.sendFrame(NewFrame);

      }

   }
   delay(10);
}

```

Maybe there is an endless Loop but I don´t know which and why.

Hope anybody can help me with that!

# Answer
I'd guess it's in the if(packetsize) logic -- if you get a packetsize of zero, you still try to read into a zero-size buffer and who knows what would happen. Move the read inside the if(){...}

See https://www.arduino.cc/en/Reference/EthernetUDPRead

Also, you want to limit the reading to the UDP\_TX\_PACKET\_MAX\_SIZE size of the buffer, not to the size of the packet.

Update: The UDP\_TX\_PACKET\_MAX\_SIZE is only used in the user code, and nowhere else within the Ethernet Library. You could use a larger buffer if you need to by defining and allocating a larger buffer and specifying its size in EthernetUDP.read() (see https://www.arduino.cc/en/Reference/EthernetUDPRead).
> 0 votes

---
Tags: arduino-due, sketch
---


# Question
Title: How do I set a constant in setup() that I can use in loop()?
I am new with coding, and I was wondering how I could run something once and define it as a constant. Here is my code:

```
int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
int g0 = 9.81*9.8;
int h1 = 48;
int R = 287.06;
int a = -0.0065;

void setup() {
    Serial.begin(9600);
    int p1 = (1.09512*sensorValue2-22.105)*133.3225;
    int t1 = (-0.08126*sensorValue1+65.6597)*274.15;
}

void loop() {
    String t = "Temperature:    ";
    String tt = " Celsius";
    String p = "Preassure:    ";
    String pp = " Pascal";
    float celsius = -0.08126*sensorValue1+65.6597;
    float kelvin = celsius*274.15;
    float pascal = (1.09512*sensorValue2-22.105)*133.3225;
    float height = (t1/a)*((pascal/p1)^((a*R)/g0))-1)+h1;
    Serial.println(t+celsius+tt);
    Serial.println(p+pascal+pp);
    Serial.println(kelvin);
    Serial.println( );
    Serial.println(height);
    delay(1000);
}

```

# Answer
You can't, and there's other things wrong with your code.

```
int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);

```

Calling functions from the global scope is an incredibly bad idea. Those are run *before* the board has been properly initialized, and the results you may get from it are not guaranteed in any way, shape, or form. Instead you must call functions like `analogRead()` from within another function, like `setup()`, or `loop()`.

As for `const` \- a `const` is just that - a constant value that can **never** change. You can only assign a value to it at the moment of creation.

And that means that you can only use it within the *scope* it was defined within. As you can't do that in the global scope (see above) then you *cannot* use a constant.

So just use a normal global variable. It will only change when you tell it to change. Using a `const` only makes sense when you have a *numeric literal* that you want to refer to by name. Using `const` doesn't protect the variable from being changed at run-time by memory leaks, etc, it just protects it from attempts to modify it at compile time - and if possible replace it with the numeric literal that it refers to.

So in summary just use:

```
int sensorValue1;
int sensorValue2;
int p1;
int t1;

void setup() {
    sensorValue1 = analogRead(A0);
    sensorValue2 = analogRead(A1);
    p1 = (1.09512*sensorValue2-22.105)*133.3225;
    t1 = (-0.08126*sensorValue1+65.6597)*274.15;
}
... etc ...

```

**HOWEVER**: Your program methodology is also completely flawed. You read the analog values once, and do calculations with them once, then repeatedly display the same values over and over again.

You **must** perform a *new* `analogRead()` of your sensors every iteration of `loop()` in order to update the values in your variables.
> 6 votes

# Answer
You can define Constants using the "const" keyword. Ex:

```
    const float pi = 3.14;
    const int foo = 12;

```

https://www.arduino.cc/en/Reference/Const
> 1 votes

---
Tags: arduino-uno, code-optimization
---


# Question
Title: Using Arduino for simultaneous lighting effects
I am building a computer for my son (me). I'm trying to spark his interest in computer technology, so my idea is to drive multiple case lighting effects with a microprocessor or controller. I went with the arduino over the pi because of simplicity of the system.

There are several lighting effects I want to drive, simultaneously, and that's where I'm wondering if the arduino is well suited, because the effects need to make use of delay(), and with it being single threaded I'm struggling to figure out how to make each output operate independently.

To give you an idea of what the microcontroller needs to drive simultaneously:

1. Flicker pattern using random delay values for outer case lighting
2. Heartbeat pattern for CPU cooling block
3. Blacklight / UV LED lighting for coolant lines.
4. Strobing LEDs aimed at the fans to make them look stationary.

Trying to run all these effects in a linear loop with delay() operators just doesn't seem to be feasible.

Do I need to get an UNO for each effect? Or is there a way of making these outputs operate independently?

# Answer
> 6 votes
Avoid delay() and use specific times of next actions and compare them to millis(). For a random time, set something like:

```
now=millis();
...
if(nextFlicker < now) {
   toggleFlicker();
   nextFlicker=now+random(10000);
}
if(nextPulse < now) {
   nextPulse=now+ isPulseOn? 100 : 1000 ;
   togglePulse();
}

...

```

If you are running more than the 50 day roll-over time of millis(), you may need some care to handle the overflows. See http://playground.arduino.cc/Code/TimingRollover

For the strobing leds, investigate the timer-controlled outputs outputs.

# Answer
> 2 votes
Base the pattern on time, instead of using delays. E.g. if the current time in seconds if odd, the led should be on. If it's even it should be off. This creates a blinking led effect without using any delay.

Some example code:

```
long seconds = millis()/1000;
if( (seconds % 2)==0 )// even
  digitalWrite(led, HIGH);
else // odd
  digitalWrite(led, LOW);

```

E.g. to have it blink faster, change `1000` to a lower value.

E.g. to make the led be on shorter than of change `%2` to e.g. `%4` (i.e. 1 second on, 3 seconds off)

etc.

---
Tags: arduino-uno
---


# Question
Title: Arduino : distance measurement between fixed points
I am creating a moving robot which needs to know its exact position on the map(known before, start point also known). My ideas were :

* GPS : this is not accurate enough for me, does not work indoors
* Acc + GYRO + Compass(Magnetometer): MPU-9150 : from that values I could compute the position but as small errors are continuously added after a while it becomes very inaccurate

Finally my idea is to put some fixed points into the area and robot can periodically check where they are and compute its position accurate.

Although I did some googlin' I could not find any appropriate sensor pair to do this. My idea is:

* one(more if no other option) sensor on robot covering 360 degrees
* few fixed points which sends a signal; each different one - let's say : I am the point one. I am the point two etc.
* sensor on a robot is receiving those signals and give me some meaningful value e.g. time from which I can compute the distance from each of the fixed point.
* 10+ meters maximum range is fine for me
* must be cheap (less than 30$ for all)

Questions:

* Do you have any idea of such sensor pair ?
* Or other solution which would fit to my needs?

Bonus: * The best would be if the fixed points were passive and just reflected the signal sends from robot - but I have no clue if such a thing exist :-)

Thanks in advance for any answers/comments.

# Answer
Seems to me you are looking for some kinda of SLAM thing. Depending on your knowledge in control theory and your precision goals you can go from simple rotary encoders on wheels to multiple sensor fusion like Extended Kalman filters (example videos). Probably the most precise thing you can have is sensor fusion with LIDAR (can be achieved precisions like 1cm), however the price range is way to far from described.

I would start with a small approach and go from there depending on the results I'd get:

* rotary encoders (easy to calibrate and can be precise enough as a starting point)
* 9DOF IMU (use a Extended Kalman filter or similar to make an AHRS correction). And in this part I have many advices. You have suggested MPU-9150. I'm not familiar with it but looking at datasheet it seems very good, specially because gyro comes factory calibrated. In past I've used razor IMU / GY-85 (adlx345 + ITG3200 + HMC5883L) and gyro was very precise and low noise. Hope Invesense used the same sensor in MPU . First in hardware: Acc are easy to calibrate just use gravity. Gyros are easy to calibrate but hard to do. Why, because it may be hard to get something that spins at constant RPM and know that value. But as I've said, according to datasheet, MPU comes factory calibrated. Magnetometers calibration can be a bit tricky. Bottom line is you get readings from various points of your robot in 3D space. you plot all and you will get an ellipsoid. Then you find a transformation equation that maps the ellipsoid into a perfect sphere take a look this article. Your concerns about Angle random walk can be minimized with kalman filter and similar. This page provides much great information and examples in how to make a good AHRS. Mr. Madgwick wrote a really nice algorithm that implements the IMU filter and have it also written in C (nice for Arduino).

After integrate all things with Kalman and see the results, if things are not good enough, you can add more sensor and provide a better estimation for example: sonars, rangefinders, landmarks with image processing and as suggested also, RSSI and triangulation.

These links might help you in finding your way:
> 2 votes

# Answer
I've been working on this also, and have not found a 100% satisfactory solution. Some ideas I've been throwing around include:

* Using an optical mouse to measure ground distance more accurately. This also subject to cumulative errors.
* Some sort of radio transmitters
* A pulse from a magnet, with a compass - these can be highly directional, and could possibly be strength-based, too.
* I read about one robot competition which had a fixed, overhead camera, picking up infrared LEDs; this is processed by a computer, which would then send the data back (e.g. for bluetooth) to the robot.
* The same infrared camera trick, but reversed: a camera pointing up, looking for fixed constelation of infrared LEDs on the ceiling - I would expect this to require more processing than an Arduino has, possibly a raspberry pi could do the trick?
> 1 votes

---
Tags: sensors
---


# Question
Title: How to make data sent by Python (via serial connection) wait for Arduino to finish current task?
I am trying to make my Arduino micro-controller and my Mac talk together, and I have created a functional serial connection. My computer is sending data to my Arduino, and my Arduino is sending a `1` when it is ready to receive a new piece of data.

I have created an `if-else` statement (Python script below), which is either sending a new line of data to the Arduino or waiting for the Arduino to be ready for receiving a new line of data.

The problem is that `ser.read()` in the first part of the Python script always returns `1`, which means that the script is sending the individual data lines faster than the Arduino connected stepper motors can possible react.

In the Arduino script you can see that I am sending the state-status in the first line of the `serialEvent()` function, which in my world should let the Arduino finish its job, before a new "task" is coming. However, it is for some reason not working. Can anybody help me out here?

**Python script**

```
import os
import time
import serial

# Name of csv file with drawing coordinates
csvFile = "scaled_coordinates.csv"

# Create serial connection
ser = serial.Serial(port='/dev/tty.usbserial-A9005bDh', baudrate=9600)

wd = os.getcwd()
myFile = open(wd + "/coordinates/" + csvFile)

state = '1'

while True: # Exits when there is no more lines to read
    print "test"

    if state == '0': # Wait for Arduino to be ready
        state = ser.read()

    elif state == '1': # Send one more line to Arduino
        line = myFile.readline()
        if not line:
            break
        print line
        ser.write(line)
        state = '0' # Wait for Arduino before reading next line

ser.close
myFile.close

```

**Arduino `loop` function**

```
void loop() {
  serialEvent(); // Call the serial function
  if (coord_complete) {
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
    coord_complete = false;
  }

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

```

**Arduino `serialEvent` function**

```
void serialEvent() {
  // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
  if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
  }

  while (Serial.available() && coord_complete == false) {
    char ch = Serial.read(); // Get new character
    // EDIT : REMOVE THIS LINE //
    Serial.print(ch);

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

    // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;  // Finish coord_string
      x_new = atoi(coord_string);    // Convert to integer
      x_complete = true;             // Change x_complete to true
      index = 0;                     // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string
    // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      //Serial.write('0');
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }

    // Ends while-loop when true
    coord_complete = x_complete * y_complete;
  }
}

```

## Edit

I have changed a bit in the first few lines of the `serialEvent` function (See comments).

Here is a sample of the text file I am reading from:

```
239,275;
1100,275;
300,400;
200,400;
200,300;

```

# Answer
> 0 votes
> If I'm getting things right, your program fails in the above:
>
> when you send the first message in python, you set state = 0. In arduino you enter the serialEvent function and while is triggered. You get the first char and send it through Serial.print (but this char will be send to python!!!). **For the sake of example let's say the first char you get from cvs is '2'**. At this point let's hold on a sec and look what happens in python. State was '0' but as you have used in arduino `Serial.print(ch);` now state will be updated with '2'. This will cause no more triggers of the if-else statements in python.
>
> edit:
>
> By now, and also as a debug, add this lines at your code:
>
> ```
> if state == '0': # Wait for Arduino to be ready
>     state = ser.read()
>     if state != '1':
>         print "state: " + state
>         state = '0'
>
> ```
>
> However if csv file contains '1's values this will also cause a problem. Do you really need that `Serial.print(ch)` in arduino?

**EDIT** The new version since comments Basically if you are trying to do things before new coordinates, you have to do things in a sequential way. You only ask for info after making all the moves. This is the code I've used to test. **Note:** I had to adapt your code because was missing the complete arduino code to test it. So I kinda simulated the motor moving etc with delays. Please adapt to your original code

```
#include <string.h>

bool coord_complete = false;
byte stepper1_disToGo = 0, stepper2_disToGo = 0;
// debug things
int led = 13;
bool led_state = true, x_complete, y_complete;
char coord_string[256];
int index = 0, x_new = 0, y_new = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  memset(&coord_string, 0, sizeof(coord_string));
}

void loop() {

  serialData(); //ask and process more data

  /*
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
  */
  delay(2000); //replace to simulate actions
  stepper1_disToGo = 10;
  stepper2_disToGo = 10;
  coord_complete = false;

  // replaced to simulate
  /*
    // Stay in while loop until steppermotors is done
    while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
    }
  */
  while ((stepper1_disToGo != 0) || (stepper2_disToGo != 0)) {
    stepper1_disToGo --;
    stepper2_disToGo --;
    digitalWrite(led, led_state); // is moving!!!!
    delay(100);
    led_state = !led_state;
  }
}

/*
   you try to use the serialEvent  but the structure of
   your code and the verifications make it act like sequential.
   If you only want to make things after all steps are done there
   is no need for the serialEvent function
*/
void serialData() {
  /*
     This will never be false because you are stuck in the while

    // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
    if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
    }
  */
  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}

```

The structure of your loop should be:

1. ask for data and wait for it
2. Read data and parse it
3. Calculate steps needed
4. move servos till new positions
5. repeat

this should be your new code more or less if no mistakes were made because can't really test this version (is missing the variables declarations setup, includes etc...)

```
void loop() {

  serialData(); //ask and process more data
  // Steps to move from currrent to new point
  target1 = steps(x_current, y_current, x_new, y_new, 1);
  target2 = steps(x_current, y_current, x_new, y_new, 2);

  // Start moving
  stepper1.move(target1);
  stepper2.move(target2);

  // Update current position
  x_current = x_new;
  y_current = y_new;

  // Reset variables
  x_complete = false;
  y_complete = false;
  coord_complete = false;

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

void serialData() {

  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  // we got info!!!
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}

```

---
Tags: serial, python, arduino-duemilanove
---


title: Yun availability

text:
# Question
Title: Yun availability
I am starting a project that may need a lot of Arduino Yuns in the future, but today I found that they are not available on the official Arduino store.

What's the story on the Yun? Is it being replaced by something newer? Also, how can I evaluate the longer-term availability of this board?

In case it's helpful, I need the dual-processor setup, wifi capability, and extra storage of the Yun.

# Answer
> 0 votes
In short: Who knows?!

With all the in-fighting between the two Arduino factions (Arduino.cc and Arduino.org) it's anyone's guess what boards are going to be available this time next year, and of those that are available which of the two factions will be producing and distributing them.

---
Tags: arduino-yun
---


# Question
Title: How to flash the "atmega328" with AVRDUDE?
I have an external device using an **ATmega328**, not a **ATmega328-P** as used by the Arduino Uno.

Now I want to use **AVRDUDE** and an Arduino Uno to flash a hex file on this chip. Therefore I removed the ATmega that came with the Arduino and popped in the one without the "-P".

With the Arduino IDE, it doesn't work, so I tried AVRDUDE:

```
avrdude -c arduino -P com3 -p ATMEGA328 -b 19200 -U flash:r:sdint.hex:r

```

However, I'm doing something wrong here, because it does not work:

> avrdude: stk500\_recv(): programmer is not responding
> avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x00
> avrdude: stk500\_recv(): programmer is not responding
> avrdude: stk500\_getsync() attempt 2 of 10: not in sync: resp=0x00
> ...

**What commandline should I use to flash an Arduino Uno with an ATmega328?**

# Answer
> 0 votes
This seems to be quite a common problem, and there are a number of problems, each with their own solution.

* Make sure you have selected the right chip
* Make sure you have selected the right serial port (when you unplug your board, it should disappear).
* Make sure you do not have anything plugged in to the tx & rx pins (usually 0 and 1).
* Make sure your Atmega chip has a bootloader on it
* Try another cable
* There may be a problem with your computer - try another computer
* If using another helps, try reinstalling the USB serial driver
* Try unplugging the Arduino board, holding down the reset switch, then plugging it in (still holding down reset); continue to hold down reset for about 5 seconds.
* make sure nothing else is trying to use your serial port
* Does your chip have a bootloader? Chips bought as part of an Arduino will, otherwise, it almost certainly doesn't, unless it specifically says (in the description of what you bought).

If it does not have a bootloader (or may not have a bootloader) you will need to set this up. You can either use the instructions here: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard (which I never got working) or you can use an ICSP like the http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VlIY\_2xifXs (which is what I use) - works great. They can be had for a few dollars from China.

---
Tags: arduino-uno, atmega328, avrdude
---


title: Library to correct time for DST

text:
# Question
Title: Library to correct time for DST
I am using a Uno as a data logger with a DS1307 RTC and the following libraries Time.h DS1307RTC.h

The DS1307 does not have any support for DST and neither library includes Time Zone.

Are there any libraries which adjust for DST?

---

I used the `Timezone` module to correct my times for DST. It took a little time to sort it out, so I though I would post the steps I followed.

Customise `WriteRules` for my Timezone. I copied rule from `WorldClock`. NOTE also need to modify Timezone in setup(void) Run `WriteRules.pde` to write rules to EEPROM address 100

Run `TimeRTCSet.pde` to set RTC time to UTC. Start Serial Monitor. In Terminal send time to Arduino

```
date -u +T%s > /dev/tty.usbmodemFA131

```

Run `HardwareRTC.pde` to demonstrate time display in UTC & local

I modified my sketch by including the following code:-

```
#include <Timezone.h>    //https://github.com/JChristensen/Timezone
⋯
Timezone myTZ(100);       //assumes rules stored at EEPROM address 100
TimeChangeRule *tcr;        //pointer to the time change rule, use to get TZ abbrev
time_t utc, local;
⋯
utc = now();
local = myTZ.toLocal(utc, &tcr);

```

# Answer
You could use the Timezone library.
> 3 votes

---
Tags: arduino-uno, time, rtc
---


# Question
Title: Identifying Arduino-compatible board signatures in code
I am developing libraries for compatibility across a number of Arduino/compatible boards. I know that Arduino boards can be identified by the test "#if defined (**AVR\_ATmega328P**)" and compatibles as well: #if defined(**TM4C123GH6PM**). There are a few lists of these IDs on the web but are all outdated. I have searched various cores and library code and do not see where these defines are actually defined.

Nick Gammon's Sketch to detect Atmega chip types identifies the chip type. What I'm looking for the board type to define pin configurations, etc.

Where and in what format are board signatures stored? Is there c++ code that can find the board signature? Does anyone know of a site where these signatures are stored and updated by the Arduino community?

# Answer
In the `boards.txt` file each board has a board type definition, such as:

```
uno.build.board=AVR_UNO

```

When you compile your sketch that is adapted into a "board" define by prepending `-DARDUINO_` to it and adding it to the compilation command line - so that one becomes the same as `#define ARDUINO_AVR_UNO`. You can, of course, test for it with:

```
#ifdef ARDUINO_AVR_UNO
....
#endif

```

The location of the `boards.txt` file varies with different versions of the IDE, but every installed core will have one. Look around in your Arduino program folder in the `hardware` subdirectory.
> 1 votes

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


# Question
Title: Why can't I include a library in another one?
I am trying to create a new library that uses another existing library.

The original library declares a way to create an object called Multiserial that can be created in the main file and the program is correctly compiled.

However, when I include this library in a second one and I try to build the program, then the IDE returns an error that says:

> In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:27:0, from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Stream.h:26, from MultiSerial.h:17, from maqMODBUSmst.h:5, from maqMODBUSmst.c:1: C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Printable.h:25:1: error: unknown type name 'class' class Print;

Even if the library only contains the include of the first one.

# Answer
Nested includes lead to these convoluted error messages and are in general, a PITA for the next reader to follow & understand. It is better practice for the dependent library to test, at compile time, for the existence of its required libraries and for each one found missing, issue:

```
#error DepLibe.h: Missing required include file ReqLibe.h

```

Most .h files guard against multiple-inclusion by

```
#ifndef _REQLIBE_H_
#define _REQLIBE_H_
// library definitions here

```

or some variant of it. DepLibe.h can test for these guard symbols. DepLibe.h should document the dependencies in prominent comments.
> 2 votes

---
Tags: library, wire-library
---


# Question
Title: Arduino due dying after connection, gets hot
I have an Arduino Due (made in Italy) which suddenly (after working nicely for some time) started a new behavior: If I connect it to my computer via USB it is recognized and connects. The "On"-led is turned on but gets darker within seconds until it's off and the connection breaks. This happens with both USB ports. The area around the usb ports gets hot and especially the "504L" next to the reset buttons. (I just have my finger to measure the temperature, so it could also be something else in this corner).

What could have happened to the board? And is there anything I can try to revive it?

Update: @GuitarPicker: It's the object labelled "0105" in your image, so it's probably the F1 fuse. If I connect the top USB, F1 gets hot, if I use the lower usb, F2 is activated.

* There is nothing connected to the board. Before that, I used it to send SPI commands where I might have connected some of the SPI pins in the 6 pin group.
* The board is placed on wood, so there should be no external connection
* No smoke or visible damage.

# Answer
> 3 votes
The "504L" is a 500mA polyfuse. If more than 500mA is attempted to be drawn through the USB port it will get hot which causes the fuse to "trip". When it cools down again it will "reset".

Why is too much current being drawn through the USB port? Well, that's what needs answering to know just why your board is misbehaving:

1. Do you have lots of things plugged into the board - like LED strips, motors, etc?
2. Is the board sat on something metal causing a short circuit? (I did that by having some loose change on my desk once).
3. Have you physically damaged the board and caused some pins of one of the chips to short together?
4. Has the Magic Smoke™ escaped from one of the chips rendering your board broken?

---
Tags: arduino-due
---


# Question
Title: Newbie - What is the Difference Between Power Supply's GND and Arduino's GND?
I am new to electronics and Arduino.

What is the difference between power supply ground and Arduino's ground. If I connect my LED cathode to power ground, it doesn't work. But if I connect it to Arduino ground, it works. Aren't all ground the same?

Please see picture below.

# Answer
> 3 votes
I would expect there to be no difference between the grounds in your circuit, and after looking over the schematic for the board, it appears that all of the grounds are common.

I think the most likely explanation for what you're seeing is a quirk in the breadboard. It may be that the side busses are split at the middle of the board, or perhaps there was just a bad connection somewhere on the ground bus on that side of the board.

One way you could troubleshoot it further would be by jumping the ground side of the LED to the power supply ground. Start with the ground on the regulator and then work out until you find the spot where you loose continuity.

# Answer
> 2 votes
I agree with the other answers. On rare occasions, TO-xxx packages have bizarre pinouts, but the 78xx series does, in fact, have ground on the middle terminal. This is surely a split power supply in your breadboard power busses, or else a bad breadboard. Many breadboards have splits in the power rails halfway down. I've also seen some with splits more often than that, perhaps as much as disconnects every 5 (or 5 pairs of) contacts. I have a breadboard, for example, which allows for 6 different voltages, all in a single line, from various connections to a battery pack. I'd recommend buzzing the breadboard before starting to use it.

I've also had breadboards whose contacts fail after using larger AWG wires in particular holes (or forcing odd connections, such as machined contacts on IC's or sockets, or larger stamped rectangular pins on a TO package such as this) into breadboard holes. The last thing you want to worry about when building a prototype of a new design is whether or not the wiring under the breadboard works.

Many multimeters have a continuity test capability for diagnosing problems such as these, BUT make sure no power is connected (or you could damage the meter on this setting).

---
Tags: arduino-pro-mini
---


# Question
Title: Why does an LED sometimes flash when increasing brightness?
This is admittedly a cross-post from LED fade malfunction (random flash) but I can't get an answer on the Arduino forum.

I was mucking around with some very basic code and I noticed that when repeatedly holding an LED at 0 brightness for 1 second and then fading in to full brightness, a small flash would occasionally happen at the beginning of each fade (seemingly random).

```
int led = 11;
int brightness = 0;

void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  if(brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    analogWrite(led, 255);
    brightness = 0;
  }
  analogWrite(led, brightness);
  if(brightness == 0)
    {
      delay(1000); //LED off for 1 second
    }

  brightness+=1; //increment brightness
  delay(20);
}

```

So, the thing that has me completely perplexed is that I can use a different piece of code (below) and the flash goes away!

```
int i = 0;
int led = 11;

void setup()
{
  pinMode(led,OUTPUT);
}

void loop()
{
analogWrite(led, i);
delay(6);
if(i%256 == 0)
{
  i = 0 ;
  delay(1000);
}
i++;
}

```

Has anyone got any clue as to why this would happen? Both programs have basically the same code, except for that i is reset to 0 in the first program whereas in the second, i keeps incrementing past 255 so that analogWrite 'overflows.' I think it must be a firmware, (or maybe a software?) problem.

There is a video on youtube of it happening here, Arduino - fading LED problem.

# Answer
According to the links you provide from the arduino.cc forum the question is more or less answered. If not that important, just avoid `analogWrite(led,0)` and make it `analogWrite(led,1)`

if you still want that `analogWrite(led,0)`, I've tested your code with the advice and it seems to work OK when changing the register manually:

```
#include "wiring_private.h"

int led = 11;
int brightness = 0;

void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  if (brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    brightness = 0;
    sbi(TCCR2A, COM2A1);
    OCR2A = 0; // set pwm duty
  }

  analogWrite(led, brightness);
  if (brightness == 0)
  {
    delay(1000); //LED off for 1 second
  }

  brightness += 1; //increment brightness
  delay(20);
}

```

# Edit: to explain what those "strange codes" are

I'm not very expert in this field to explain how exactly this works but basically `sbi` is function defined in a macro by Atmel (?), it stands for "**s**et **b**it **i**n" and is used to change registers of ATmega chips. So basically what I did was change register defined by the macro `TCCR2A` (why? because it is the register that controls PWM in pin 11) and pass the bitmask `COM2A1` (this is a mode of compare defined in datasheet) and `OCR2A` is a register used to store the compare value that defines duty cycle. Imagine a counter that every time it receives a tick from a signal clock it compares the value of the counter with the value stored in `OCR2A` and it sets the pin high or low if that value as been passed or not (more or less like this, depending on the mode stored on `TCCR2A`).

But in fact I've not done some black magic. I just looked into the code of `analogWrite()` and that is the way they use to set a value of PWM in pin 11:

```
void analogWrite(uint8_t pin, int val)
{
    // We need to make sure the PWM output is enabled for those pins
    // that support it, as we turn it off when digitally reading or
    // writing with them.  Also, make sure the pin is in output mode
    // for consistenty with Wiring, which doesn't require a pinMode
    // call for the analog output pins.
    pinMode(pin, OUTPUT);
    if (val == 0)
    {
        digitalWrite(pin, LOW);
    }
    else if (val == 255)
    {
        digitalWrite(pin, HIGH);
    }
    else
    {
        switch(digitalPinToTimer(pin))
        {

...

          #if defined(TCCR2A) && defined(COM2A1)
            case TIMER2A:
                // connect pwm to pin on timer 2, channel A
                sbi(TCCR2A, COM2A1);
                OCR2A = val; // set pwm duty
                break;
          #endif
...

}

```

So basically I just used that info to set the register to zero, as suggested from the arduino.cc forum link that you have.

If you want to know more about PWM in Arduino, this site has a lot of info and explains a lot of the modes of registers also.
> 4 votes

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


# Question
Title: Interrupt on Analog Port - ESP8266 w/ Arduino
I'm trying to implement interrupts in my program. It essentially is constantly reading a photo-resistor and if it exceeds a certain threshold, we should send an update to our database. I'm struggling to understand how to do interrupts on a analog pin. I've tried reading this but honestly, it doesn't make much sense. Could anyone give me some advice? Here's out code.

```
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Initally send out false state
  sendState("18:FE:34:F4:D0:AF", false, false);
}

void loop() {

  if(analogRead(A0) < 20) {
    sendState("18:FE:34:F4:D0:AF", false, true);
    lastState = true;
    Serial.println("Waiting....");
    delay(15000);
  } else if(lastState == true){
    sendState("18:FE:34:F4:D0:AF", false, false);
    lastState = false;
  }

}

void sendState(String address, boolean lights, boolean occupied) {

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  String lightsStr = (lights) ? "true" : "false";
  String occupiedStr = (occupied) ? "true" : "false";
  String json = "{\"MACAddress\":\"" + address + "\", \"occupied\":" + occupiedStr + "}";

  String postData;
  postData += "POST /sensor HTTP/1.0 \r\n";
  postData += "X-Parse-REST-API-Key: " + API_KEY + "\r\n";
  postData += "Content-Type: application/json \r\n";
  postData += "Host: " + String(host) + " \r\n";
  postData += "Content-Length: " + String(json.length()) + "\r\n\r\n";
  postData += json;

  // Send the postdata to the server.
  client.print(postData);

  delay(1000);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("Closing connection!");
}

```

# Answer
> 3 votes
Interrupts are a tricky concept to get, you have to be mindful of so many things (in bigger projects).

Have a quick look on youtube for some tutorials, there are a heap out there.

Having said all that, your code above isn't using interrupts at all. And you have these big delays, does the code work as published?

I would suggest you rework the code into more of a state machine and have a single loop. ditch all the delays (except for your setup, that's fine) and go along the lines of:

# setup

set a variable for current timer value and have a constant defined for your update interval

# loop

* read sensor (consider constantly reading, or reading it more often than the information is sent, and average it out)
* anything on the serial port?
    + go read it
* check timer against old timer and interval
* interval exceeded
    + send averaged value

## using interrupts

You could use interrupts but the thing to consider is that they can be run AT ANY TIME. your code must be interrupt-able which whilst isn't too hard, needs special consideration in relation to delays, reading 16bit values, not having delays in the interrupt, status register changes, a whole host of others.

There are two types of interrupt, those that are driven by a change in input and those that are time based. You don't really want the change in state on this one because you would normally want to monitor it constantly anyway, but it is certainly doable.

In both time based and external input, you would have the interrupt set a flag that gets acted upon in your main loop.

*sorry for not providing more info at this time, screaming kids :(*

# Answer
> 2 votes
You can use the inbuilt analog comparator to generate an interrupt when a certain threshold is reached. Example circuit (reference voltage on D7, voltage under test on D6):

---

Example code for the Uno:

```
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

```

---

The incoming voltage is on the AIN0 (positive) pin which is pin 12 on the actual chip, and D6 on the Arduino board. The reference voltage (negative) pin is pin 13 on the chip, and D7 on the Arduino.

My example does not address the issue of transmitting the results, but that is the easy bit. You might need to build in a test so that you don't transmit the information thousands of times a second.

---
Tags: arduino-ide, interrupt
---


# Question
Title: Arduino Yun RFID-RC522 module not working
I have tried to use Arduino Uno with RFID-RC522 module. It is good work\[1\] and read rfid cards. But Arduino Yun doesn't work with RFID-RC522 module.

What is diffrent Uno and Yun?

1- http://www.grantgibson.co.uk/2012/04/how-to-get-started-with-the-mifare-mf522-an-and-arduino/

# Answer
According to the link you provided, we can see that the RFID-RC522 uses SPI to communicate with Arduino.

On Arduino UNO, the SPI pins are located as follows:

* pin 11: MOSI,
* pin 12: MISO,
* pin 13: SCK

On the Arduino YUN, this is different though; as stated there (bold highlight is mine):

> SPI: on the ICSP header. These pins support SPI communication using the SPI library. **Note that the SPI pins are not connected to any of** **the digital I/O pins as they are on the Uno**, They are only available on the ICSP connector. This means that if you have a shield that uses SPI, but does NOT have a 6-pin ICSP connector that connects to the Yún's 6-pin ICSP header, the shield will not work.

Hence you can not wire the RFID-RC522 module the same on UNO and Yun. For the Yun, you'll have to follow this wiring picture:

Pin 1 in image above is the pin that is marked with a dot on the Yun PCB.

Also see the ISP-header layout, at the lower-right corner of the yun\_by\_pighi Yun pinout diagram.
> 4 votes

# Answer
I had the same issues Thanks for help .However I made the following connections then above mentioned

RC522 RFID borad Arduino YUN (as per the github example code dumpinfo) chip select (nss ) - Pin 10 Rst - Pin 9

Link for Gihub RFID RC522 Hope it helps someone who is stuck
> 0 votes

---
Tags: arduino-uno, arduino-yun, rfid
---


title: How do I use I2C devices with Arduino?

text:
# Question
Title: How do I use I2C devices with Arduino?
I have a few useful I2C components, such as a 16-bit port expander (MCP23017), which I'd like to use in various projects.

What do I need to do to make these work with Arduino? Will it work with any Arduino, or do I need a specific board or shield?

# Answer
Arduino have the Wire Library that communicate with I2C.

> This library allows you to communicate with I2C / TWI devices. On the Arduino boards with the R3 layout (1.0 pinout), the SDA (data line) and SCL (clock line) are on the pin headers close to the AREF pin. The Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to the AREF pin and the additional one is on pins 20 and 21. As a reference the table below shows where TWI pins are located on various Arduino boards.

Board I2C / TWI pins

* Uno, Ethernet A4 (SDA), A5 (SCL)
* Mega2560 20 (SDA), 21 (SCL)
* Leonardo 2 (SDA), 3 (SCL)
* Due 20 (SDA), 21 (SCL), SDA1, SCL1

You can take a look at , this examples.

Like @TheDoctor said:

> The I2C data lines both need resistors to 3.3V. This keeps them from drifting if they are disabled. Andy resistor value should work, but it is recommended to use one between 10k ohm and 47k ohm.
> 9 votes

# Answer
Additional shields are not needed.

You only need the Wire library and a couple of wires to connect the device to **SDA** and **SCL**.

The position of these pins is different on the various Arduinos, please have a look here.
> 3 votes

# Answer
For future readers: use the Adafruit\_MCP23017 library.
> 3 votes

---
Tags: i2c
---


# Question
Title: Serial Communication Problem Using Eclipse
**Please help**

I have created an Arduino program that will switch the pins when I send a char. It works fine with serial monitor, but the problems come when I send chars with Eclipse using RXTX serial communication. When I click the button to send the char, at first click it does not switch the Arduino pins; it just senses the Rx and Tx LED but the second time it switches on. But when I tried to switch the second LED it first turns off the first LED although that was not my aim, and then it switches the intended LED. Here is my Arduino code.

```
const int lamp=2;
const int fan=3;
const int pump=4;
const int fridge=5;
char val;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lamp,OUTPUT);
  pinMode(fan,OUTPUT);
  pinMode(pump,OUTPUT);
  pinMode(fridge,OUTPUT);
}
void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available()) {
    val=Serial.read();
    if(val=='a') {
      digitalWrite(lamp,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='b') {
      digitalWrite(lamp,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='c') {
      digitalWrite(fan,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='d') {
      digitalWrite(fan,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='e') {
      digitalWrite(pump,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='f') {
      digitalWrite(pump,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='g') {
      digitalWrite(fridge,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='h') {
      digitalWrite(fridge,LOW);
      Serial.print(val);
      delay(100);
    }
  } else {
    int sensorValue = analogRead(A0);
    Serial.println(sensorValue/10);
    delay(100);
  }
}

```

*Here is a part of my Java code*

```
public boolean identifyport() throws PortInUseException, IOException, TooManyListenersException {
  this.setVisible(true);
  try {
    Enum=CommPortIdentifier.getPortIdentifiers();
    while(Enum.hasMoreElements())
      portname=(CommPortIdentifier)Enum.nextElement();
      if(portname.getPortType()==CommPortIdentifier.PORT_SERIAL)
        port=portname.open(this.getClass().getName(), 2000);
      serialport=(SerialPort)port;
      serialport.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);
      input=((CommPort) serialport).getInputStream();
      output=((CommPort)serialport).getOutputStream();
      serialreader=new BufferedReader(new InputStreamReader(input));
      serialport.addEventListener(this);
      serialport.notifyOnDataAvailable(true);
      progressBar.setBackground(Color.GREEN);
      portlist.addItem(portname.getName());
      progressBar.setValue(i);
      slider_3.setValue(value);
      Thread.sleep(1000);
      prg();
    } catch (UnsupportedCommOperationException e1) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(contentPane, "Check USB cable connection", "No port available ", 0);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(null, "Port status", "Please connect the device....!!!!", day, null);
    }
    return rootPaneCheckingEnabled;
  }
  @Override public void serialEvent(SerialPortEvent e) {
    // TODO Auto-generated method stub
    if(e.getEventType()==SerialPortEvent.DATA_AVAILABLE){
      try {
        serial=  serialreader.read();
      } catch(Exception e1) {
        e1.printStackTrace();
      }
    }
  }
  public void writedata(int v1) {
    try {
      output.write(v1);
      output.hashCode();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

*And this is part of the switch button;*
Button button_1 = new Button("switch");
button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
button_1.setBounds(10, 10, 117, 42);
panel_3.add(button_1);
button_1.addActionListener(new ActionListener() {
  int count=0;
  public void actionPerformed(ActionEvent e) {
    writedata(v1);
    if(count==0) {
      canvas.setBackground(Color.RED);
      canvas.setForeground(Color.GREEN);
      v1='b';
      count++;
    } else {
      canvas.setBackground(Color.YELLOW);
      canvas.setForeground(Color.GREEN);
      v1='a';
      count--;
    }
  }
});

```

Sorry I can not write everything because there is so much code.

# Answer
Thanks my friends, I had already solved the problem, the problem was this.... I made the method that ran after pressing each button, which sent the data at particular button, it seems the data interfered each other but I do not know why, but I had deleted that method and I used to send data using the object I created at each button.

```
Button button_1 = new Button("switch");
    button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
    button_1.setBounds(10, 10, 117, 42);
    panel_3.add(button_1);
    button_1.addActionListener(new ActionListener() {
            int count=0;
        public void actionPerformed(ActionEvent e) {
            if(count==0){
                canvas.setBackground(Color.RED);
                canvas.setForeground(Color.GREEN);

                char v2 = 'a';
                try {
                    output.write(v2);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            count++;
            }
            else{
                canvas.setBackground(Color.YELLOW);
                canvas.setForeground(Color.GREEN);
                char v1 = 'b';
                try {
                    output.write(v1);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                count--;
        }

        }

```

Now it worked fine....!!!!.
> 0 votes

# Answer
The java code you wrote should send just 'a' and 'b' so you should see just lamp turning on and off.

Move writedata invocation just before count++ and count-- statements to solve your "first time". The problem could be the initialization of v1.

Into writedata method why do you call hashcode on the output stream? Maybe flush?
> 0 votes

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


title: Arduino graphic interface

text:
# Question
Title: Arduino graphic interface
I succeeded in programming a system of thermoregulation using Arduino. This system holds the temperature of a plate at 37°C. I used a PID corrector to realize this.

What I want to do now is make a graphic interface that can communicate with the Arduino, allowing me to see a graph of the temperature.

I would like an explanation of how to send temperature data to a graphic interface using Arduino Uno.

# Answer
> 2 votes
There are two main possibilities.

The first one is to make a GUI on the Arduino itself. Add a TFT screen, touchscreen if you want the user to interact, or a non-touchscreen (cheaper) if you just want to display. Then, within your Arduino code, you can display the temperature data, and if you go the touchscreen route, interact with the user.

I own a couple of Arduino Esplora devices, and they would be near perfect for this, as they have a non-touch TFT screen, a joystick, buttons and a pot. All the equipment you need to display the temperature. Oh, and it has temperature and light sensors onboard.

The second way would be to make a GUI on your desktop/laptop machine. In your Arduino code, you could send your temperature data through USB (Serial), Bluetooth (SoftwareSerial), WiFi, Ethernet, nRF, etc etc etc. If you don't mind having the Arduino tethered to your computer by a cable, USB\<--\>Serial is the easiest solution. The software on the computer listens on a serial socket and when it receives temperature data, it displays it within its GUI.

HTH

# Answer
> 1 votes
It all depends on what graphical interface. There's many ways of doing it. You have TFT screens that the Arduino controls directly (take a look at UTFT for example), or serially connected displays (such as the ones offered by 4D Systems).

First you need to decide what kind of display device you want to use - and that is deciding:

1. What your budget is
2. How many Arduino resources you can dedicate to the interface
3. What IO you have available on your Arduino

And more.

---
Tags: arduino-uno
---


# Question
Title: 5v to 4.3v Regulator - For SIM800 module
I want to build a simple voltage regulator 3.8-4.2V with atleast 2A Peak Current Capability for my GSM Shield (It doesn't have regulated power supply), I don't want variation or it may burn the board.

Using voltage divider won't help here as there can be variations. Somewhere i read LDO are for for this task but i am able to get only 3.3v regulator with 800mA supply.

Can i use 3.3v to power the same ?

# Answer
> 1 votes
Consider using a buck converter for this. Search ebay for "buck converter" and you will see items like "Buck Converter Step-Down Adjustable Converter Power Module Regulator LM2596. That title indicates several things: the converter is adjustable, it steps voltage down, it's a regulator, and it's based on TI's LM2596 chip. It's rated at 2 A continuous, 3 A peak.

A buck converter has some advantages over a linear regulator:

1. Lower dropout (in general), ie, the input voltage has to be at least as much as the output voltage, possibly plus a small margin for one FET loss, but doesn't have to have the 1.1 to 1.3 volt margin typical of an LDO regulator.
2. Higher efficiency (in general). For example, 95% is not uncommon. (The ebay item mentioned above shows 92%.) A linear regulator, whether LDO or not, turns the input-to-output voltage difference into heat. A buck converter, on the other hand, uses an inductor and a capacitor to store energy; it refills the capacitor at a controlled rate via the inductor as often as necessary to deliver the required load. The inductor's DC resistance wastes energy, but that resistance can be kept small.
3. Smaller parts due to high frequency switching operation. As operating frequency is increased the inductor can be made smaller. On the other hand, higher frequencies lead to higher switching losses, so there's a tradeoff. Note, some SOT3-sized (~1.4 mm x 2.9 mm) transistors eg NTR4503 are rated over 2 A at 25°C and might be usable as an output FET for a buck converter chip, and inductors and capacitors also are available in sizes probably as small as you are looking for, but buying them and building your own converter is unlikely to be cost effective.

# Answer
> 1 votes
> I planned to use 3.7v LIPO battery

That's what your SIM800 module is *intended* to be *directly* powered by, *without* any intervening boost or buck converter.

Behind all the misdirection of a title that doesn't describe what you are actually trying to do, your question is an exercise in going around in a circle right back to where you started. Don't try to convert energy from the lithium cell to some other voltage and then from there to the allowed input range of the SIM800 (which is very intentionally that of a single lithium cell), rather use the parts as they were intended to be used.

> i guess it has current 800mA..

No, it has a capacity of 800 milliamp hours, not 800 milliamps.

A phone or RC model type lithium cell you would find today would have a "C" rating of 10 or better, but even if we assumed one of only 5, that would predict that your cell should be expected to be able to support pulse loads of 5 times the one-hour draw rate, which would be .8 * 5 = 4 amps.

---
Tags: arduino-uno, power, voltage-level
---


# Question
Title: Addressing contents of array using incrementing variable
Why would this simple code which prints out array values give the right value 240 when the array is addressed with index directly addressed by number but give 184 when addressed usin a varibale n that is incrementing?

```
PROGMEM const unsigned char COLSA[8] = {
      240, 240, 240, 240,
      240, 240, 240, 240};  //Stored pattern

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

void loop() {
  int n;
   for(n=0;n<8;n=n+1)
    {
      Serial.println(n);
      Serial.println(COLSA[1]);
      //n=2;  //If I use n in this way things are fine. It prints 240. Else it prints 184
      Serial.println(COLSA[n]);
    }
     delay(100);
}

```

# Answer
> 4 votes
Because the array is a constant the compiler can, when it knows the entry number (i.e., using a numeric literal) replace the access to the array with the contents of that array index - so it's not looking up the value of 240 at runtime, instead the value 240 has been used where the access to the array was.

However, when accessing it using a variable the compiler can't do that, so it has to actually access the array in RAM.

**BUT** the array *isn't* in RAM, it's in PROGMEM, so the address that it's being given for where the array is located is completely wrong. You're program is telling it "It's in the bedroom" - but you're omitting the important information of: "... of the house next-door.".

PROGMEM and RAM are two completely different things accessed through two completely separate data and address buses - just like two separate houses, they both have a number of rooms in them, and those rooms are called the same thing, but *they're not the same room*.

So instead of accessing an array by index like that you have to use special instructions to say "Get this value from PROGMEM", such as:

```
     Serial.println(pgm_read_byte_near(COLSA + v));

```

That says "Give me the byte that is located at *v* addresses on from the start of the `COLSA` array in PROGMEM.

---
Tags: programming
---


# Question
Title: How to choose SPI type used by RF24 library from application?
I am developing a device with Ethernet shield (with Wiznet W5100) and NRF24L01+. I need to use Soft SPI due to a bug in the Wiznet chip. Next I am developing a different device with NRF24L01+ only. I want to use hardware SPI (besides other things it already contains a socket for NRF24L01+ connected to the default Arduino SPI pins).

It is very inconvenient to enable/disable `#define SOFTSPI` in `RF24_config.h` every time I want to work on the other device.

Is there a way how to choose the SPI type used by RF24 library in the application?

My current solution is to make a copy of RF24 to RF24\_SoftSpi and RF24Network to RF24Network\_SoftSpi. I enabled SOFTSPI in “\_SoftSpi” versions (+ renamed all files, fixed includes and #ifndef statements in headers to avoid ambiguous errors).

Then in an application I just include RF24\_SoftSpi instead of RF24 and RF24Network\_SoftSpi instead of RF24Network to use software SPI.

With this workaround it is difficult to make updates to “\_SoftSpi” libraries when a new feature is released.

Do you know of any better solution?

# Answer
Using this RF24 library set, I am able to use or not softspi by doing #define SOFTSPI on my sketch, there's no need to define it on the RF24\_config.h, you should be able to define it on your own sketch.

***EDIT:***

Arduino 1.6.5

```
#include <SPI.h>
#include "RF24.h"
#include "printf.h"
#define SOFTSPI //Define pins RF24_config.h

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8     */
RF24 radio(8,9);

....
....
void setup() { ... }
void loop() { ... }

```
> 1 votes

---
Tags: nrf24l01+
---