title: Arduino Yun and REST call security

text:
# Question
Title: Arduino Yun and REST call security
I'm not expert about web development but very excited of doing some rest call using the yun as server (with a minimal python or node.js server inside the openwrt machine in the yun) and expose sensors and actuators to the cloud.

I'm also worried about security. I don't want the super-shellproof system but just don't want that accidental visitors reads my home temperature or make my garden light switch on when I'm out.

For instance I have a central unit yun with some logic inside it and few arduino yun that makes reads from sensors and runs actuators around my home. The communication between the central yun and the slaves is happening via REST calls. I'm using `curl` for testing it, for instance. Here two questions:

1. Arduino Yun provide a simple user/password account when `arduinoname.local/arduino` is called. How is it implemented?
2. Let's say I'm using node.js to make a super simple web-server, what is the best way to protect the communication central-yun and slave-yun? and to protect central-gun and internet communication?

Best way in term of computation (the yun machine is not very powerful and I'm going to use battery in some cases) and in term of "easy to implement".

# Answer
> 1 votes
Password protection of the REST API is done with Basic Authentication. This, coupled with HTTPS, makes API calls more secure. Since the SSL certificate is self-generated, you'll need to run `curl` with `-k` parameter.

As Annonomus Penguin suggested, before going into securing the Yuns, you should secure the network they are using (e.g.: home WiFi should use a strong password).

---
Tags: arduino-yun, web-server
---


title: Reading text/strings via processing

text:
# Question
Title: Reading text/strings via processing
I'm trying to control an led attached to my arduino via key presses on my laptop.When i hold down a key, the led should light up, and when i release the key, the led should turn off.

While my code works ATM, i am wondering why my code will not work if i replace the numbers in my code with text/strings.

Processing code(Working)

```
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write(2);println("released");
}

```

Arduino Code(Working)

```
int red = 7;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == 1){
    digitalWrite(red,HIGH);
  }else if(input == 2){
    digitalWrite(red,LOW);
  }
}

```

Processing Code (Not working)

```
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(8);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write("red");
      println("red");
    }

  }

}

void keyReleased(){
  myPort.write("released");
  println("released");
}

```

Arduino Code(Not working)

```
int red = 7;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
  if(input == "red"){
    digitalWrite(red,HIGH);
  }else if(input == "released"){
    digitalWrite(red,LOW);
  }
}

```

From the above example, i get the error ISO C++ forbids comparisons between pointers and integers.After googling the error, it was suggested that i replace the double quotes with single quotes, after which the arduino code is able to compile, but the processing code gives an error "badly formed character constant(expecting quote,got e)".

I then tried changing using double quotes for processing and single quotes for the arduino quote, but predictably, it did not work.

Why does my code work when i pass numbers to the arduino via serial communication, and my code fails when i use text strings?

# Answer
> 2 votes
The problem is that you're mixing different variable types. It's kinda an oil/water scenario.

Basically, the `serial.read();` command returns an integer, `-1` if there's nothing in the buffer. If there is something, it will return the character code (i.e. 93 = `a`). Because of that, *it's an integer.* When you put something in single quotes, it compiles as the equivalent ISO character code.

So, when you do `input == 2`, it is `integer [compared to] integer`. When you do `input == "string"`, you're doing `integer [compared to] string`, thus you get errors. BTW: a string is a type of pointer.

So, what you have to do is this:

```
string input = "";
if(serial.avaliable()) {
    delay(100); //Wait for all data to be received
    while(serial.avaliable()) {
        string = string + char(serial.read());
    }
}
if(input == "yay_it_works!) {
    //Done!
}

```

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


# Question
Title: How do I convert code between Arduino platforms?
What documentation is available regarding the differences between the different Arduino platforms?

For example, I have some code written for an Arduino Teensy that I would like to run on an Arduino Mega.

Is there documentation on the capabilities and equivalencies between each of the platforms? e.g. memory, number of PWM outputs, etc?

# Answer
> 4 votes
The most detailed one seems to be Baldengineer's, but Arduino, SparkFun, and Adafruit have their own as well, although more limited.

As always, the best source for information about them is the datasheets for both the MCU(s) used as well as for the boards themselves.

And note that different macros are predefined for each MCU and feature (e.g. `__AVR_ATmega328__` and `__AVR_HAVE_MUL__`); it is possible to test for their existence in order to customize behavior.

---
Tags: programming
---


# Question
Title: Setting a Pin to HIGH to simulate a button with a "pull up" resistor
in the below Fritzing diagram, I have a button that has a pull-up resistor, which when pressed, sets the GPIO Pin 23 to HIGH. On the Raspberry Pi, when the button is released, the GPIO goes LOW. The Raspberry Pi detects when the button is released and pressed. This is my desired behavior.

However, in my current configuration, I have PIN 13 connected to the Base of a NPN transistor to try to simulate the same behavior as the button with a pull-up resistor. When pin 13 is set to high, it sets the GPIO 22 Pin to high. When I set the Arduino Pin 13 to low, The GPIO Pin goes low but the Raspberry PI does not detect that GPIO 22 pin went low. Is there a way to simulate the same behavior as a button with a pull-up resistor with an OUTPUT pin from the arduino?

# Answer
So the solution to this was to remove the transistor all together and connect the Arduino pin directly to the Pi. However, I need to change my Arduino sketch. The approach was to set the pin HIGH and go LOW when selected. I had it backwards.
> 0 votes

# Answer
First of all, I don't think you will need *full* simulation of a button. There are a couple of things this approach won't have:

* Bouncing: it'll be (kinda, minus interference) a square wave. With a real button, the metal contacts "bounce," thus creating a weird waveform. Depending on interference, you'll still need debouncing code, although I would be surprised if it was necessary. I'd inlcude it in case I modified it to add a real button and/or there's some weird interference.
* The time it's "pushed" may be very short, depending on your code. Keep this in mind when designing this.

Basically, you're hooking up the Arduino and the RPi together, with a voltage divider or a level shifter between the two.

Voltage divider:

>

*Sparkfun*

That is a voltage regulator (drawn four different ways; it's the same circuit). I calculated the values you will need: 1700 ohm for R1, 3300 ohm for R2.

Of course, serial (with USB of the Arduino) communication would be a lot easier...
> 1 votes

# Answer
I don't think your circuit is correct. If red is positive and your switch is momentary closed then it actually pulls GPIO23 low.

Likewise with the NPN transistor, using it in this way gives you an inverter. It should work if internal pull ups are enabled on GPIO22 and you remove the resistor.

IF GPIO23 is 5V tolerant, you can instead connect the resistor to 5V and GPIO23 straight to the collector.

You should also have a 1K resistor between the arduino pin 13 and the base of the transistor to limit the base current.

This all assumes that the VCE of the transistor is lower than the 0.8V low-level cutoff of the GPIO pins (it should be).

In any case, if GPIO23 is 5V tolerant, just connect it straight to the Arduino. If it isn't, follow penguins advice and use a voltage divider.
> 1 votes

# Answer
If you don't mind using SMD components you could use the NX3V1G66 analog switch.

When you send a signal to the IC it will simulate a push button.

Maybe there are leaded versions of this IC but I haven't found them on the website where I order all my components.
> 0 votes

---
Tags: pins, resistor
---


title: Did I burn my Arduino UNO?

text:
# Question
Title: Did I burn my Arduino UNO?
I've recenly bought my first Arduino uno and I was messing with DC motors. I put on the prototype shield on arduino with a mini breadboard on it. I was using L293D bridge. I've connected everything and then put in my 6V battery pack and it BURNED. I don't know what happened. I didn't upload the code, I just connected batteries. I put negative to GND and positive to pin 8. Arduino is responding, but I'n not sure whether all pins are working, how do you check this?

# Answer
> 4 votes
To make sure all pins are responding you could put all your pins as input with internal pull-up except pin 13 which must be set as output. The on board led is connected to pin 13, so when you put pin13 high it will turn the led on. Connect every other pin 1 by 1 to the GND to see if the led is toggling once you've connected a pin to the GND.

Try to use this code.

```
void setup(){
for(int p = 0; p <= 12; p++){  // Define pin0 until pin12 to INPUT with internal pull-up resistor
pinMode(p, INPUT_PULLUP);
}
pinMode(A0, INPUT_PULLUP);  // Define pinA0 as INPUT with internal pull-up resistor
pinMode(A1, INPUT_PULLUP);  // Define pinA1 as INPUT with internal pull-up resistor
pinMode(A2, INPUT_PULLUP);  // Define pinA2 as INPUT with internal pull-up resistor
pinMode(A3, INPUT_PULLUP);  // Define pinA3 as INPUT with internal pull-up resistor
pinMode(A4, INPUT_PULLUP);  // Define pinA4 as INPUT with internal pull-up resistor
pinMode(A5, INPUT_PULLUP);  // Define pinA5 as INPUT with internal pull-up resistor
pinMode(13, OUTPUT);        // Define pin13 as OUTPUT (INTERNAL LED);
}

void loop(){
if(digitalRead(0, LOW)){   // If pin0 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(1, LOW)){   // If pin1 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(2, LOW)){   // If pin2 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(3, LOW)){   // If pin3 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(4, LOW)){   // if pin4 is connected to GND turn led on
digitalWrite(13, HIGH);
}
 if(digitalRead(5, LOW)){  // If pin5 is connected to GND turn led off
digitalWrite(13, LOW);
}
 if(digitalRead(6, LOW)){  // If pin6 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(7, LOW)){   // If pin7 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(8, LOW)){   // If pin8 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(9, LOW)){   // If pin9 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(10, LOW)){  // If pin10 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(11, LOW)){  // If pin11 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(12, LOW)){  // If pin12 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(A0, LOW)){  // If pinA0 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(A1, LOW)){  // If pinA1 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(A2, LOW)){  // If pinA2 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(A3, LOW)){  // If pinA3 is connected to GND turn led on
digitalWrite(13, HIGH);
}
if(digitalRead(A4, LOW)){  // If pinA4 is connected to GND turn led off
digitalWrite(13, LOW);
}
if(digitalRead(A5, LOW)){  // If pinA5 is connected to GND turn led on
digitalWrite(13, HIGH);
}
}

```

---
Tags: motor, safety, battery
---


# Question
Title: Input audio from jack to Arduino, and output by
I've never used Arduino but I know a few of its utilities.

I want to input audio from a Jack cable (analog) and be able to send it via Bluetooth, or Wi-Fi, or USB to an Android Phone and being able to print the values (from 0 to 1).

I'm looking for tutorials but I just find the way to make the input but not the output.

Which one would you recommend me of Bluetooth, Wi-Fi and USB?

Thanks.

# Answer
The simplest solution: *it really depends.* There are a couple of things to consider:

* **Bluetooth** would probably be the least professional to impliment. The easiest way to do this is with an app. You can impliment it into *your* application with this:

> Let your own Android application receive data from Arduino by listening to the "primavera.arduino.intent.action.DATA\_RECEIVED" intent. This intent will contain the "primavera.arduino.intent.extra.DATA" byte array with the received data. Call getByteArrayExtra("primavera.arduino.intent.extra.DATA") to retrieve the data. Send data to Arduino from your application by broadcasting an intent with action "primavera.arduino.intent.action.SEND\_DATA". Add the data to be sent as byte array extra "primavera.arduino.intent.extra.DATA".

Still, that's pretty unprofessional IMHO. There are probably other ways to do this, but *Arduino Uno Communicator* is the easiest by far that I've seen. The main advantage of Bluetooth is it works without a router and it's very cheap (as far as wireless). I can't remember if it's the HC4 or HC5 chip that is commonly available, but \[one of those\] can be picked up for around $6. Just connect via serial and issue AT commands.
* **WiFi** would be the most professional. First of all, people hear *Wifi* and they think *Ohh! Shiny! I'm going to buy it!* That's just what I've observed in the past, but it may not always be true. WiFi can be done with the TL-WR703N router. This blog post outlines how you can even connect it *directly* to the Arduino. You can also use an ethernet shield (or equivalence, I've seen breakout ethernet boards built for ~$5). Either way, it's a great way to add 5V WiFi to your Arduino. The only disadvantage is cost and it only works if you're near a WiFi router. If those aren't disadvantages, go ahead with WiFi; it's a great product.
* **USB** is only useful if you want:

+ Speed
    + Stability
    + Portability (i.e. no WiFi Router)

Speed can be eliminated as a need if you only send data every 300 ms or so, depending on what you're doing. For WiFi, it might be best to only go to a webpage when an even occurs (i.e. button pushed on Arduino). Bluetooth and WiFi are stable enough if you're over short distances (and you couldn't go a long way with wires, anyway), and there's not too much interference (don't try at a football game with 50K cell phones... granted, they will be on different bands if using cell service, but Bluetooth may be on).

As far as portability, for the price of an OTG cable for your phone, you'd be better off buying a Bluetooth module for a dollar extra.

Suggestion: go with WiFi unless you need the portability. Consider figuring out WPS so your users can connect to WiFi with a push of a button. I don't know if the TL-WR703N has support for WPS, via serial or not.

Forgot to mention: I don't know everything about your app, but WiFi might have too much latency/overhead for near-instant response. As far as wireless, Bluetooth would have much lower latency AFAIK. (As you can tell, there's no perfect solution here :-))
> 3 votes

---
Tags: android
---


# Question
Title: Unable to light up all the LEDS connected to Arduino using processing
I have 3 LEDs connected to my arduino which are controlled via laptop key presses with processing.

While the LEDs are able to light up when the respective buttons are pressed, i am unable to light up all 3 LEDs simultaneously when i press all 3 keys at the same time. I am however able to light up 2 LEDs by pressing 2 buttons simultaneously.

All the LEDs light up when their respective buttons are pressed, so i know that it is not a defective LED and/or faulty connections/wiring at play but something else that is causing the issue.

My processing code:

```
import processing.serial.*;
Serial myPort;

void setup(){
  println("The available ports are: ");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
  myPort.buffer(64);
  size(500, 500);
}

void draw(){
  if(keyPressed){
    if(key == 'r' || key == 'R'){
      myPort.write(1);
      println("red");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(2);
      println("yellow");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(3);
      println("green");
    }
  }

}

void keyReleased(){
 if(key == 'r' || key == 'R'){
      myPort.write(4);
      println("red released");
    }
    else if(key == 'y' || key == 'Y'){
      myPort.write(5);
      println("yellow released");
    }
    else if(key == 'g' || key == 'G'){
      myPort.write(6);
      println("green released");
    }

  println("released");
}

```

My Arduino code:

```
int red = 7;
int yellow = 6;
int green = 5;

void setup(){
  Serial.begin(9600);
  pinMode(red,OUTPUT);
   pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
}

void loop(){

}

void serialEvent(){
    int input = Serial.read();
    if(input == 1){
      digitalWrite(red,HIGH);
    }
    else if(input == 2){
      digitalWrite(yellow,HIGH);
    }
    else if(input == 3){
      digitalWrite(green,HIGH);
    }
    else if(input == 4){
      digitalWrite(red,LOW);
    }
    else if(input == 5){
      digitalWrite(yellow,LOW);
    }
    else if(input == 6){
      digitalWrite(green,LOW);
    }
}

```

Things i've tried.

1. I've tried increasing the buffer size from 10(initially) to 64(in the code above)
2. I've tried increasing the baud rate from 9600 to 12000, just in case it was the serial information not being read fast enough.

None of the things i've tried, listed above, was above to solve my problem, and i dont see what could be causing the problem.

Any advice would be much appreciated.

# Answer
> 1 votes
I'm guessing it is a hardware issue as I discussed in the comments above.

I have just set up a breadboard and copied your code verbatim into the Arduino IDE and Processing (I edited the port index to use). It works as desired. Pressing R, G, or Y will turn on the respective LED and releasing it will turn it off.

I can press these three keys in any combination of none on, one only, any two, or all three, and the LED gives the expected result.

Keyboards were not initially designed to have multiple "main" keys pressed down at any one time, the exceptions to these being the modifier keys (Windows/Command, Option/Alt, Control and possibly some others (I'm thinking the older keyboards here that had "other" keys—Scroll Lock, Print Scr, etc—I'm really unsure).

It appears now, that some hardware and software may have overcome this. As I've said, your project works fine for me. Also, you could try three different keys, it could be a result of how the keys are scanned and you may stumble across three that don't interfere with each other.

As I've suggested in the comments to your question, modify the code to utilise the modifier keys instead, or use the keyboard keys as toggles (ie press once for on, press again to turn it off).

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


title: How does this code work?

text:
# Question
Title: How does this code work?
I've found this code below, but I can't figure out how it works. Can someone explain to me the flow of the program?

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 10, 7, 5, 4);
int mem=0;
void setup() {
    pinMode (12,OUTPUT);
    pinMode(13,OUTPUT);
    // initialize the LED pin as an output:

    // initialize serial communications:
    Serial.begin(9600);
    lcd.begin(16, 2);
}

void loop() {

    lcd.setCursor(12,1);
    int se25 = analogRead(A4);
    int se50 = analogRead(A3);
    int se75 = analogRead(A5);
    int se100 = analogRead(A2);
    if(se100>=1000){lcd.print("100%   ");mem=100; }
    else if(se75>=1000){lcd.print("75%   ");mem=75; }
    else if(se50>=1000){lcd.print("50%   ");mem=50; }
    else if(se25>=1000){lcd.print("25%  ");mem=25; }
    else{lcd.print("emty");mem=0;}
    if(se100<1000&&se75<1000&&se50<1000&&se25<1000){
        digitalWrite(13,LOW);
        lcd.setCursor(12,1);
        lcd.print("emty");
    }

    if(digitalRead(6)==HIGH){digitalWrite(13,LOW);}

    if(digitalRead(6)==LOW&&mem>0)
    {// read the value of the potentiometer:
        int tempw = 0;
        //digitalWrite(12,LOW);
        int tempa = analogRead(A1);
        delay(20);
        int tempb = analogRead(A1);
        delay(20);
        int tempc = analogRead(A1);
        delay(20);
        int tempd = analogRead(A1);
        delay(20);
        int tempe = analogRead(A1);
        delay(20);
        int tempf = analogRead(A1);
        delay(20);

        int avg = ((tempa + tempb + tempc + tempd + tempe + tempf ) / 6);

        int temp = avg;
        // map it to the range of the analog out:
        temp = map(temp, 0, 1023, 0, 4900);
        float tempx = temp * (0.1);
        // change the analog out value:
        int tempy=analogRead(A0);
        tempy = map(tempy, 0, 1023, 0, 150);
        // print the results to the serial monitor:
        lcd.setCursor(0,0);
        lcd.print("act T=" );
        lcd.print(tempx);
        lcd.print("'C  " );
        lcd.setCursor(0,1);
        lcd.print("set T=");

        lcd.print(tempy);
        // Serial.println("'C ");
        lcd.print("'C  ");

        if(tempy<=tempx){digitalWrite(13,LOW);}
        if(tempy>tempx){digitalWrite(13,HIGH);}

        delay(200);
    }

}

```

# Answer
I'm assuming you already have some understanding of programming, so I won't literally explain everything line-by-line (that would probably be beyond the scope of this site, and would result in a very long answer). I'll try to explain the important points though. If you need to lookup more information about specific commands, I recommend checking out the Arduino reference.

At a very broad level, the program is taking some readings, and reporting data to a screen (LCD). I would guess that the data is the fluid level in a tank, as well as some kind of temperature reading. It's impossible to be sure about that though, as I don't know what's actually connected to the inputs.

This line creates an object for talking to the LCD screen. The numbers specify which pins it's connected to:

```
LiquidCrystal lcd(2, 3, 10, 7, 5, 4);

```

The `setup()` function gets run once when the device starts up, and is typically used for initialisation tasks. In this case, the lines within `setup()` initialise two pins as outputs (#12 and #13), initialise serial communication (which isn't actually being used), and initialise the LCD object/screen:

```
pinMode (12,OUTPUT);
pinMode(13,OUTPUT);
...
Serial.begin(9600);
lcd.begin(16, 2);

```

The rest of the program is in the `loop()` function, which runs repeatedly as long as the device is on.

The following lines take 4 analog-to-digital readings (from different inputs), and output the approximate result:

```
int se25 = analogRead(A4);
int se50 = analogRead(A3);
int se75 = analogRead(A5);
int se100 = analogRead(A2);
if(se100>=1000){lcd.print("100%   ");mem=100; }
else if(se75>=1000){lcd.print("75%   ");mem=75; }
else if(se50>=1000){lcd.print("50%   ");mem=50; }
else if(se25>=1000){lcd.print("25%  ");mem=25; }
else{lcd.print("emty");mem=0;}
if(se100<1000&&se75<1000&&se50<1000&&se25<1000){
    digitalWrite(13,LOW);
    lcd.setCursor(12,1);
    lcd.print("emty");
}

```

My guess is that each of the analog readings comes from a different fluid sensor in a tank. If the top sensor shows a strong reading, the tank is considered full. Otherwise, it checks the next sensor down, and so on. If none of them shows a strong reading, the tank is considered empty. Interestingly, the condition for an empty tank is actually checked twice, which is presumably a mistake.

(Once again, bear in mind that I'm just guessing that the readings are from fluid sensors in a tank. I don't know for sure.)

The remainder of the code only runs if a particular input (#6) is low, and if the tank is not empty. Input #6 could be from some kind of override switch, but again that's just speculation.

The following block takes 6 analog readings, all from the same input. There's a short delay (20 millisecond) between each reading. The results are then averaged. This is a common approach when you want to try to eliminate noise spikes in an analog signal.

```
int tempa = analogRead(A1);
delay(20);
int tempb = analogRead(A1);
delay(20);
int tempc = analogRead(A1);
delay(20);
int tempd = analogRead(A1);
delay(20);
int tempe = analogRead(A1);
delay(20);
int tempf = analogRead(A1);
delay(20);

int avg = ((tempa + tempb + tempc + tempd + tempe + tempf ) / 6);

```

The next block re-maps that reading onto a different range (presumably related to the expected temperature range). It then takes another analog reading from a different input, and remaps that to a different range:

```
int temp = avg;

temp = map(temp, 0, 1023, 0, 4900);
float tempx = temp * (0.1);

int tempy=analogRead(A0);
tempy = map(tempy, 0, 1023, 0, 150);

```

The following block outputs the two re-mapped readings. It looks like both of them are treated as temperatures. One is presumably from a temperature sensor, and the other is presumably from a potentiometer used to calibrated the system:

```
lcd.setCursor(0,0);
lcd.print("act T=" );
lcd.print(tempx);
lcd.print("'C  " );
lcd.setCursor(0,1);
lcd.print("set T=");

lcd.print(tempy);

lcd.print("'C  ");

```

These lines compare the two readings from above, and set output pin 13 high or low depending on which reading is higher. I'd guess it could be connected to a warning light or similar.

```
if(tempy<=tempx){digitalWrite(13,LOW);}
if(tempy>tempx){digitalWrite(13,HIGH);}

```

Lastly, this delay stops the loop from running too fast. Interestingly though, the code only reaches this point under certain circumstances. In other circumstances, there's no limit on loop execution speed:

```
delay(200);

```
> 11 votes

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


# Question
Title: Problems with Dallas temperature sensor code
I have connected up my temperature sensor and I am trying to run the one wire address finder to find the address of the sensor.

The problem is that when I run the code it gives me the error: 'OneWire' does not have a type.

I have imported by the temperature and the onewire libraries but it still does not work.

```
#include <OneWire.h>

OneWire ds(6);  // This is where the error is

```

# Answer
I presume the exact error you get is

> error: 'OneWire' does not name a type

This error is typical when the OneWire library (or any other library for that matter) is not located under the **libraries** folder, which should be at the root of the Arduino installation folder.

Also, make sure that the OneWire.h and OneWire.cpp files are 1 folder down the hierarchy, as follows:

\[Arduino Installation Folder\]\libraries\OneWire\OneWire.h

If they are nested deeper inside the folder hierarchy, the Arduino IDE will not find these files in its initial scan, and you will get the same error.

Make sure to close all Arduino IDE windows and re-open it after fixing the folder path.
> 1 votes

---
Tags: arduino-uno, temperature-sensor
---


# Question
Title: Setting up the MMA8452 to trigger interrupt
I am working with the MMA8452q accelerometer by Freescale. I am trying to set it up to be in low power mode, to go to sleep when no motion has happened, and to wake up due to motion being detected and trigger the interrupt that corresponds to it. I am using Arduino.

I have verified the accelerometer works (i.e. can read off accelerometer data and communicate properly to it via I2C), and I have also verified that the interrupt and handler all work (by manually triggering the interrupt as compared to using the accelerometer). However, after initializing using the code below, my interrupt due to motion is not getting triggered.

-The datasheet can be found here: http://www.freescale.com/files/sensors/doc/data\_sheet/MMA8452Q.pdf

-App note can be found here: http://cache.freescale.com/files/sensors/doc/app\_note/AN4074.pdf

My code is as follows:

```
void MMA8452::initMMA8452(unsigned char fsr)
{
    //CONFIGURE THE ACCELEROMETER
    MMA8452Standby();  // Must be in standby to change registers

    //Set up the full scale range to 2, 4, or 8g.
    if ((fsr==2)||(fsr==4)||(fsr==8))
        writeRegister(XYZ_DATA_CFG, fsr >> 2);
    else
        writeRegister(XYZ_DATA_CFG, 0);

    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | bmRES1DOT56);  //1.56Hz resolution in both wake and sleep mode (lowest power)
    writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING

    writeRegister(CTRL_REG3, (1 << WAKE_FF_MT));        //ONLY WAKE UP FROM MOTION DETECTION
    writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT));  //ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
    writeRegister(ASLP_COUNT, ASLP_TIMEOUT);    //162s TIMEOUT BEFORE SLEEPING

    writeRegister(CTRL_REG5, (1 << INT_CFG_FF_MT) | (1 << INT_CFG_ASLP));  //INTERRUPT SLEEP AND FREE FALL TO INT1 PIN OF MMA8452

    //SETUP THE MOTION DETECTION
    writeRegister(FF_MT_CFG, (1 << ELE) | (1 << OAE));      //MOTION DETECTION AND LATCH THE RESULT WHEN IT HAPPENS AS OPPOSED TO COMBINATIONAL REAL TIME
    writeRegister(FF_MT_THS, MOTION_THRESHOLD);             //MOTION DETECTION THRESHOLDS
    writeRegister(FF_MT_COUNT, MOTION_DEBOUNCE_COUNT);      //TIME MOTION NEEDS TO BE PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

    MMA8452Active();
};

```

# Answer
I played around more with it, and this code works:

```
void MMA8452::initMMA8452(unsigned char fsr, unsigned char dr, unsigned char sr, unsigned char sc, unsigned char mt, unsigned char mdc)
{
    MMA8452Standby();

//Set up the full scale range to 2, 4, or 8g.
if ((fsr==2)||(fsr==4)||(fsr==8))
    writeRegister(XYZ_DATA_CFG, fsr >> 2);
else
    writeRegister(XYZ_DATA_CFG, 0);

writeRegister(CTRL_REG1, readRegister(CTRL_REG1) & ~(0xF8));
if (dr<= 7)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (dr << DR0));
if (sr<=3)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (sr << ASLP_RATE0));

writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING
writeRegister(ASLP_COUNT, sc);

// Set up interrupt 1 and 2: 1 = wake ups, 2 = data
writeRegister(CTRL_REG3, (1 << WAKE_FF_MT) | (1 << IPOL));  // Active high, push-pull interrupts, sleep wake up from motion detection
writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT) |  (1 << INT_EN_DRDY));  // DRDY ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
writeRegister(CTRL_REG5, (1 << INT_CFG_ASLP) | (1 << INT_CFG_FF_MT));  // DRDY on INT1, ASLP_WAKE INT2, FF INT2
writeRegister(CTRL_REG5, readRegister(CTRL_REG5));

//SETUP THE MOTION DETECTION
writeRegister(FF_MT_CFG, 0xF8);     /*MOTION DETECTION AND LATCH THE
                                    //RESULT WHEN IT HAPPENS AS OPPOSED
                                    //TO COMBINATIONAL REAL TIME*/
    writeRegister(FF_MT_THS, mt);       //MOTION DETECTION THRESHOLDS
    writeRegister(FF_MT_COUNT, mdc);    //TIME MOTION NEEDS TO BE
                                        //PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

    MMA8452Active();
}

```
> 3 votes

---
Tags: arduino-uno, firmware, accelerometer
---


title: Arduino LCD shows only black boxes

text:
# Question
Title: Arduino LCD shows only black boxes
I've hooked up my Arduino on this LCD, and after running the following code, all I see is a row with black boxes and another one empty.

```
//LiquidCrystal d(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(0, 1, 2, 3, 4, 5);

void setup() {
     lcd.begin(16, 2);
     lcd.print("hello, world!");
}

void loop() {
     lcd.print("hello, world!");
}

```

Wiring:

(The UTP cable is used just for the data lines :-)

Actual wiring photos: (sorry for the total klutz in the wiring, I had limited solid-core wires so I had to use these scrap ones)

# Answer
The problem was that the R/W pin on the LCD was left floating, after I connected it to GND, I started working :)
> 2 votes

---
Tags: lcd, wires
---


title: Prototyping method

text:
# Question
Title: Prototyping method
I'm currently using a normal breadbord 'n' solid-core-wires for prototyping, but it gets messy when I need to connect a large number of pins on the arduino, as when using an LCD display + another sensor. What are my other options for prototyping?

# Answer
> 0 votes
One of the Arduino's greatest strengths are shields, and shields upon shields. (Another is it's ease of programming via USB amongst a whole host of others).

They are perfect for prototyping. There's nothing wrong with breadboarding it as well, but it's pretty much one or the other (excluding making your own circuit board).

I am working on a garage controller and it has three shields on top of the arduino itself.

1. XBee/wireless coms
2. a relay shield, and
3. a prototying shield where I have created custom circuitry (buttons, connectors, optocouplers etc).

Especially with the top shield, I have made several changes to get it to perform as I'd like. If I'd committed to making a custom board, then I would have had to change it (and re-change it). What I've done would be virtually impossible on a breadboard.

The idea is, you use the shields to get your idea up and running, as a proof of concept. Then, you could/can leave it as is, or you could take the next step, break it down to the required components and make a custom PCB for your project. If it wasn't for shields and stacking shields, you would either breadboard it (which as you've indicated can get ugly, cumbersome and problematic), or make a PCB which (depending on the project) might not be a small task. So shield it up, test it out, then build your own based on what you've put together.

That's not to say, you have to make your own PCB in the end, many projects can remain a shield on an arduino. So if you can find a shield to do specifically what you're after, then why wouldn't you use it?

---
Tags: pins, wires, prototype
---


# Question
Title: Are there any GPS data pusher for Arduino?
I plan to build a GPS logger for my car using a GPS device, an Arduino board and a SD Card. The plan is that the GPS device forwards the position to the Arduino which is responsible for storing the data on the SD card. However, I would like to regularly (say every hour) send my current position to a server at home.

For that you can use GPS pusher or puller, but I couldn't find any such devices on the Internet. Do these devices exist? What are my (other) options?

# Answer
> 2 votes
Check this shield out, it sounds almost exactly like what you need, plus it has OBD2 (CAN) access to log RPM, indicated speed, steering wheel angle, and whatever else your car exposes. You can get a GPS module from Sparkfun as well. Matter of fact, I'm using it in a very similar project, but development is paused until I upgrade to a Mega, since I've run out of RAM.

The shield comes with example code that's hacked together from other sources but it serves the demo purpose well.

As for pushing to a server--that'd be tougher. I would go the route of a Bluetooth shield and make a corresponding app for the phone that pushes the data.

---
Tags: tinygps
---


# Question
Title: Problems controlling servos using proximity sensor
I've just started using Arduino and I need to make a code to simulate the behavior of a lizard, meaning that if you come close to it, it moves away from you.

I'm using a "Arduino duemilanove" that my university lend me, I was told that it was an alternative version of Arduino Uno.

Both of the servos says "Tower Pro, mg996r, digihi-speed"

Looking different codes I made one which I think is correct. Also, I checked for each servo motor (I'm using two) and the proximity sensor running codes for everyone of them alone, if they worked well and they did but with this code, they supposed to move when you are closer than a meter but they don't stop spinning.

If anyone could help me with this, it would be great.

Here is the code:

```
#define Servo1 9
#define Servo2 11
#define trigPin 10
#define echoPin A0

#include <Servo.h>

Servo servo1;
Servo servo2;

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin (9600);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(Servo1, OUTPUT);
  pinMode(Servo2, OUTPUT);
  servo1.attach(9);
  servo2.attach(11);

}

void loop(){
  long duracion, distancia; // variables

  /* Hacer el disparo */
  digitalWrite(10, LOW);
  delayMicroseconds(2);
  digitalWrite(10, HIGH);  // Flanco ascendente
  delayMicroseconds(10);        // Duracion del pulso
  digitalWrite(10, LOW);  // Flanco descendente

  /* Recepcion del eco de respuesta */
  duracion = pulseIn(A0, HIGH);

  /* Calculo de la distancia efectiva */
  distancia = (duracion/2) / 29.1;

  if (distancia<100){
    for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
    {                                  // in steps of 1 degree
      servo1.write(pos);    // tell servo to go to position in variable 'pos'
      servo2.write(pos);
      delay(15);                       // waits 15ms for the servo to reach the                 position
    }
    for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
    {
      servo1.write(pos);              // tell servo to go to position in variable                 'pos'
      servo2.write(pos);
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  }
  else{
  }
}

```

# Answer
> 1 votes
I am new to servos as well, but I do have two coding thoughts. The servos I have used in the past have started in the halfway position. That would mean the "pos" variable would start off trying to go from the starting 90 position to the 0 value in 15ms. Not enough time before the next for loop. I could see that causing some weird spinning while the servos try to get to the intended position. So..

```
int pos = 90; // Start servo position.

```

And secondly, the "distancia" could just always be less than 100. I would try finding a max distance value to compare to vs a hard coded value.

```
void loop() {...
long duracion, distancia; // variables
boolean isMoveTrigger = false; // Movement trigger.

/* Calculo de la distancia efectiva */
distancia = (duracion/2) / 29.1;

// Store a maximum value.
if (distancia > maxDistance) {
    maxDistance = distancia;
}

// Wait to get a starting maximum distance value.
if (countDown > 0) {
    countDown--;
} else {
    if (distancia > 0) {
      int distancePercentage = (maxDistance * 100) / distancia; // A 0-100 percentage of the maximum value.
      // Then trigger the movement when less than this percentage.
      isMoveTrigger = distancePercentage < 50;
    }
}
if (isMoveTrigger) {
    for(pos = 0; pos < 180; pos += 1) ...

```

# Answer
> 0 votes
As an extra tip, from my experience do not power the servos from the same power supply as the sensors. I built a similar project to you and it didn't work as expected. I then powered the servos directly from the battery (6v) and the sensors and arduino from a regulated 5v supply taken from the battery. The servos can cause power spikes that mess with the sensor readings.

---
Tags: arduino-uno, sensors, servo, proximity
---


# Question
Title: what is the coversion details of temperature usnig lm35?
I found similar type of code in many sites for coverting analog signal lm35 to centigrade. But i can't understand that fully. So I need some help what this equation means

```
tempC = (5.0 * tempC * 100.0)/1024.0;

```

Thank you,

# Answer
I took a quick look at the data sheet for LM35 and it says that each centigrade means a 10 millivolt change.

If you have an ADC with 10-bit resolution, it means you have 1024 steps from 0 V to 5 V.

The temperature is then:

tempC = 5 * (ADCdata / 1024) * 100

This is equal to your equation. So it seems to be correct.

**EDIT:**

A more thorough explanation of the formula:

Lets call the value you read from your LM35 "ADCdata". The range of this value is determined by the resolution of the Analog-to-Digital Converter (ADC). The ADC converts a voltage to a digital value in the Arduino. This value is again what I refer to here as "ADCdata".

If the ADC resolution is 10-bits, it means the 5 volt input can be divided into 1024 equal levels. One level is about 5 millivolts (five thousands of a volt).

To find what value "ADCdata" is in volts we need to divide it with the resolution (1024) and multiply with 5 volts.

Lets say we have a 2.5 volt input signal. The ADCdata will then be 512. If we now divide 512 by 1024 we get 0.5. Lets multiply that with 5 volts and we get 2.5 volts!

We know from the data sheet that 10 millivolts equals 1 centigrade. Since we have our value in volts (2.5 V, which is the same as 2500 millivolts) we need to multiply it with 100 to get centigrades.
> 3 votes

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


# Question
Title: Wired serial connection between two Arduinos - do they need a common Ground (GND)?
I would like to connect two Arduinos by a serial connection. Is it sufficient to connect TX1\<--\>RX2 and RX1\<--\>TX2 or do I also need to connect the GND of the two Arduinos?

# Answer
Short answer: Yes.

Rx/Tx is referenced with a logic ground. Without ground being common, there is no way to determine what is high or low.

(Sorry I don't have a more technical explanation)

Edit: I thought I would add, if you are using the same power source, then they probably have a common ground. In this case, a common power source doesn't mean the wall side of a wall adapter, but the SAME wall adapter.
> 2 votes

---
Tags: arduino-uno, serial, arduino-due, arduino-nano, softwareserial
---


# Question
Title: Serial port /dev/cu.usbmodemfa131 vs /dev/cu.usbserial-A702NY8S
On Mac OSX Mavericks, why does Arduino Uno uses serial port named `/dev/cu.usbmodemfa131` while Arduino Nano uses `/dev/cu.usbserial-A702NY8S`?

Are they using different FTDI drivers?

# Answer
> 2 votes
Drivers are different. On older boards, such as Duemilanove you may need to actually download serial drivers to talk to them at all in Lion, Mountain Lion, Mavericks. There's some discussion of that problem here.

# Answer
> 1 votes
It's really down to the manufacturer and what they identify their USB side as. I have found that Arduino(tm) provide a more meaningful (to me) identifier, eg `/dev/cu.usbmodemfa131` Whilst the boards that use the FTDI chip have the more serialised numbers `/dev/cu.usbserial-A702NY8S`.

# Answer
> 0 votes
The Uno is not using FTDI drivers **at all**, since it does USB through an ATmega16u2, not an FTDI chip.

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


# Question
Title: Where can I find out how to make a hex file for arduino firmware?
I have followed this tutorial on flashing my Arduino R3 to turn it into a "USB keyboard", but the article doesn't explain how the hex works, it's just for granted. Where can I learn about how to make my own hex file so that I can learn how to make my Arduino mimic *any* USB device?

# Answer
The HEX file is simply a translated version of the AVR executable, which is in turn a translated version of AVR source code.

There are many tools available for turning (compiling) AVR source code into an AVR executable, including but not limited to the Arduino IDE, Ino, AVR-GCC, and Atmel Studio. Note that all four tools will compile the code the same way, since AVR-GCC is used under the hood by the other three.

```
avr-g++ -mmcu=atmega328 source.cc -o executable

```

Once you've compiled the code, you can use avr-objcopy to extract the appropriate sections from the executable into HEX files for programming into the flash and EEPROM.

```
avr-objcopy -j .text -j .data -O ihex executable executable.hex

```

You can then use AVRDUDE to upload the various HEX files to the target device.

```
avrdude -c arduino -P /dev/ttyUSB0 -b 19200 -p m328 -U flash:w:executable.hex:i

```

Note that the USB libraries in Arduino/Ino and AVR LibC are limited; you will need to use Atmel Studio if you want full USB capabilities.
> 2 votes

# Answer
There are plenty of sites out there that document how to make/build such.

```
Example: http://hunt.net.nz/users/darran/
or https://github.com/harlequin-tech/arduino-usb
GOOGLE: build usb keyboard 16u2

```

Please note that when attempting this on the Uno R3, the DFU is updating the code on the 16U2 and not the 328p.

I would suggest for novices to use the Leonardo. Where there are stock examples in the IDE for using the application directly as USB HID. Avoiding any alterations to either the boot loader or the USB to Serial co-processor chip (the 16u2). Making it much simpler.
> 2 votes

# Answer
It is possible, but it's kind of hard(especially if you want to mod both the 8u2 AND the 16u2. I'd recommend the Teensy(https://www.pjrc.com/teensy/index.html) I recently posted a question about a question similar to yours and after hearing about all the pitfall I decided to go with the Teensy. I has much richer USB/HID support by default (You can start on your project right away rather than trying to mod the UNO). Teensys are also relatively cheap ranging from $18 to $24.

By comparison, UNOs are $27.18 and are out of stock. To be fair both are probably cheaper used. This is probably moot since it seems you already have one. For more info, see my question (Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes)
> 2 votes

# Answer
You don't need to do something magical. Here's how you can use the Arduino IDE's affiliates.

Once you compile or upload a sketch, the *.hex* file is automatically created and stored in your computer's drive that has the OS installed (I've found this on Windows). You can access it by navigating to the directory containing temporary files.

Typically, the path will be something like this: *C: \> Users \> Admin \> AppData \> Local \> Temp*

Now you'll see (a lot of) directories with names that go like "build"... followed by a big number. One of these directories contains compiler-generated files of the code you're looking for. From this location, you can search (using Windows Explorer, for example) and identify the *.hex* file you're looking for by the date and time of last modification.

Once you've got your *.hex* file, you can upload it to your Arduino using Atmel FLIP after setting your Arduino's microcontroller to the Device Firmware Upgrade (DFU) mode. Atmel FLIP, an acronym for FLexible In-system Programmer, can be used very easily, thanks to its minimal UI.

Here's how to use FLIP:

1. Go to *File \> Load HEX File...* and select the file.
2. Choose your microcontroller by selecting the first icon on the bar.
3. Choose your programming interface from the small list.

I've used this with ATXmega that supports USB but it's not the same for all.
> 2 votes

---
Tags: firmware, flash
---


# Question
Title: Are there any pressure sensor for 22 kg (~50lbs) and more?
I'm looking for pressure sensors up to 22 kg and more. So far the highest capacity I could found was 25 lbs. Do higher ones not exist?

# Answer
Your problem may be that you are using sub-optimal search terms. The kilogram is not a unit of pressure, but instead of mass. Scales technically do not sense mass, but instead sense force. This is assumed to be the force exerted by a resting body under earth gravity. Pressure is force over an area, such as pounds-per-square-inch (PSI) or the Pascal which is a newton per square meter.

Anyway, the sensor you want is called a force cell. The nice ones are rated in newtons or kilonewtons, with a kg being equivalent to 9.8 newtons.

Here is a load cell that take up to 50 kg. http://www.phidgets.com/products.php?product\_id=3135

Sources: http://en.wikipedia.org/wiki/Force
> 2 votes

---
Tags: sensors
---


title: Operating / pin voltages ATTiny chips

text:
# Question
Title: Operating / pin voltages ATTiny chips
I would like to set up a project with an ATtiny chip, such as the ATtiny84 or ATtiny85, in which I interface the microcontroller directly with an XBee for both wireless serial communication, as well as monitoring a digital signal from the Xbee (digital input to the ATtiny). As the Xbee chips can handle only 3.3V and will be damaged at higher voltages (such as 5V), I was wondering whether I can simply power the entire project at 3.3V so that all digital inputs and outputs will be at that voltage?

# Answer
Yes. As given in the datasheets, normal ATtinyX4/X5 chips can run with a supply between 2.7 and 5.5V inclusive, whereas the low-power versions can run between 1.8V and 5.5V. Mind the speed restrictions when running at lower voltages though; see the "Electrical Characteristics" section of each datasheet to determine the maximum characterized speed for a given voltage.
> 5 votes

---
Tags: xbee, voltage-level, attiny
---


title: Reading the rpm of multiple fans

text:
# Question
Title: Reading the rpm of multiple fans
I am trying to build a fan controller for my pc, the problem is that the example code(http://playground.arduino.cc/Main/ReadingRPM) im using utilizes interrupts. On my uno I can then only read the rpm of one fan. I want to also control the rpm (via pwm) and monitor temperatures (via thermistors) Anyone know how I coud do it differently? I. E. Without interrupts. I would also like it to be as close to real time as possible

# Answer
If temperature regulation is what you seek, why bother with the Tachometer signal at all?

Thermistors don't require interrupts. Why do you need fully closed loop fan control? A simple proportional control of each fan and each hot item would likely suffice in keeping your system cool. Noise concerns, perhaps?

A brief article on proportional temperature control

A data sheet on a TI chip that may have some inspiration for you
> 3 votes

# Answer
If you only want 2 fans, the uno has 2 external interrupts, so you can use the same strategy as your example, just make another interrupt function for fan 2 and attach it on interrupt 1 instead of 0. the fan should be plugged in to pin 3 in this case. On a leonardo, you could have 5 fans on interrupts, and a mega has 6 external interrupts. See http://arduino.cc/en/Reference/attachInterrupt

If you need more than what your hardware can support, I would look into using a timed interrupt to check all the fans. If you find the minimum amount of time in-between reads to read your fans at max RPM and then use a timer interrupt to check some pins at that interval, you can probably read as many as you need, provided the interrupt routine stays fast enough. the function

```
attachInterrupt(function, period);

```

from the libraries on this page : http://playground.arduino.cc/Code/Timer1 should help you out with this.
> 0 votes

---
Tags: arduino-uno, sensors, interrupt
---


# Question
Title: How to integrate smoothing into project (HVAC thermostat / controller)
I am working on building a "simple" HVAC thermostat. This is my current sketch.

```
    // include the libraries for gizmos
#include <LiquidCrystal.h>
#include <dht11.h>

dht11 DHT11; // Figure out what this line does
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

// These constants won't change:
const int ACledPin = 8;      // Air Conditioner LED (RED)
const int HTledPin = 9;      // Heat LED (YELLOW)
const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

const int RELAY_01 = 6;    // RELAY 1 PIN 9
const int RELAY_02 = 10;   // RELAY 2 PIN 10

void setup() {
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
  Serial.begin(9600);    // Serial setup

  pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
  pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
  pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
  pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

  // Leaves the relays in default "off" (no noise/click)
  digitalWrite(RELAY_01, HIGH);
  digitalWrite(RELAY_02, HIGH);

}

void loop() {

  float analogValue = (DHT11.fahrenheit()); // trying to set up the temp reading as an int variable
////////////// if then ////////////////
// if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ACledPin, HIGH);
    digitalWrite(HTledPin, LOW);
    digitalWrite(RELAY_01, HIGH);
    digitalWrite(RELAY_02, LOW);
  }
  else {
    digitalWrite(ACledPin, LOW);
    digitalWrite(HTledPin, HIGH);
    digitalWrite(RELAY_01, LOW);
    digitalWrite(RELAY_02, HIGH);
  }

Serial.println(analogValue);  // print the analog value:

// Set up the LCD Stuff
  lcd.setCursor(0, 0);      // Set cursor to top left
  lcd.setCursor(0, 1);
  lcd.print(analogValue, 1);
  lcd.print("F");

  delay(1000);

}

```

I want to add "smoothing" to the temperature reading. I Found this tutorial http://arduino.cc/en/Tutorial/Smoothing and have it working the way I want it.

```
// Define the number of samples to keep track of.  The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input.  Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
#include <dht11.h>
dht11 DHT11; // Figure out what this line does

const int numReadings = 5;

float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total
float average = 0;                // the average

void setup()
{
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  Serial.begin(9600);    // initialize serial communication with computer:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:
}

void loop() {
  // subtract the last reading:
  total= total - readings[index];
  // read from the sensor:
  readings[index] = (DHT11.fahrenheit()); //analogRead(inputPin);
  // add the reading to the total:
  total= total + readings[index];
  // advance to the next position in the array:
  index = index + 1;

  // if we're at the end of the array...
  if (index >= numReadings)
    // ...wrap around to the beginning:
    index = 0;

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println("");
  Serial.print("Realtime: ");
  Serial.println(DHT11.fahrenheit(),2);
  Serial.print("Average:  ");
  Serial.println(average);
  delay(2000);        // delay in between reads for stability
}

```

I'm new to Arduino and don't know the best way to do this. I'm not certain how to do multiple loops/delays in a single project, or if I even need to.

EDIT:

I've ended up with this based on the comments from @Craig. The only thing that needs some adjustment are the first 4 readings are low, so it would be nice to somehow ignore, probably not a big deal in the long run.

Example readings on startup;

```
Realtime: 77.00
Average:  15.40

Realtime: 77.00
Average:  30.80

Realtime: 77.00
Average:  46.20

Realtime: 77.00
Average:  61.60

Realtime: 77.00
Average:  77.00

```

Final code

```
// include the libraries for gizmos
#include <LiquidCrystal.h>
#include <dht11.h>

dht11 DHT11; // Figure out what this line does
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

// These constants won't change:
const int ACledPin = 8;      // Air Conditioner LED (RED)
const int HTledPin = 9;      // Heat LED (YELLOW)
const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

const int RELAY_01 = 6;    // RELAY 1 PIN 9
const int RELAY_02 = 10;   // RELAY 2 PIN 10

// START ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////
const int numReadings = 5;
float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total

float get_smoothed_temp() {
    total = total - readings[index]; // remove oldest reading
    readings[index] = DHT11.fahrenheit();
    total += readings[index];
    index = (index + 1) % numReadings;

    return (total / numReadings);
}
// END ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////

void setup() {
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
  Serial.begin(9600);    // Serial setup
  for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:

  pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
  pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
  pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
  pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

  // Leaves the relays in default "off" (no noise/click)
  digitalWrite(RELAY_01, HIGH);
  digitalWrite(RELAY_02, HIGH);

}

void loop() {

  float analogValue = (get_smoothed_temp()); // trying to set up the temp reading as an int variable
////////////// if then ////////////////
// if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ACledPin, HIGH);
    digitalWrite(HTledPin, LOW);
    digitalWrite(RELAY_01, HIGH);
    digitalWrite(RELAY_02, LOW);
  }
  else {
    digitalWrite(ACledPin, LOW);
    digitalWrite(HTledPin, HIGH);
    digitalWrite(RELAY_01, LOW);
    digitalWrite(RELAY_02, HIGH);
  }

Serial.println(analogValue);  // print the analog value:

// Set up the LCD Stuff
  lcd.setCursor(0, 0);      // Set cursor to top left
  lcd.print("Real F:");
  lcd.setCursor(0, 1);
  lcd.print("AVG  F:");
  lcd.print(analogValue, 1);

  delay(1000);

}

```

# Answer
> 3 votes
What you want to do is replace your call to `DHT11.fahrenheit()` with a call to a new function (e.g. get\_smoothed\_temp()) that keeps track of the last several readings and returns the smoothed value.

```
const int numReadings = 5;
float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total

float get_smoothed_temp() {
    total = total - readings[index]; // remove oldest reading
    readings[index] = DHT11.fahrenheit();
    total += readings[index];
    index = (index + 1) % numReadings;

    return (total / numReadings);
}

```

You will still need to set the readings array to all zeros in the setup function.

# Answer
> 3 votes
Your running average code is fine.

A quick way to start up fast is to take your first reading in setup, and fill the array with that value instead of zero. That way you always get a reasonable temperature from the smoothing, it just gradually drifts from the first reading to the average of multiple readings (rather than from 0 - a bogus value - to the that average).

This can work for the exponential smoothing too (old average = first reading).

An alternative is to only average as many samples as you have put into the array (1 then 2, then 3 etc until it's filled). That takes extra code to handle just the first few results, tho, and the simpler approach suggested above (initially fill the array with a legitimate reading) is usually fine.

# Answer
> 2 votes
> I'm not certain how to do multiple loops/delays in a single project

You *can't* do this.\* Software threading is the only way to do something like what you want, but it's too complex for what you need. What you want is to use the `millis()` function to return the time and

```
// constants won't change. Used here to
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

```

You can then pull button changes while you wait for a new reading. Another way would be to use an *interrupt* to interrupt the flow of the program when a button changes. I won't get into that.

For your use, you can use this template I made:

```
long previousMillis = 0;        // will store last time temp was updated
long interval = 1000;           // interval at which to check the temp (milliseconds)

void setup() {
  //Foobar
}

void loop()
{
  //Bar of foo
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    //Check Temp
  }
}

```

*Not to be confused with the `loop` statement.

# Answer
> 2 votes
I've just done a fan controller (using digital sensors - DS18b20, in my case) and chose an exponential average for smoothing the readings because it doesn't require storing or managing old data and I could get the smoothing I needed. During setup I took a reading from each sensor and preset the averages to those values. That gives the system a "running start"; it doesn't need to wait for enough samples for the averages to settle.

The exponential average I chose was `(3 * oldAverage + tempr)/4` because it gave the performance I needed and is easy and fast to calculate without floating point. Multiplying by 3 is done by shifting and adding; dividing by 4 is done by shifting.

Here's the routine I used. It could easily be put in-line; the compiler probably will:

```
int16_t xpavg(int16_t tempr, int16_t oldAverage)
{
   // (3*oldavg + 1*tempr)/4
   return( (((oldAverage<<1) + oldAverage + tempr) + 2) >> 2 );
}

```

---
Tags: programming
---


title: Reading speed of different arduinos

text:
# Question
Title: Reading speed of different arduinos
I'm thinking about using an Arduino for one of my Projekts. This would require that the Arduino can read/write a digital input/output in the order of 100kHZ to 1MHz. Is this possible or do I have to resort to my own boards using ATmegas?

# Answer
> 1 votes
Focussing on your final question:

> Is this possible or do I have to resort to my own boards using ATmegas?

Remember, an Arduino is already just an ATMega already on a board. Designing your own board around an ATMega that is already part of the Arduino family is not going to significantly alter your project. That is unless you are going to have supplementing hardware, or go via higher clock speeds or ARM processing.

# Answer
> 0 votes
Any Arduino will do just fine. Technically, you could output 8 digital signals simultaneously at the Arduino's clock speed (16 MHz on most models), as it only takes one clock cycle to flip an output bit.

In more realistic scenarios 100kHz is no problem at all, and depending on your code 1MHz is possible as well.

---
Tags: arduino-uno, arduino-due
---


title: If statement behaves erratically

text:
# Question
Title: If statement behaves erratically
I connected the output from an encoder motor to int0. this is used to increment a counter at every pulse. in the loop(), I check this counter and stops the motor if it is above certain value. But this "if statement" works erratically. The while loop should break at 380, but sometimes it breaks at 256.

```
Serial.print(cnt);
cnt=0;
Serial.print("  ");
Serial.print(cnt);
motor1_up(255);
motor2_up(255);
while(1)
{
    if(cnt>380)
    {
        Serial.print(" break ");
        Serial.print(cnt);
        break;
    }
}
motor1_down(255);
motor2_down(255);
Serial.print("  ");
delay(40);
Serial.println(cnt);
motor1_down(0);
motor2_down(0);
delay(2000);

```

Here is the serial output

```
 1  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389
 396  0 break 381  389
 396  0 break 256  264
 270  0 break 381  389
 397  0 break 381  390
 396  0 break 381  389
 397  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389

```

# Answer
> 5 votes
Not only must `cnt` variable be declared `volatile`, but accessing it from the main loop must also be protected because:

* it can be modified by an ISR
* it is longer than 1 byte

In AVR architecture (8-bits), **read/write operations on bytes are guaranteed to be atomic**, i.e. no function can access a byte while it is read/written by an ISR.

However, **operations on types larger than bytes are not atomic!**

This means that reading e.g. an `int` variable from your main loop might be interrupted in the middle of the operation (only 1 byte read) by an ISR that could modify the value (both bytes this time); then when the ISR is finished the main loop would resume reading the second byte -modified by the ISR- of the variable, while keeping the first original byte -not modified by the ISR.

I would advise you to write a pair of functions to read and write `cnt` in a protected way, i.e. with interrupts disabled:

```
volatile int cnt;

void set_cnt(int val) {
    uint8_t status = SREG;
    cli();
    cnt = val;
    SREG = status;
}

int get_cnt() {
    uint8_t status = SREG;
    cli();
    int val = cnt;
    SREG = status;
    return val;
}

```

What those functions do are:

1. get the current status of exceptions (from `SREG` register)
2. disable exceptions with `cli()`
3. access `cnt` without any risk of it being accessed concurrently
4. restore initial status of exceptions (to `SREG` register)

Everywhere in your code (except in code called from an ISR where it is not necessary), you must then call these functions to access `cnt` variable.

# Answer
> 2 votes
It looks like it could be a caching issue. If you're accessing a variable from the main loop *and* from an interrupt handler, then you need to ensure it's declared as `volatile`. For example:

```
volatile int cnt = 0;

```

That tells the compiler that the contents of the variable could change unexpectedly, i.e. when an Interrupt Service Routine is triggered. The result is that it always fetches the actual value from RAM, instead of relying on a cached copy which could be out-of-date.

---
Tags: rotary-encoder
---


# Question
Title: How to program arduino for ethernet with only usb cable
I have arduino UNO r3 ATMEGA 328P board and this kind of a cable. But I want to make and test a program that need to get the data through ethernet port. Can I do only with them. I want to know whether they are enough to that (there are any converter or virtual devices) or should I buy anything.

# Answer
> 2 votes
You can do the programming of the Arduino through the USB cable, but in order to test and operate the program, you'll need an Ethernet shield and a cable to connect that to the LAN.

---
Tags: arduino-uno, uploading, ethernet
---


# Question
Title: SerialEvent handling when using multiple serial ports
I would like to use multiple (three) serial ports on an Arduino Due. Instead of polling the ports continuously, I would like to use a Serial.Event function for each of the ports. These handler functions will read out the incoming string from the port and parse the string (i.e. check for a pre-defined command and call a corresponding sub-routine).

I was wondering what is going to happen when serial data arrives at the same time at two different ports? For example, if the program is in the process of handling/parsing the first serial message, will it interrupt/abandon this process as soon as another SerialEvent on another port is triggered? Or will it complete the first SerialEvent routine before going to the second one?

# Answer
The built in serialEvent() function on arduino only responds to serial port 0, called just "Serial" in the code. To respond to messages on "Serial1", use serialEvent1() on the Arduino Due there also exists serialEvent2() and so on.

EDIT: the serialEvent() handlers are not on interrupts; they run sequentially in-between loops. If the loop is blocking they do not get run, and they do not interrupt eachother.
> 3 votes

# Answer
That should be fairly simple to implement.

Each serial port has TX and RX interrupts. You just need to tie into the various interrupts.

Here is an example for a mbed, but it should be similar (both use ARM NVIC interrupt controllers).

To be clear, this wouldn't involve touching the `serialEvent()` function stuff at all, but rather implementing what it does using your own code.

---

If you set up your own interrupt handlers, you also get the benefit of being able to control interrupt priority yourself. The ATSAM3X has 16 interrupt priority levels, and a interrupt of a higher priority can pre-empt a lower-level interrupt.

I Strongly suggest you read the ATSAM3X datasheet. It describes the interrupt controller, as well as the rest of the processor peripherals.
> 2 votes

---
Tags: serial, arduino-due
---


title: Arduino PWM fading led

text:
# Question
Title: Arduino PWM fading led
I am trying to blink an LED with PWM on Arduino.

I don't know what is wrong but my LED is not fading as expected. What is wrong?

I think that I have bad registers settings, but I am not sure.

LED is connected to Arduino pin 9.

Here is my code:

```
#include <avr/io.h>
#include <util/delay.h>
const int delay=1000;
void initialize_PWM()
{
    TCCR0A|=(1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
    TCCR0B=1;
    DDRB|=(1<<PB1);
}

void set_pwm(uint8_t data)
{
    OCR0A=data;
}

int main (void)
{
    initialize_PWM();
    uint8_t brightness=200;
    while(1)
    {
        for(brightness=0;brightness<255;brightness++)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }

        for(brightness=255;brightness>0;brightness--)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }
    }
    return 0;
}

```

# Answer
> 5 votes
From your code you are using **Timer0** in **FastPWM mode with top = 0xFF**.

In this mode, as used in your code, `OCR0A` defines the pulse width rate (more precisely, `OCR0A / 256`).

**Timer0** uses port `OC0A` and `OC0B` to ouput PWM signals, in your code, you are using only `OC0A` (which is perfectly fine).

Now if you take a look at ATmega 328 data sheet, chapter 14.3.3 you will see that pin `OC0A` maps to **port D, pin PD6** (on Arduino UNO, this is port **D6**, according to http://arduino.cc/en/Hacking/PinMapping168).

So this means that **you have used the wrong port** in your setup (Arduino pin D9 maps to `OC1A`, which is pin **PB1** of **port B** on ATmega328, `OC1A` is used by **Timer1**, not Timer0).

Hence you should do the following to fix the problem:

1. Plug the LED to Arduino pin D6 instead of D9
2. Fix `initialize_PWM()` by replacing `DDRB|=(1<<PB1);` with `DDRD|=(1<<PD6);`

Otherwise, if you want to keep Arduino pin D9, then you will have to change the timer you use: Timer1 instead of Timer0. Updating the code is left as an exercise!

# Answer
> 1 votes
It's much too soon to optimize. Get your LED working using the standard (known working) libraries. Only then - and perhaps never, unless you find a need to - should your optimize (use direct register I/O). If it works with the libraries but not with your direct I/O, you'll know the bug lies in the direct I/O code and nowhere else, ruling out failed hardware, improper or unreliable connections, and programming errors elsewhere in your project. Right now, you don't know even that much.

# Answer
> 1 votes
The easiest way is to use the timer1 library written for arduino. You can download it here.

To install, simply unzip and put the files in Arduino/hardware/libraries/Timer1/

---

Prescaler set for 16Mhz

```
Prescale    Time per counter tick   Max Period
1   0.0625 uS   8.192 mS
8   0.5 uS  65.536 mS
64  4 uS    524.288 mS
256 16 uS   2097.152 mS
1024    64uS    8388.608mS

```

In general:

Max Period = (Prescale)*(1/Frequency)*(2^17) Time per Tick = (Prescale)\*(1/Frequency)

---

Instructions available using this library are:

initialize(period) You must call this method first to use any of the other methods. You can optionally specify the timer's period here (in microseconds), by default it is set at 1 second. Note that this breaks analogWrite() for digital pins 9 and 10 on Arduino.

setPeriod(period) Sets the period in microseconds. The minimum period or highest frequency this library supports is 1 microsecond or 1 MHz. The maximum period is 8388480 microseconds or about 8.3 seconds. Note that setting the period will change the attached interrupt and both pwm outputs' frequencies and duty cycles simultaneously.

pwm(pin, duty, period) Generates a PWM waveform on the specified pin. Output pins for Timer1 are PORTB pins 1 and 2, so you have to choose between these two, anything else is ignored. On Arduino, these are digital pins 9 and 10, so those aliases also work. Output pins for Timer3 are from PORTE and correspond to 2,3 & 5 on the Arduino Mega. The duty cycle is specified as a 10 bit value, so anything between 0 and 1023. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.

attachInterrupt(function, period) Calls a function at the specified interval in microseconds. Be careful about trying to execute too complicated of an interrupt at too high of a frequency, or the CPU may never enter the main loop and your program will 'lock up'. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.

setPwmDuty(pin, duty) A fast shortcut for setting the pwm duty for a given pin if you have already set it up by calling pwm() earlier. This avoids the overhead of enabling pwm mode for the pin, setting the data direction register, checking for optional period adjustments etc. that are mandatory when you call pwm().

detachInterrupt() Disables the attached interrupt.

disablePwm(pin) Turns PWM off for the specified pin so you can use that pin for something else.

read() Reads the time since last rollover in microseconds.

---

Example - Sets up PWM output on pin 9 with a 50% duty cycle, and attaches an interrupt that toggles digital pin 10 every half second.

```
/*
 *  Timer1 library example
 *  June 2008 | jesse dot tane at gmail dot com
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}

```

Source: http://playground.arduino.cc/Code/Timer1

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


# Question
Title: Can the SPI pins of an Arduino be separated from SPI?
Are the SPI pins on the ICSP header of an Arduino Uno "separable" from the correspondent I/O pins - when one chooses to the use the ICSP header can the corresponding I/O pins be used for something else?

# Answer
No. Those pins are not separate on the microcontroller itself. If you need to use SPI and still need more pins you may use analog inputs as digital inputs or outputs. Otherwise you'll probably have to use an expander of some sort, or use a Mega or Due for additional inputs or outputs.
> 4 votes

# Answer
Actually, it can. You just can not use them at the same time. One needs to be careful to wire it in ways not to comprise the shared functions. Where MISO can be used as GPIO-INPUT and MOSI/SCK can be used as GPIO-OUTPUT, avoiding any pull up/downs, etc... As such electrical items may interfere with the ICSP.

For example I use the ICSP programming, along with the MISO, MOSI and SCLK pins as hard SPI and use them as Bit Bang one-wire, all on the same board and same wires. I simply ensure the SPI is properly configured each at each use.

One additionally needs to ensure that any peripherals on the shared SPI/ICSP lines are guaranteed to be in reset. Such as a pull down on such devices reset pins. Or a Pull Up on their ChipSelects. Noting that ATmega's GPIO pins are Hi-Z out of reset and during the ICSP.
> 1 votes

---
Tags: spi
---


# Question
Title: Why voltage at AREF is given by Vin * R2 / Rtotal
In chapter 4 of Arduino Workshop on page 85 (or page 31 in the pdf) it says that the voltage at AREF in the schematic is given by:

Vin * R2 / (R2 + R1)

However, the voltage is flowing from 5V to Ground so isn't AREF actually in parallel with R1, and so shouldn't AREF be given by:

Vin * R1 / (R1 + R2) ?

# Answer
> 3 votes
You are correct.

$$V\_{ref} = \dfrac{R\_1}{R\_1 + R\_2} \cdot V\_{CC}$$

or Vref = Vin * R1 / (R1 + R2) until we finally get MathJax enabled on this site.

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


title: splitable jumper wires question

text:
# Question
Title: splitable jumper wires question
I just received my starter kit from oddwires.com today and it came with a split-able ribbon cable for prototyping. I was curious if it is possible to split each wire off and use only what I need to for the tutorials or is that a bad idea? I am very excited to start playing around and learning this as it has been a interest of mine for many years.

# Answer
Each wire in the Dupont ribbon cable is is independent, and does not hold onto its neighbors with any real force. You can split them or join multiple wires together using larger connectors as desired.
> 2 votes

---
Tags: arduino-uno, wires
---


title: Keyboardmessage on Arduino UNO

text:
# Question
Title: Keyboardmessage on Arduino UNO
Can an Arduino UNO and Arduino Leonardo do the same things?

Some of the examples in the Arduino software say to use Leonardo e.g. KeyboardMessage.

# Answer
> 1 votes
No, the Uno and the Leonardo cannot do the same thing. The Leonardo is a single MCU directly connected to the USB port. It is down to the software on that MCU as to how it communicates (what it enumerates as) on the USB bus.

The Uno, conversely, is a dual MCU system. It has the "main" MCU (the ATMega328P) which is what you program, and that communicates to the USB port via another MCU. The two MCUs are connected using TTL RS-232 (UART), so the only communication you have with your computer is through the Serial object.

There are benefits and problems with both approaches. The benefits of the Leonardo are that you can emulate keyboards, mice, etc. The down side is that the whole USB communication is more fragile and is at the mercy of the user. The Uno's benefits are that the USB serial is always connected and available regardless of the state of the main MCU, which is much more friendly from the PC's point of view. The down side is that it severely limits your communication options.

# Answer
> 0 votes
Yes you can, but not with that library. This method is a little advanced and requires you to upgrade a different type of firmware to your second MCU on your Uno.

*(The full tutorial is available here)*

Example code from the tutorial link shown above (for process outlined below):

```
uint8_t buf[8] = {
  0 };  /* Keyboard report buffer */

void setup()
{
  Serial.begin(9600);
  randomSeed(analogRead(0));
  delay(200);
}

void loop()
{
  int randomChar = random(4, 130);
  long randomDelay = random(1000, 10000);

  delay(randomDelay);

  buf[2] = randomChar;    // Random character
  Serial.write(buf, 8); // Send keypress
  releaseKey();
}

void releaseKey()
{
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8); // Release key
}

```

Here's what you need to do:

1. Get a DFU programmer

> Windows: Download Atmel's flip programmer from here http://www.atmel.com/tools/flip.aspx
>
> Mac: Install MacPorts following these instructions: http://www.macports.org/install.php#pkg Once MacPorts is installed, in a Terminal window, type `sudo port install dfu-programmer`
>
> Linux: from a command line type `sudo apt-get install dfu-programmer` or `sudo aptitude install dfu-programmer` depending on your distribution

*(Source: http://arduino.cc/en/Hacking/DFUProgramming8U2)*
2. Download the Keyboard LUFA firmware
3. You'll have to solder a resistor on a non-SMD Uno (that's outlined in the Arduino link in the second step)
4. Connect the Uno to your comptuer and reset the 8u2 (short the farthest left pair of metal contacts in the upper left hand corner of the Uno)
5. Upload the firmware using the GUI in flip, OR for Mac/Linux go to the directory where the firmware is using the terminal then:

Type this line (Still, Mac or Linux only):

```
sudo dfu-programmer at90usb82 erase
sudo dfu-programmer at90usb82 flash [Replace-this-with-file-name].hex
sudo dfu-programmer at90usb82 reset

```

Unplug/plug in your board and enjoy! Note: you'll have to flash the standard firmware to upload a new sketch and the flash the keyboard firmware again to get this to work.

---
Tags: arduino-uno, programming, uploading, arduino-leonardo
---


title: No usb serial on Mac

text:
# Question
Title: No usb serial on Mac
I've been using my Arduino UNO without a hith for a few days now, but suddenly I can't program it anymore.

When I try to programm my Arduino on Mac, I get the following Error:

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

```

The USB option under serial port has disappeard (It was there before). Has anyone an idea on how to fix this?

The last thing I did is use the serial port for some communication. A reboot hasn't improved anything.

I tried programming Linux, but it resulted in the exact same result.

# Answer
It seemed to be a hardware problem on the board. Thanks for the effort.
> 3 votes

# Answer
If I try to upload with no device connected, I get a dialog with the message "port is blocked" and a message in Eclipse's console window that the port is not found.

So I'm guessing you've got a sync problem. UNO should reset automatically when avrdude connects. Try manually resetting it just before you click to start the download. If that works, then the automatic reset has failed.
> 1 votes

---
Tags: programming, serial
---


title: 7 Segment Display SET UP

text:
# Question
Title: 7 Segment Display SET UP
I am new to Arduino. I have been trying to connect a 7 segment display (3 digits) to my Arduino and I was successful, but I am not doing any connection to ground. I do not find the data sheet so I am not sure if this connection is well done. My doubt is: Is the connection to ground necessary? Or how do Arduino pins work? I am using 12 pins of the Uno to do the set up.

Thanks

My set up is the following:

# Answer
I don't know exactly how your display is wired exactly, but it is certain that some sort of multiplexing is going on, since A: there is no wired ground, and B, you are controlling more LED's than you have pins going to the display.

Multiplexing manages this by using some trickery and persistence of vision. The pins for each part of the segment are all wired together. For example, the top segment on each of the three segments are all connected to one arduino pin. The common anode/cathode (depending on your specific display) for each of your three displays are wired separately however. Turning only one of the common pins on will cause only one display to function when the other pins set which segments are on. The micro controller then changes which common is active and what segments are on to illuminate the next character very quickly. It pulses between segments so quickly you cannot tell they are only on one third of the time each.

The wiring inside the display will likely look similar to this: http://www.modd3d.com/articles/wp-content/uploads/normal-multiplexing-s.gif
> 1 votes

---
Tags: arduino-uno, pins, wires, display, electronics
---


# Question
Title: Arduino Ethernet Shield connection to PC
is it possible to connect Arduino Ethernet Shield direct to PC and send a String variable? How can I read it later on the PC?

Will this code work?

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

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; // Shield MAC

byte pc[] = "192.168.0.13"; // pc IP
EthernetClient client;

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

  Serial.println("connecting...");

  delay(5000);
  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("Sample String");
    client.println();
  } else {
    Serial.println("connection failed");
  }

}

void loop()
{

}

```

# Answer
> 1 votes
No, you seem to be off on a tangent. There at least two problems:

1. The Ethernet library is designed to run on an Arduino board. If you set the IP address to the same as the PC IP address, the network will get confused and nothing will work reliably.
2. Are you asking how one can publish data from an Arduino board and read the results on a PC? This is easier. Just set up the web server example on the Arduino, and access it from a browser on your PC.

---
Tags: lan, ethernet
---


title: Code flow for precission applications

text:
# Question
Title: Code flow for precission applications
This is a question about programming. Mainly about the loop() function

As an example Consider code where you get data from an accelerometer, and if the Gs are high enough you do something.

Consider the following pseudocode:

```
void setup()
{
pinMode(1, INPUT);
bool flag = false;
}

void loop
{
int x= analogRead(1);
if (x>2)   //if the Gs we get from accelerometer
  flag = true;
if (button)  // if user hits the emergency button
  flag = true;

if (flag == true)
{
//GET SERIAL DATA (EG GPS COORDINATES)
//DO SOME HEAVY PROCESSING
}
}

```

Now loop runs repeatedly That means all the commands are executed in a continuous/serial style

Since that happens, what will happen if the accelerometer reading where (x\>2), which is what we look for, happen in the REAL world, at a time where in the CPU, the cpu is at that time processing or checking following commands in the program flow, like

```
if (button)  // if user hits the emergency button
      flag = true;

    if (flag == true)
    {
    //GET SERIAL DATA (EG GPS COORDINATES)
    //DO SOME HEAVY PROCESSING
    }
    }

```

Is there any chance that the cpu will miss real world events, because at that time the real world event occured, the cpu was processing other code. Or rather, not checking for that at that time. For our example, when the event occured, it wasnt checking the analogread() at that time, but was processing following code.

Should i worry about that?

# Answer
> 2 votes
Yes, in theory you can always miss events if you use a polling approach like that. Whether or not that's a problem depends on how accurate/frequent your data collection needs to be.

You can often mitigate the issue to an acceptable level if you are able to poll fast enough. That's determined largely by what else your main loop is doing. The more work it has to do elsewhere, the longer it will take between calls to `analogRead()` (and the more likely it is to miss something). Optimising your code can help.

You may also find that you can compensate sufficiently by interpolating between samples. Linear interpolation is very easy, although more complex options may also be possible, especially if you're processing the data offline afterwards.

If polling isn't working for you, then interrupts are the obvious alternative. Since you're reading an analog signal, you'd probably need some external circuitry which does a voltage comparison. You can get dedicated comparator IC's from all sorts of vendors, or use an op-amp circuit if you prefer.

If the signal goes over a pre-determined threshold, the comparator would have to pulse or assert a digital line. That could trigger an external interrupt pin on your microcontroller, which will execute custom handler code. See `attachInterrupt()` for more information.

# Answer
> 2 votes
one should take into account the frequency response of the signal versus the sample rate. Per Arduino's web site AnalogRead "It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second." or 5K/S for 2 AnalogRead's.

Where I read the output response of the accelerometer used on the Esplora is 300-400Hz. Note often there are additional filters between the accelerometer and the A2D input.

So in short there should be enough time to sample both X & Y along with a Z, leaving a margin of 10x. To do other things.

Just be careful not to do too much, with routines that block.

As a matter of practice, it is best not to rely on a loop for what ever timing it loops at. But rather setup a timer, either by interrupt or by watching the millis(), to trigger the analog reads at a known interval.

```
#include "TimerOne.h"
volatile int x,y,z;
void setup()
{
  Timer1.initialize(3000);         // initialize timer1 to overflow at 333hz
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}
void callback()
{
  x = analogRead(A0);
  y = analogRead(A1);
  z = analogRead(A2);
}
void loop()
{
  noInterrupts(); // to ensure they are all in sync.
  // do something with x,y&z
  interrupts();
  // do something else, that is not blocking.
}

```

---
Tags: programming
---


title: Confusion around LEDs on a breadboard

text:
# Question
Title: Confusion around LEDs on a breadboard
I am just starting out with an Arduino Diecimila and am playing around with LEDs, and am confused by why some circuits result in an LED not lighting up.

Successful Scenarios:

1. Yellow LED from pin13 to 16B on the breadboard, Green LED from 16A to GND. This works both LEDS light up.
2. Yellow LED from pin13 to 16A on the breadboard. Wire from 16E to 14E. Green LED from 14A to GND. This works and both LEDs light up.

Failed Scenarios:

1. Yellow LED from pin13 to 16A. Green LED from 16E to 14E. Yellow LED from 14A to GND. No LEDs light up. I would assume that all the LEDS are in series, and all 3 should light up, I assumed this would be exactly the same as my second successful scenario where the LED is acting the same as the wire.
2. Yellow LED from pin13 to 16A. Wire from 16E to 14E. Yellow LED from 15A to GND. Green LED from 16B to 14B. Here I have both Yellow LEDS lit, but the Green LED is not lit. I was expecting that the Green LED would have been in parallel and should have lit up.

In both failed scenarios I have swapped around the LEDs and proved that all the LEDs function.

There must be some basic concept that I am not understanding with the circuits, any ideas?

# Answer
Scenario 1 fails because yellow and green LEDs have forward voltages of about 2V each, so when putting 3 in series, you need a forward voltage to light them that exceeds the 5V available.

Scenario 2 fails because the wire you have in parallel with the LED provides a path with a very low voltage drop (close to 0V), so the path through the LED with a ~2V voltage drop is not taken (and if you remove the wire, the same reasoning as in scenario 1 applies, so nothing would work).

BTW, you should never run LEDs without a series resistor, as your experiments will surely demonstrate to you soon ;-)
> 6 votes

---
Tags: led
---


title: Serial.write() prints a variable twice

text:
# Question
Title: Serial.write() prints a variable twice
I have this code:

```
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

char clat[11];
char clng[11];

void loop()
{

        bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c))
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);
}

```

Now when all is done, the clng value is printed twice in the serial monitor. The value i get is in this format:

```
27.275869  15.151013
  15.151013

```

As you can see, clng is printed twice. Any ideas why is that?

# Answer
> 4 votes
The width parameter to `dtostrf()` is the width of the resulting string NOT including the null terminator. So you are overflowing the array.

Change:

```
char clat[11];
char clng[11];

```

to

```
char clat[12];
char clng[12];

```

and it should work.

---
Tags: serial, terminal
---


# Question
Title: Arduino Ethernet Shield: May I connect it to a PC connected to the internet via wifi?
I have an Arduino Ethernet shield.

May I **connect it to a machine that´s connected wirelessly to the internet** in order to get the arduino into the internet?

Or do I need to connect it **only** to a router?

# Answer
Assuming an Ethernet port on the PC, the Ethernet shield can be connected to it using an Ethernet **crossover** cable:

(*source: Wikipedia*)

Many recent PC network interfaces have automatic cross-over (Auto MDI-X), with which even a regular (straight) Ethernet patch cable will work.

This merely addresses the **physical Ethernet connectivity**.

For **actually routing IP packets** between the Arduino and the rest of the Internet, some software router or software bridge is required to run on the PC. Several open source routing products exist, especially for Linux and FreeBSD, but that is outside the scope of this StackExchange.

Finally, the Ethernet shield does not need a router, it an as well be hooked up to an Ethernet **switch** or **hub**.
> 2 votes

---
Tags: ethernet
---