# Question
Title: Convert a Bitstring into an integer value
I have got a String filled up with 0 and 1 and would like to get an Integer out of it:

```
String bitString = "";
int Number;
int tmp;

bitString = "";
  for (i=1;i<=10;i++)
  {
    tmp= analogRead (A0);
    bitString +=  tmp % 2;
    delay(50);
  }
// now bitString contains for example "10100110"
// Number = bitstring to int <-------------
// In the end I want that the variable Number contains the integer 166

```

# Answer
If you only need the string for printing you can store value in an integer and then use the Serial.print(number,BIN) function to format the output as a binary value. Appending integers to strings is a potentially costly operation both in performance and memory usage.

```
int Number = 0;
int tmp;

for (int i=9;i>=0;i--) {
  tmp = analogRead (A0);
  Number += (tmp % 2) << i;
  delay(50);
}
Serial.print(Number, BIN);

```
> 6 votes

# Answer
Check out `strtoul()`

It should work something like this:

`unsigned long result = strtoul(bitstring.c_str(), NULL, 2);`

Now you have a long variable which can be converted into an int if needed.
> 5 votes

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


# Question
Title: Cheapest way to connect android device to arduino wirelessly
I'm building a simple RC car which I want to control using android phone. The phone has bluetooth and Wi-Fi. My questions is what will be the cheapest way to connect the two devices at about 50-120m range? I have thought of the following:

* Cheap bluetooth module (like this). Will this fit into my problem? What range I will archieve using this module.
* Wi-fi module. I can set the android device to be "wi-fi hotspot", but the wi-fi shields are pretty expensive tho.

Any suggestions will be greatly appreciated.

# Answer
**Solution 1**

If you don't want to change the coverage radius, sadly none of them would help you to achieve a coverage of 50m.

But if you are not using a camera feed and just want to control, I think RF transceiver would be best solution for you. But to implement this you mist connect an Arduino Mega ADK to your android device. Serially receive your directions to mega and then transmit the directions over RF transceiver.

**Solution 2**

If you are willing to change the coverage range to less than 15m, you can use Wi-Fi Module. This will also help you to get live camera feed from your RC car to your phone. Forget about Bluetooth module as they are slow, less range.

You can increase the coverage of Wi-Fi Module if you have a Wi-Fi AP with huge transmit power. As long as the module is able to receive the signal from AP, your car would do great.

**P.S.** :- Here is a cool tip. Record every turn instruction and the time after which it was given. When the signal from transmitter or AP is absent for more than a particular time, you can program the car to take a U-turn and reverse the directions. Your car will come home without any instruction.
> 3 votes

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


# Question
Title: Use Higher Resistance Than Instructed in a Circuit
I'm following the "Get Started with Arduino" Guidebook, and I'm at the part where pulse width modulation (PWM) is discussed.

The instructions say to create a simple circuit with a breadboard, red LED, arduino (connected at pin 9 and ground) and a 270 ohm resistor. My power source will be the usb connection.

I have a 510 ohm resistor.

1. May I use it instead?
2. In general, will using a resistor with a higher resistance than intended in a circuit fry the arduino?

Thanks very much for your help. I'm new to arduino and electronic circuits. I have a Uno R3.

# Answer
> 4 votes
The cases where using a higher value resistor will damage a circuit exist, but are a bit less usual than the cases where it may simply produce a weaker result than desired, or a different frequency response than desired.

The primary situations where you do have to watch out come about where "feedback" is used to adjust one thing in relation to something else, and so putting a larger resistor on the "sense" side of the circuit can cause the "output" to be too high. Examples you might run into would be adjustable voltage regulators (obvious potential for damage with wrong output) and op-amps (higher than desired output, though more often distortion than damage).

It seems quite likely the the role of the resistor in your circuit is to limit the current through the LED - protecting that (and to a more vaguely best-practices degree, the ATmega pin) from damage.

For your needs it could be worth noting that a parallel combination of two 510 ohm resistors will give an effective resistance of half that, or 255 ohms. This is very close to the design intent, so might be a decent substitution (cheap resistors have a larger tolerance for piece-to-piece variation of value than that anyway).

Normally I would say the desired 270 ohms feels a little small, and that I'd prefer to start with 330 ohms. But if you do parallel two 510's, the 255 ohms would give just under 20ma of current if connected directaly across a 5v supply. Given your LED will have some forward voltage drop (varies widely with color), and your Arduino pin a little of its own, the actual voltage and thus current will be less - as a guess the end result is likely to be in the 15ma range, and not unreasonable for many common LEDs.

Resistors would also be a fairly easy component to salvage out of old electronics - the leads will end up short, but other than that you basically just need to read the color code, and perhaps confirm the value after removal with a meter.

Ultimately though it is worth buying an assortment of resistors - the 1/4 watt size are generally preferred for breadboarding as the leads are the best fit.

# Answer
> 3 votes
If the resistor is in series w the LED, it'll just be about half as bright when you use 510 vs 270 ohms. I=E/R and all -\> half the current. Your PWM will still work, but starting from a lesser brightness on down.

---
Tags: arduino-uno, led, resistor
---


title: Looking for a protocol, any hints?

text:
# Question
Title: Looking for a protocol, any hints?
I am looking for a multi-purpose wire protocol for Arduino.

Requirements:

1. Range of at least 500ft (200m)
2. No shield required
3. Able to communicate between Arduino and Raspberry Pi
4. Be able to run "point-to-multipoint"

# Answer
> 4 votes
There is nothing that will work given those constraints.

You only have low power 5V signals on the Arduino which won't handle your distance requirements.

You could look into RS-485 using a shield on the arduino side and a breakout board on the Raspberry Pi.

---
Tags: hardware
---


# Question
Title: DC-DC converter with Arduino not working
I've got a program running on the Arduino that is supposed to turn on and off a pump. currently, I am outputting the reads of the components that need to be read and it shows when the port (port 13) is supposed to turn on and when it's supposed to turn off. When I use a multimeter between the port 13 and ground, everything works as expected.

When I start the program and the port is off, I get a reading of 0.03v @20v max (to be more precise, I get 14.0 at 200mV) - Shouldn't this be zero? or is there always going to be some electricity flowing?

When the port is turned on: `digitalWrite(airPump, HIGH);` (and yes, airPump is set to 13), the voltage reads between 4.0 and 4.51 with spikes down to 3.65 on my multimeter set at 20v max. is it ever stable? (pictured below)

So, the main question is: I'm supposed to be sending the power from port 13 to a DC-DC converter. I tested the converter on a separate bread board just by itself. I used a DC power supply and set it to 4.5v, then ran the power through the vIn, grounded the ground pin and ran the vOut to the multimeter (then to ground with the multimeter) and I got it set to output only 2.5v with a constant 4.5 running into it. (pictured below)

I also tested whether or not changing the voltage input would change the output at all and it seems it does not, from 1.5-15v, the converter stays steady at 2.5v

Now when I do the exact same set up on the arduino with the power from port 13 running into the voltage in on the DC-DC converter, it gives me a reading of 0.01v. Any idea why this is happening?

I've checked probably over 30 times and rearranged everything just as many, but nothing seems to help. I can't get a stable 2.5V output from the converter with the arduino...

UPDATE: Below is a simple wiring diagram:

The image shows what it is supposed to do, but for testing purposes I made it so if the rH is higher than average (I just breath on it) then the pump will turn on.

# Answer
The arduino output pin cannot provide enough current to drive the pump. The DC-DC converter is not designed for this use.

You need external power supply with enough current to drive the motor that you switch on and off with the arduino output pin.

Search for "Arduino 3V DC motor control" for examples of how to do this, there are many options.
> 3 votes

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


# Question
Title: Measure LiPo / Li-Ion SOC or the ever standing question of how much juice is remaining in my battery?
So I have a project in which an arduino runs on a two cell LiPo battery and I need a fast, straight forward way to determine remaining battery charge (with an accuracy of 10% so I only have a readout with 10 LEDs on it) without using any major extra components (so using an external battery charge meter IC is cheating :P). How should I go about this?

(using arduino mini, LiPo is two cells: 7,4V 150mAh)

# Answer
Use a low-leakage op amp to divide the battery voltage by 8 (AV of 1/8). Connect the output to an analog input. Set your reference to the internal 1.1V reference (`INTERNAL`). Perform analog reads. Full battery will be about 975 ((8.4V/8)/1.1V⋅1024 ~= 977.45455). Empty will be about 700 ((6.0V/8)/1.1V⋅1024 ~= 698.18182). Note that the voltage scaling for Li-ion cells is non-linear; see the datasheet for the cells for the appropriate scaling (and if you want more precise full and empty values).
> 1 votes

# Answer
If you are using a single cell, then the Fuel gauge from Sparkfun would be great. Instead of reading analog values manually it sends the battery level via I2C.
> 0 votes

---
Tags: battery, software
---


# Question
Title: portd not writing on digital ports 5 and 7
I try to build a function generator (preferably a sine) with an R-2R ladder and a Arduino Leonardo by Borderless Electronics.

For performance reasons one should use `portd` instead of `digitalWrite`. However the signal is not at all what I want (just noise). So upon further investigation I found that the digital pins were never on `HIGH`. Pin 6 worked flawlessly. Furthermore I have tested the two failing pins with simple test programms and they behaved exactly as I would have expected.

Here is the code I use

```
 int sine[255];

 void setup()
 {
     pinMode(0, OUTPUT);
     pinMode(1, OUTPUT);
     pinMode(2, OUTPUT);
     pinMode(3, OUTPUT);
     pinMode(4, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(7, OUTPUT);

     float x;
     float y;
     for(int i=0;i<255;i++)
     {
          x=(float)i;
          y=sin((x/255)*2*PI);
          sine[i]=int(y*128)+128;
     }
}

void loop()
{
     for (int i=0;i<255;i++)
     {
          PORTD=sine[i];
          delayMicroseconds(10);
     }
}

```

I tested this with two Arduinos of the exactly same type.

**Question:** Why are pins 5 and 7 never on `HIGH`?

**Edit:** I have simplified everything down to one statement in the loop: `portd = x;`

I vary x manually

**expected** findings:

x -\> #pin that is on high

0 -\> None

1 -\> 0

2 -\> 1

4 -\> 2

8 -\> 3

...

128 -\> 7

**actual** findings

x -\> #pin that is on high

0 -\> None

1 -\> 3

2 -\> 2

4 -\> 0

8 -\> 1

16 -\> 4

32 -\> None

64 -\> None

128-\> 6

I test this by simply connecting an oscilloscope to the output pins. The behaviour is extremely strange since the pins seem to be in random order, some even missing to `portd`. Furthermore `portd = B11111111`, according to the manual, is equivalent to `portd = 255;` and should set all pins on `HIGH`. But in my case it sets every pin to `HIGH`, except pins 5 and 7 are on `LOW`.

# Answer
> 4 votes
This is because on ATmega 32u4, which is used in Arduino Leonardo, pins 5 and 7 are not mapped to port D but to port C and E respectively, as you can see in the ATmega 32u4 - Arduino Pin Mapping.

So you will have to:

* either find another port where all 8 bits are available as digital outputs (note that I'm not sure one such port exists)
* or split each `sine[i]` in 2 parts because you will have to work with 2 ports at the same time.

# Answer
> 2 votes
As @jfpoilpret points out, Arduino pins are not always mapped to port bits in a straightforward manner, and it’s crucial to understand the mapping for your particular model.

In fact, the Arduino Leonardo is designed in a way that **none** of the ports has all 8 bits usable as I/O pins. As far as the microcontroller is concerned, ports B and D each have all 8 bits available, but the Arduino Leonardo/Micro design uses one bit on each port for a LED.

I would also recommend that if you’re using a PORTx register directly, instead of going through the Arduino API, that you also use the DDRx register to set pin directions, instead of trying to use `pinMode`.

---
Tags: programming, pins, arduino-leonardo
---


# Question
Title: How many total digital pin outs does the Arduino Yun have
I have read the details on the products page for Arduino Yun but I have also read, on a Arduino forum, that there are only 18 digital pins because of Tx, and Rx. Is this true? I am not worried about the PWM, or analog capabilities of the pins, just purely digital.

# Answer
According to the official specification, it has 20 digital IO pins which can be used with `digitalRead()` and `digitalWrite()` etc.. As is typical on Arduino boards though, pins 0 and 1 *also* act as serial Rx and Tx (respectively).

You can program it to use them for either purpose.

The information you read might be referring to problems with uploading though. If you have something physically connected to pin 0 and/or 1, then you may have to disconnect it while you do an upload, otherwise it can interfere with the communication between your computer and the microcontroller.

If you're doing a lot of tinkering, then sometimes it's simply easier to avoid using pins 0 and 1 altogether, meaning you'd only have 18 IO pins left.
> 3 votes

---
Tags: arduino-yun
---


# Question
Title: Detecting ball moving between IR pair and handling ambient light changes
I plan to use the SEN-00241 IR Emitter and Detector pair to detect a ping pong ball moving fast between them.

I understand I could watch for voltage changes to detect this passing object, however how do people generally deal with ambient light changes? From my research it seems that the voltage will change with ambient light, and although I can take steps to create funnel vision between the 2 I'm sure it may still be an issue.

Would you take constant readings and find averages over 10 consecutive readings to allow for changes in ambient light and set a new baseline reading? Then if the voltage changes dramatically and only for a few reads then I know that was the ball and not to change the baseline reading.

# Answer
this is the same problem that IR remote/television has; how can TV they tell if that high voltage is a direct light or a logic 1 sent by remote? Simply because remote does not send a "HIGH" signal, but a modulated one, tipically at 36KHz. This mean a logic "HIGH" is a train of "HIGH-LOW" at 36KHz (you can see it as PWM at 50%duty cicle and 36KHz frequency)

Ambient light des not have fast variation, and inside light are at 50-60Hz, so they will be "filtered" out.

So, until you see high voltage change at 36KHz, you have your beam fine, if it is not the case, then look at voltage: if fixed at normally low voltage, beam is broken; is fixed at normally high voltage then some light stronger than your emitter is "blinding" the sensor.

note that because 36KHz is a very use frequency on Remote, there a a lot of chip that will emit or read a modulated IR, but expose a normal digital input/output, but still can be done by software, expecially if hardware assistet (like PWM for output), interrupt for input
> 1 votes

---
Tags: arduino-uno
---


title: Parallel shift registers

text:
# Question
Title: Parallel shift registers
I'm having trouble with using parallel shift registers, I've studied example codes and I've come up with this function to set the pins to on or off. The problem is the first time the function runs all the output pins are set to HIGH regardless of the values in the array.

```
    void updateRegister(int ClockPin,int DataPin,int LatchPin){
      int pinState;//Holds the state of the data pin
      pinMode(ClockPin, OUTPUT);//Sets the pinmode of the pins
      pinMode(DataPin, OUTPUT);//Sets the pinmode of the pins
      pinMode(LatchPin, OUTPUT);
      digitalWrite(LatchPin, 0);//Turns latch off to prevent bleedover while shifting

      digitalWrite(DataPin, 0);//clear everything
      digitalWrite(ClockPin, 0);//clear everything

      for (int i=1; i<=16; i++){//Repeats 16 times with i increment from 1 to 16
          if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
          else{pinState= 1;}//If it equals false set it to 0, LOW

          digitalWrite(DataPin, pinState);//Sets the data pin depening on the pinstate
          digitalWrite(ClockPin, 1);
          digitalWrite(DataPin, 0);
          digitalWrite(ClockPin, 0);
        }
      digitalWrite(LatchPin, 1);//Turns latch pin back on
    }

```

I'm storing the boolean values of the each pin in an array called Qout which is defined and all set to false like this

```
    boolean Qout [17];//Holds the state for each pin
    for (int i = 1; i < 17; i++ ) {Qout[i]=false;}//Sets all output to off

```

I know I should start at Qout\[0\] but it just makes it way more confusing.

Can someone help me fix my function so that it actually works.

This is what I based it on ShftOut23

# Answer
First of all, fix the following part of your code:

```
if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
else{pinState= 1;}//If it equals false set it to 0, LOW

```

into:

```
if (Qout[i])
{
    //Checks the array for the value and if it is true sets the pinstate to 1, HIGH
    pinState = 1;
}
else
{
    //If it equals false set it to 0, LOW
    pinState = 0;
}

```

Of course, if you always set `pinState` to `0`, it won't work as you expect :-)

Note that you should rather use `HIGH` and `LOW` constants (more readable) instead of `1` and `0`.

Finally, you could make the code much simpler this way:

```
pinState = (Qout[i] ? HIGH : LOW);

```
> 4 votes

---
Tags: shift-register
---


# Question
Title: Can a PC connect to an Arduino for serial communication without installing the entire dev kit?
I'd like to send a prototype board to a friend pre-programmed and wired. Ideally they should just need to plug in the USB and connect to it over a serial COM port.

With another laptop I used for testing I had to install the full dev kit, sketch editor and all to get it working.

Can I somehow send just the portion of the kit that provides the COM drivers and not the rest? Is there a prebuilt install for just that portion?

# Answer
On Windows in `C:\Program Files\Arduino` there is a folder called `drivers`, which contains all the drivers for the Arduino boards. I think that's what you are looking for.
> 7 votes

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


title: Arduino Interrupt Debouncing

text:
# Question
Title: Arduino Interrupt Debouncing
I have an issue with debouncing. I am using a MCP23017 as an I/O-extender with an Arduino. This uses I2C to communicate with each other.

A variable amount of switches is connected to the MCP23017 (0-16 switches). On change of the inputs, an interrupt is generated and the Arduino captures this on rising edge. So whenever a button is pushed or released, an interrupt is generated.

Now I'm confused as how I should debug them. One option would be to set a delay after an interrupt (of let's say 50 ms), before turning the interrupts back on. This could have an issue however, since multiple inputs are connected to the same interrupt line.

Another option is to have a timestamp or something for the last time each switch was changed, and check if the time difference is big enough, otherwise ignore the next pulse. The problem with this is that it uses quit some resources as I have limited memory and there can be up to 8 extenders (so 8 * 16 = 128 inputs).

What is the most efficient way to handle these interrupts with debouncing?

# Answer
> 2 votes
Add debouncing circuitry if you can; it's not that difficult.

# Answer
> 2 votes
Depends on the application.

Define efficiency. What are you looking to optimize for? Manhours spend coding/testing, processor speed, response time?

Are theses keys to a piano synth? Yes you'll want interrupt speed, and each key needs to not affect the surrounding keys.

Is it going to be rare that two keys are pressed anywhere near each other? a timeout for the ISR is perfectly legitimate.

Will the user not observe any lag when he flips a switch and resources are tight? Then polling could be a viable option.

Are the EMI concerns and you need to filter out false positives? Well you're going to need do some more. Like sampling for sustained values or counting how long until the falling edge occurs.

There are so many options depending on what you want it to do.

---
Tags: c
---


title: Unable to read text file from server

text:
# Question
Title: Unable to read text file from server
I saw the Web client Example , In the example, the server connection is initialized in `setup()`. But I want the server to update the text file every time. So, I need the server connection to be in `loop()`.

But, it is not working. Where is the problem in my code.

```
#include <GSM.h>

#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "yourdomain.com";
char path[] = "/current.txt";

int port = 80; // port 80 is the default for HTTP

void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
Serial.println("SMS connected");

// connection state
boolean notConnected = true;

// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while(notConnected) {
   if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
    (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
    notConnected = false;

else {
     Serial.println("Not connected");
     delay(1000);
    }
   }
Serial.println("GPRS connected...");
Serial.println(" Connecting to Server ");
}

void loop() {
if (client.connect(server, port)) {
  client.print("GET /current.txt");
  Serial.print("GET /current.txt");
  client.println(" HTTP/1.1");
  Serial.println(" HTTP/1.1");
  client.println("Host: www.yourdomain.com");
  Serial.println("Host: www.yourdomain.com");
  client.println("User-Agent: Arduino");
  Serial.println("User-Agent: Arduino");
  client.println("Accept: text/html");
  Serial.println("Accept: text/html");
  client.println("Connection: close");
  Serial.println("Connection: close");
  client.println();
  Serial.println();
  Serial.println("\nCOMPLETE!\n");
  //client.stop();

} else {
  Serial.println("connection failed");
  Serial.println("\n FAILED!\n");
}

if (client.available()) {
  char c = client.read();
  Serial.print(c);

} else {
  Serial.println();
  Serial.println("disconnecting.");
  client.stop();
}
}

```

# Answer
> 0 votes
Its working as long as the connection doesn't break or the server doesn't stall. We must wait till the response .

```
while (client.connected())
{
 while(client.available())
 {
 char ch = client.read();
 Serial.print(ch);
 }
}
 client.stop();

```

---
Tags: arduino-uno, gsm, web-server
---


title: 8-segmet LED's on Adafruit Trinket

text:
# Question
Title: 8-segmet LED's on Adafruit Trinket
I would like to have an array of eight 7- and 8-segment LED numerical displays on my Adafruit Trinket. I know that there are some prebuilt arrays of 4 LED's. So 2 in array would do just fine. However, my Adafruit Trinket doesn't have enough ports for that. I have heard something about connecting it to a small piece of controlling hardware that makes me able to have way less ports in need. What is the appropriate way of connecting a lot of those LED's on only a few ports on a micro controller?

My ideal output would be as follow: 88 88:88:88 or maybe 88 88.88.88 So ideally there would be a small space between the first group of 2 digits and the rest. Basically, the last 6 digits will represent a time in minutes, seconds and hundreds of seconds.

# Answer
> 2 votes
For LED displays, I advise using a MAX7219.

This circuit:

* can manage up to 8 digits (7-segments + 1 LED for DP or colon separator) or up to 64 LEDs
* needs only 3 pins to manage display
* can be daisy-chained if you need to interface with more than 64 LEDs
* requires only 1 resistor to be fully functional
* is easily supported on Arduino with this library

I have used it in several circuits and happy with it.

Note that there also other libraries that support this circuit but I haven't used them.

This circuit has only one downside: its price (about $10 each); but the price is counter-balanced by its simplicity and the fact you don't need any additional component (e.g. transistors) besides a simple resistor.

---
Tags: led, display
---


title: Animated LED Strip & Sensing an Object

text:
# Question
Title: Animated LED Strip & Sensing an Object
Problem: Have an LED strip do some animation (say it takes 15 seconds for that line of code to run) meanwhile, have a sensor (tried methods: PIR sensor and ultrasonic sensor) watching to see if an object passes by. If it senses an object, stop the light animation and make the lights do something else.

Issues: The PIR sensor takes too long to reset... I have the timing turned all the way to minimum and I am still able to count 12 seconds before it starts sensing motion again. (Is there anyway to override this in the code?) The other issue is the ultrasonic sensor, as far as I know, can't reliably run the first animation and watch for a change in distance then call an interrupt since an interrupt can only happen on FALLING, RISING, LOW, or CHANGE. This is an issue because the ultrasonic sensor is continuously sending LOW to HIGH then back to LOW for its pulses.

OVERALL QUESTION: How can I effectively sense if an object passes by a sensor, run new LED animation then back to where it left off without having to wait 12 seconds every time. Is there some other hardware I could try? Please help!?

# Answer
> 1 votes
It seems as you are using the `delay();` function for your code. The reason that it doesn't run anything is your Arduino does *nothing* during the function. The easiest option IMHO is using `millis();`. This will "return" a long datatype. Some example code (modified from example sketches in Arduino IDE):

```
/*
 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen
 modified 5/16/14 by Anno. Penguin
 This example code is in the public domain.
*/

const int ledPin =  13;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds)

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

void loop()
{
  //Sensor code
  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);
  }
}

```

Obviously, your code will be more complex than that. This one only blinks it, but you'll have to do some creative logic here. I don't know what the animation is, but most likely you'll need to add a few more variables (make sure to declare them outside `loop()` so they aren't disposed of each iteration!).

---
Tags: sensors, led
---


# Question
Title: To connect a simple toy circuit and trigger with an arduino?
I have a small circuit from a toy sword that has an LED and a small speaker. It was powered by a couple of small coin cells.

I am trying to figure out how to connect it to my Arduino so I can trigger it. If I attached the circuit directly to the GND and +3.3V and press the switch in it I get the sound of a sword and flashing LED as desired.

Now I want to somehow get the Arduino to trigger the circuit but am very new to Arduino and quite unsure of how to approach this.

Can anyone advise how best to work with an existing low power circuit that can use the Arduino's power rails but needs the switch integrated?

Sorry for the noob question.

# Answer
You'll probably want to use a transistor to switch it on/off. You *could* just use the Arduino's digital pin but they can only supply a limited amount of current. Transistors can work with larger currents. The Arduino switches the transistor and it powers the external circuit.

There are a couple of existing questions that may help you.

jippie's answer in the first link shows an example schematic for hooking up a transistor with a bunch of LEDs but you would replace them with your own circuit:
> 1 votes

---
Tags: arduino-uno, pins
---


title: Timer1 stops firing

text:
# Question
Title: Timer1 stops firing
I am trying to use interrupts to play notes on a speaker. Timer2 works fine, but after about 15 seconds, Timer1 stops firing for about 5 seconds, and then it comes back on. If I keep running the sketch, it will stop and resume every now and then.

Here is my code:

```
#define SPEAKER1 8
#define SPEAKER2 7
volatile bool swap1;
volatile bool swap2;

ISR(TIMER1_COMPA_vect)
{
    digitalWrite(SPEAKER1, swap1);
    swap1 = !swap1;
}

ISR(TIMER2_COMPA_vect)
{
    digitalWrite(SPEAKER2, swap2);
    swap2 = !swap2;
}

void playNote1(unsigned note) { //Play a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitSet(TCCR1B, CS10);
    bitSet(TCCR1B, CS12);
    unsigned ticks = (16000000 / 1024) / (note);
    ticks /= 2;
    OCR1A = (ticks <= 65535 ? ticks : 65535);
    SREG = oldSREG;
}

void playNote2(unsigned note) { //Play a note on Timer2.
    uint8_t oldSREG = SREG;
    cli();
    bitSet(TCCR2B, CS20);
    bitSet(TCCR2B, CS21);
    bitSet(TCCR2B, CS22);
    unsigned ticks = (16000000 / 1024) / (note);
    ticks /= 2;
    OCR2A = (ticks <= 255 ? ticks : 255);
    SREG = oldSREG;
}

void stopNote1() {  //Stop playing a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TCCR1B, CS10);
    bitClear(TCCR1B, CS12);
    SREG = oldSREG;
}

void stopNote2() {  //Stop playing a note on Timer2.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TCCR2B, CS20);
    bitClear(TCCR2B, CS21);
    bitClear(TCCR2B, CS22);
    SREG = oldSREG;
}

void setup() {
    pinMode(SPEAKER1, OUTPUT);
    pinMode(SPEAKER2, OUTPUT);
    pinMode(13, OUTPUT);
    // initialize timers
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B
    // turn on CTC mode:
    bitSet(TCCR1B, WGM12);
    bitSet(TIMSK1, OCIE1A);

    TCCR2A = 0;     // set entire TCCR2A register to 0
    TCCR2B = 0;     // same for TCCR2B
    // turn on CTC mode:
    bitSet(TCCR2A, WGM21);
    bitSet(TIMSK2, OCIE2A);
    sei();          // enable global interrupts
}

void loop() {
    playNote1(523);
    delay(1000);
    stopNote1();
    delay(500);
    playNote1(131);
    delay(2000);
    stopNote1();
    delay(500);
}

```

# Answer
> 2 votes
The problem you have is that **you never reset Timer1 counter (`TCNT1`) when you stop a note and then play another one**.

Also, changing the clock divider selection to "*no clock*" by clearing bits **CS10** and **CS12** as you do is not the most effective way to stop the timer; in fact, rather than stopping it, you can let it run but just **disable its interrupts**.

I have modified your program and this worked correctly:

```
#define SPEAKER1 8
volatile bool swap1;

ISR(TIMER1_COMPA_vect)
{
    digitalWrite(SPEAKER1, swap1);
    swap1 = !swap1;
}

void playNote1(unsigned note) { //Play a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    unsigned ticks = (16000000 / 1024) / (note);
    ticks /= 2;
    OCR1A = (ticks <= 65535 ? ticks : 65535);
    TCNT1 = 0;
    bitSet(TIMSK1, OCIE1A);
    SREG = oldSREG;
}

void stopNote1() {  //Stop playing a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TIMSK1, OCIE1A);
    SREG = oldSREG;
}

void setup() {
    pinMode(SPEAKER1, OUTPUT);
    pinMode(13, OUTPUT);
    // initialize timers
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B
    TCCR1C = 0;     // same for TCCR1C
    // Set clock divider
    bitSet(TCCR1B, CS10);
    bitSet(TCCR1B, CS12);
    // turn on CTC mode:
    bitSet(TCCR1B, WGM12);
    bitClear(TIMSK1, OCIE1A);
    sei();          // enable global interrupts
}

void loop() {
    playNote1(523);
    delay(1000);
    stopNote1();
    delay(500);
    playNote1(131);
    delay(2000);
    stopNote1();
    delay(500);
}

```

Note that I have removed all code for Timer2 as it does not play any role in the initial problem.

The important changes are:

1. `setup()` now performs Timer1 setup completely (CTC mode, clock divider); note that I also included **TCCR1C** to ensure full setup (it is preferrable as Arduino libraries may have initialized it differently before `setup()` is called); it also ensures Timer1 interrupts are initially disabled.
2. `playNote1` now clears `TCNT1` **and then** enable Timer1 interrupt for `TIMER1_COMPA_vect`
3. `stopNote1()` just disables Timer1 interrupt for `TIMER1_COMPA_vect`

To be complete, you would also want to limit **useless consumption** on output **pin 8**, thus stopping a note should also force its output level to `LOW` (or `HIGH` depending on your actual circuit behind, but `LOW` is more likely):

```
void stopNote1() {  //Stop playing a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TIMSK1, OCIE1A);
    swap1 = false;
    SREG = oldSREG;
    digitalWrite(SPEAKER1, LOW);
}

```

### Now what about your code for Timer2, the code is the same, so why does it work?

Actually it doesn't :-)

But you can't hear the difference between Timer2 is an 8-bit counter so if you don't reset it, then it won't take long until it reaches 255 and resets to 0, so only the first wave phase will be wrong but your hear won't notice that...

So **you should also modify the code for Timer2** to make it correct.

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


# Question
Title: Why is that any sensor signal need to be hooked up to the interrupt pins on Andruino boards?
I have come across some Andruino Sensors like Motion, Light and all recommend to be connected to pin 2 or 3 on Andruino Uno board which are interrupt pins. This is especially true if you are looking for HIGH or LOW values. Why is that to be connected to interrupt pins?

One example would be is I used CC3000 Wifi Breakout and Motion sensor. Both were in fight to occupy the interrupt pin 2. I have seen the Motion sesnor not working correctly after getting it's signal hooked to Pin 4\[It has pull up resistor enabled\]

What should I do if i need to hook up more sensor which uses the limited interrupt pins and how should i handle the above scenario?

# Answer
The interrupt pins are used to notify the MCU that a device needs attention. The INTx pins are chosen first because they are easy to program for; each gets a dedicated interrupt vector and hence ISR.

There is another type of external interrupt though, the Pin Change interrupt. This can be invoked via any of the PCINTxx pins on the device; on the '328 *any* pin can act as an interrupt.

The main difference between INT and PCINT is that PCINTs are grouped into banks of 8, which means that once the ISR has been invoked the appropriate pins need to be checked for their level, which furthermore means that it is possible to misread an interrupt if a bank is shared by multiple devices and the interrupt pulse itself is very short.

Further details can be read in the "External Interrupts" and "Interrupts" sections of the MCU datasheet.
> 6 votes

# Answer
Ignacio provides a great answer on the differences between the two types of interrupts. But to add to that, it isn't a universal requirement to even use an interrupt.

**Polling** is also a possibility, though it has been compared to periodically picking up the phone to see if anyone is trying to talk to you.

* Advantages of using an interrupt can include faster response, background response while a program is primarily doing something else, and often an associated ability wake up the processor from low-power sleep mode used in battery powered gadgets.
* But polling can have a role, for example when the program runs in a tight loop and can only take action in response to input at certain times anyway - an interrupt service routine that merely sets a flag to tell the main program loop that something has happened may or may not be much benefit.
* Often the best solution is a hybrid approach - an interrupt service routine records events - especially ones which might vanish or be repeated before the main program loop can poll for them. Then when the main program loop reaches a logical decision point, it checks the flags or event queue to see if the interrupt service routine has recorded anything to which it should respond. Serial receive is typically handled this way in the Arduino framework.
> 4 votes

---
Tags: sensors, interrupt
---


# Question
Title: Initialize a "Matrix" object in my own library?
So, I'm trying to make a custom library to drive a 8x8 Bi-Color LED Matrix from 2 MAX7219's that incorporates two "Matrix" objects from the "Matrix" library and I cannot, for the life of me, figure out how to initialize them in my class. Can someone help me? By the way, I have been programming for 8 years, and consequently have a decent knowledge of the topic! Here is my current code:

header file

```
#include "Arduino.h"
#include "Matrix.h"
#include "Sprite.h"

class ZackBiColorMatrix{

    public:

        ZackBiColorMatrix(byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG);

        Matrix r;
        Matrix g;

        void setLED(byte col, byte row, byte val, char color);
        void writeSprite(byte x, byte y, Sprite sp, char color);

    private:

        byte redData;
        byte redLoad;
        byte redClock;

        byte greenData;
        byte greenLoad;
        byte greenClock;

};

```

and the .cpp file:

```
#include "Arduino.h"
#include "Sprite.h"
#include "Matrix.h"
#include "ZackBiColorMatrix.h"

ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG) {

    redData = dataR;
    redLoad = loadR;
    redClock = clockR;

    greenData = dataG;
    greenLoad = loadG;
    greenClock = clockG;

    r = Matrix (redData, redClock, redLoad);
    g = Matrix (greenData, greenClock, greenLoad);

}

void ZackBiColorMatrix::setLED (byte col, byte row, byte val, char color) {

    if (color == 'g') {

        g.write (col, row, val);

    }
    else if (color == 'r') {

        r.write (col, row, val);

    }

}
void ZackBiColorMatrix::writeSprite (byte x, byte y, Sprite sp, char color) {

    if (color == 'g') {

        g.write (x, y, sp);

    }
    else if (color == 'r') {

        r.write (x, y, sp);

    }

}

```

Also, I use the Eclipse Arduino IDE if that matters.

# Answer
This is a C++ question actually.

In C++, you initialize class members in the class constructor definition by using a "member intialization list" as follows for your example:

```
ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG)
:   r(dataR, clockR, loadR),
    g(dataG, clockG, loadG) {
    ... Additional initialization here
}

```

This is a special C++ construct (note the colon `:` after the constructor declaration but before its implementation).

Also note that, in your example, I think you don't need to declare `redData`, `redLoad`, `redClock`, `greenData`, `greenLoad`, `greenClock`, sicne they are not being used once your 2 `Matrix` fields have been initialized.

Hence you could simplify your class further, I think.
> 1 votes

---
Tags: c++, library, led, class
---


# Question
Title: Why does the Arduino Due have a native and USB programming port?
According to the schematics, the Arduino Due has two USB inputs:

1. Native
2. Programming

Why is this? And when would I use the different ports?

# Answer
> 8 votes
Either port can be used for programming, but the native USB port lets you do other things:

> It also enables the Due to emulate a USB mouse or keyboard to an attached computer. To use these features, see the Mouse and Keyboard library reference pages.
>
> The Native USB port can also act as a USB host for connected peripherals such as mice, keyboards, and smartphones. To use these features, see the USBHost reference pages. http://arduino.cc/en/Main/arduinoBoardDue

So you can use the Due to interface with USB devices or connect it to your computer and have it act like a USB device.

---
Tags: arduino-due
---


title: arduino EM408 GPS problem

text:
# Question
Title: arduino EM408 GPS problem
I have written this little snippet of code to interface with EM408 GPS.

```
#include <SoftwareSerial.h>
SoftwareSerial GPS = SoftwareSerial(2,3);  //rx,tx
void setup()
{
  GPS.begin(4800);
  Serial.begin(9600);
}

void loop()
{
  //Serial.print(GPS.read(), BYTE);
  Serial.write(byte(GPS.read()));  //as of Arduino 1.0
}

```

Hardware side i have these connections:
ENABLE: 3.3V
Vcc : 3.3V
Ground: Ground
Rx, Tx correctly connected to arduino and correctly initialized with SoftwareSerial

However, the values i get are just junk data

```
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

```

I get these without ending... I experimenting with changing the baud rate, still the same thing goes on. Any ideas?

EDIT:
I used to get random junk data before with the EM406 gps module, but i solved it by casting everything to BYTE. I have tried both approaches here, but the results are the same...

# Answer
> 2 votes
The problem you get is that `read()` does not wait for a byte to be available, it just returns `-1` if there is no byte available; converted as an unsigned byte that becomes `255`.

In **ISO-8859-1**, which I guess is the encoding that your serial monitor is using, `255` translates to `ÿ`, so this is exactly what you observe.

Fixing this problem is straightforward, just check that a byte is available on `SoftwareSerial` before reading it:

```
void loop()
{
    if (GPS.available()) {
        Serial.write(byte(GPS.read()));  //as of Arduino 1.0
    }
}

```

---
Tags: serial
---


# Question
Title: Is there a way to test whether the UART Tx buffer is empty without waiting?
Is there a way to test whether the UART Tx buffer is empty without waiting?

`serial.flush()` waits, so it won't help me.

I tried looking into `serial.SerialEvent()`, but the link was broken on the Arduino reference page.

Can anyone point me to a description of it?

# Answer
It doesn't look like that function is implemented. The source for HardwareSerial.{cpp,h} are in `/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino` under OS-X. (Someone better versed in Window than I may have to chime in here to point you to that source location.)

Taking HardwareSerial::available() as a model, create a new function, say, HardwareSerial::txremaining(), that does the same thing, but for the transmit buffer.

Left as an exercise for the student:
Make a common function that returns the contents of an arbitrary ring-buffer and use it in both ::available() and ::txremaining().
> 1 votes

---
Tags: serial, uart, softwareserial
---


# Question
Title: Send text according to an ultrasonic measurement, on battery
I have this big bucket where I would like to install an arduino on the top of the bucket where it would calculate the % of the bucket being filled up with water. Then, every day at night the arduino will send a text message (via SIM card) to the server where it would collect data for that bucket.

As far as a beginner point of view, I can understand that I will need:

an Arduino Board PING))) Ultrasonic Distance Sensor Battery pack that would allow to run the board for a year? and the Arduino GSM Shield (integrated antenna) OR the GSM/GPRS Module M10?

My question is: What arduino board do I need for my setup? How long will 2 large or 4 AA batteries lasts for receiving a value from the ultrasonic sensor once a day and sending that value to a server? The point of the instrument is to be as small as possible.

# Answer
> 3 votes
First of all: what is the intention of your setup? What are you trying to measure, what do you want to do with the data? Where is the bucket located, in your backyard or miles away in a forest?

I foresee some problems with your current setup.

First of all, you need a enclosure that keeps your 'duino and other components dry and at a comfortable temperature. I don't know how severe the weather conditions are, but stuff can get unreliable when used close to the min/max operating temperatures. Can you find an enclosure that can protect your electronics against the elements?

My advice: think of a good enclosure.

Second, do you really think PING))) is the best sensor? Have you already tested how it behaves around water? Are the measurements correct? Another option would be an array of metal strips, one connected to +V or GND, the others to separate ports on your Arduino. Space them evenly from the bottom of your bucket to your maximum water level (drill a hole in the bucket to prevent overflowing or drowning your duino). Poll the pins at a predefined interval (not too short, keeping battery life in mind) to see which ones make contact with the water (allowing current to flow from/to the pins from/to +V/GND)

My advice: do some research on sensors, or try to make your own

The best way to communicate with your 'server' (what are you going to use?) totally depends on how far it is from the bucket. GSM shields are quite pricey, other alternatives may be preferable (and do not have additional phone costs). Is your server on the other site of the window? Bluetooth? Somewhere in your backyard? Zigbee. Across the street? High-power Zigbee (if allowed by local authorities). Far away but with WIFI access? Zigbee, posting data to an online place. In the middle of nowhere but with great cell phone reception? GSM.

My advice: check out wireless communication possibilities. There's a ton of them, each with pros and cons.

Last hurdle, energy. Your battery setup will most definitely NOT be able to provide enough energy for a whole year. There's just too little juice in them.

Arduino and standalone AVRs often have a sleep mode, in which power consumption can be very *very* low. Google is your friend on this one. Still, that won't let your setup last a year.

Unless there was a gigantic glowing ball of plasma hanging around some 8 lightminutes from here and we could harness its incredible power with the use of photovoltaic elements... Wait, we totally can! Using (a) solar panel(s) and some simple circuitry you can recharge your batteries, and depending on the weather conditions this could keep your project up and running for a year.

My advice: get down and dirty with small solar panels.

I really appreciate your ambition. If done right, this could be quite the project for a beginner! Just make sure you thoroughly research every part of the system, on itself and as a whole. This could prevent a lot of disappointment and unnecessary costs, while only expanding your knowledge.

Good luck!

---
Tags: gsm
---


# Question
Title: Data packet format when USB initialized as COM port
Does anyone know how the data in data packet looks like when the USB is initialized as COM port?

I have a Arduino Mega 2560. I have initialized COM port with a baud rate of 9600. I know that there are four types of USB packets as

1. Token Packet (Commonly used for device identification and transaction initiation.)
2. Data Packet (Contains the data that needs to be transferred from host to client or vice-versa.)
3. Acknowledgement Packet (Acknowledgement for error-free data reception.)
4. Special Packets (Hub to hub communication and speed differential.)

The payload in data packet is formatted as

**DATA1 \>\> PAYLOAD \>\> CRC16 ; DATA2 \>\> \>\> PAYLOAD \>\> CRC16 ;** etc.

Till this point I am clear about whats happening.

Now all I want to know is

* How the data is structured in the PAYLOAD section, when USB is initialized as COM port?
* How the baud rate comes into picture i.e how a particular baudrate is achieved in this type of communication?
* How is communication in terms of packet sequence? Does the sequence of packets change? (Like token\>\>data\>\>ack\>\>data\>\>ack\>\>...)

I really need to know this urgently as I am working on program that has to connect with 3 MEga2560 boards through a USB hub. I want to fix my design constraints depending on what is the maximum baud rate that I can achieve for all boards.

# Answer
Once the USB connection is initialized as a COM port, it no longer utilizes traditional USB packets (only internally). It acts as a regular COM port. This layer of abstraction is created by 8u2 chip on Arduino side and by the driver on the PC side.

If you need to use the USB without the COM port abstraction, you have to probably configure the 8u2 chip to behave this way. I think it should be possible to configure to act as some HID device for example. You would also need to take care about the PC side and you might have to write your own driver.

For a guide on hacking and configuring the 8u2 chip on Mega, see following link:

http://arduino.cc/en/Hacking/DFUProgramming8U2
> 1 votes

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


title: SoftwareSerial error

text:
# Question
Title: SoftwareSerial error
I have arduino , upon arduino I have Arduino GSM shield (Tx-2, Rx-3, Modem reset-7) and upon it, I have the Adafruit GPS Logger shield. I am trying to send sms of Latitude from the GPS Logger shield to my numer through GSM shield. I am getting a error ..

```
SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_3'

GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here
SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_4'

GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here
SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_5'

GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here

```

What is the meaning of this error ? what should I do to solve it?

# Answer
> 2 votes
This error means, that there is library overlapping on a vectors. To solve this error, you need to modify your Library file :

STEPS :

1. Remove the Softserial Library
2. Download AltSoftSerial library
3. if you have shield then you need to replace AltSoftSerial in place of SoftwareSerial in both .cpp as well as .h files.
4. Import AltSoftSerial library in place of SoftwareSerial in the sketch.

Execute .

---
Tags: arduino-uno, gsm, softwareserial
---


# Question
Title: How to program an empty Mega2560 with an Arduino sketch?
I am writing code on Arduino mega. My current code is working fine. However, I'm not using all the pins.

My question is:

1. I have the hex file for my code and I can purchase a Mega2560 MCU. Is there any way to upload the hex file to it and how?
2. What are the circuits I would need to to build?
3. Eagle files of the Arduino mega are available here. Is this circuit more than enough?

# Answer
> 3 votes
If you buy an empty mega2560 IC. It won't contains any bootloader. That means that you need an extra circuit, a programmer, to upload your HEX file into your MCU. "When to use the bootloader" questions link

But, if you buy your mega2560 from an Arduino provider, you should be able to order the MCU with the arduino booloader already programmed. Then a simple serial link from your PC to your MCU will suffice to program the MCU with your Arduino sketch using the Arduino environment. You could clone the serial part that you have on the Eagle files of the original Arduino to do this.

In summary:

* Programming an empty chip requires a programmer
* Programming a chip that has a booloader requires either a programmer, or a simple serial link.

You may also use another Arduino with the suited sketch as a programmer and use it for programming another empty MCU. There are examples of this on the web.

---
Tags: bootloader
---


title: Setting time frame in Arduino Uno

text:
# Question
Title: Setting time frame in Arduino Uno
I have built the circuit below using mux ICs. In a particular interval the respective selector pins get selected and analog signal from hall sensors are read and give a particular analog value out. There is a total of 30 hall sensors which are represented by `HS0` to `HS31`.

Now I wanted to set time as in the table below. After 8000ms I would like it to reset the time automatically and start reading. **Can someone tell me which timer example would let me achieve this?**

```
TIME IS ms  OUT1    OUT2    OUT3    OUT4
  0-1000    HS0     HS8     HS16    HS24
1000-2000   HS1     HS9     HS17    HS25
2000-3000   HS2     HS10    HS18    HS26
3000-4000   HS3     HS11    HS19    HS27
4000-5000   HS4     HS12    HS20    HS28
5000-6000   HS5     HS13    HS21    HS29
6000-7000   HS6     HS14    HS22    HS30
7000-8000   HS7     HS15    HS23    HS31

```

# Answer
Could you tell us which multiplexer IC you are using? This way, we can help you better. Also, why do you need the 8 second cycle? Does it matter if it's a little shorter or longer? If timing does not have to be very precise it would make things a lot easier.

By the way: you say there are 30 sensors, but your table has 32...

The following pseudocode will not work on your Arduino, but you can use the same structure.

```
int sensorArray[32] // we will store our 32 sensor values here

// these pins control the multiplexer chips
int selectPinZero = 8;
int selectPinOne = 9;
int selectPinTwo = 10;

// these pins will receive the sensor values from the multiplexer chips
int inputPinOne = 0;
int inputPinTwo = 1;
int inputPinThree = 2;
int inputPintFour = 3;

void setup(){
    // make sure the correct pins are inputs and outputs
    pinMode(selectPinZero, OUTPUT);
    pinMode(selectPinOne, OUTPUT);
    pinMode(selectPinTwo, OUTPUT);

    pinMode(inputPinOne, INPUT);
    pinMode(inputPinTwo, INPUT);
    pinMode(inputPinThree, INPUT);
    pinMode(inputPinFour, INPUT);
}

// all done, now keep reading the sensors
void loop(){

    // set selectPins so that each Multiplexer will output its first channel
    digitalWrite(selectPinZero, HIGH); // or low, depending on your Multiplexer IC
    digitalWrite(selectPinOne, HIGH); // or low, depending on your Multiplexer IC
    digitalWrite(selectPinTwo, HIGH); // or low, depending on your Multiplexer IC

    // start reading sensors

    int i = 0;
    while(i<32){
        sensorArray[i] = analogRead(inputPinOne);
        i++; // variable i was 0, now 1

        sensorArray[i] = analogRead(inputPinTwo);
        i++; // variable i was 1, now 2

        sensorArray[i] = analogRead(inputPinThree);
        i++; // variable i was 2, now 3

        sensorArray[i] = analogRead(inputPinFour);
        i++; // variable i was 3, now 4

        /*
        use digitalWrite() on all the selectPins to make the Multiplexer IC output the next channel
        */

        delay(1000); // wait 1000 milliseconds
    }

    /*
    this will repeat until all 32 sensors are read and stored in the array
    */

}

```

This code is by no means optimized, but written to make it easy for you to understand. Good luck!
> 2 votes

---
Tags: arduino-uno, arduino-mega, time, analogread
---


# Question
Title: How to program a CAN-BUS Arduino shield to control car windows?
My project is to control car windows using voice recognition. I have successfully controlled some LEDs using the EasyVR Arduino shield using and Arduino MEGA. Now I want to take control of the windows using the CAN-BUS arduino shield.

Because the car that I own doesn't have an OBD-II connector, I am using two Arduinos with two CAN-BUS Arduino shields making one a sender and the other a receiver. How can I program the CAN-BUS Arduino shield to make a simulation of the car's windows?

CAN-BUS shield that I am using: https://www.sparkfun.com/products/10039

Arduino Mega: https://www.sparkfun.com/products/11061

# Answer
What model car do you have? Most cars do not have the ability to control power windows from the car computer. Late model cars will have the ability to control the window motors using bidirectional functions on a scan tool. On any car, the window motors have two wires, if one wire is given power and one ground it will spin if you switch the wire that gets power with the wire that gets ground it spin in the opposite direction. In my experience the way power windows work are both wires are ground while the switch is in the neutral position and by flipping the switch the switch will disconnect one of the grounds and replace it with a power. Find a wiring diagram for your car, and look at how the windows are controlled.

Get a 2 relay breakout board such as this one (make sure you check the current ratings): http://www.amazon.com/SainSmart-2-CH-2-Channel-Relay-Module/dp/B0057OC6D8/ref=sr\_1\_1?ie=UTF8&qid=1400730995&sr=8-1&keywords=arduino+relay+12v

Connect the ground wire to the normally closed (when no power is applied to the relay this is connected to the output wire) side of both relays and the 12v power to the normally open (when power is applied to the relay this is connected to the output wire)side of both relays.

In order to control the relay breakout board you choose one io pin per relay and set it as an output, then connect those pins to the corresponding pin on the breakout board. Set one of the pins to high (you apply power to one relay) the motor now has a power and a ground connection, set the opposite pin high to spin the other way.

I would place this in the driver side door underneath the window master switches because you can have access to every windows wires as they come out of the master switch.

Some late model cars will have a different set up than the one described, but the window motor will only have two wires (it is just a brushed DC motor) just find the window motor and hookup there.

I hope this helps.
> 2 votes

# Answer
the central lock system will close the car doors and close the windows, i think you should build your system with the same idea, dealing with windows motors as normal motor without special commands for the window
> -1 votes

---
Tags: programming, arduino-mega, can-bus
---


# Question
Title: Arduino reading serial data non-blocking
I have an Arduino reading serial data and responding to other inputs as well, I'm trying to read incoming serial data without using the while, if at all possible. the incoming serial data will be formatted in a specific manner each time and will be CSV; It will look like such:

```
19,1400700083, 1-0,1-10,and other values delimited with a new line character "/n".

```

The first value will tell how many bytes are coming in so the serial receive function wont parse data until it gets all the bytes,second value is a Unix time-stamp, the third value (1-0) is the "get" or set" value; which will tell the Arduino to return a value or to set a value. The fourth (1-10) value will correspond to what variable to get or set. and the other values will be integers as well but are dependent on the other values.

My code is as follows:

```
void CheckSerialData() { // begin function

  if(Serial.available() >= 2) { // begin one, first line will be how many bytes incoming.
  int NumberOfIncomingBytes = Serial.parseInt();
    if(Serial.available() >= NumberOfIncomingBytes) { //begin two
    int IncomingTime = Serial.parseInt();
    setTime(IncomingTime); //time is always incoming with serial values
    int GetOrSetValue = Serial.parseInt(); //this value should be 1 or 0 for "getting values(1)" or "setting values(0)"
      if(GetOrSetValue == 1) { //BEGIN THREE
        int ValueToGet = Serial.parseInt();
          switch(ValueToGet) {// BEGIN SWITCH
            case 0:
              Serial.print(GetTemp());
              Serial.print("/n");
              break;
            case 1:
              //serialwrite yaw pitch roll
              break;
            case 2:
              Serial.print(GetVoltage());
              Serial.print("/n");
              break;
            case 3:
              //append all RGB final values together and serial print it
              break;
            case 4:
              //print out accel values
              break;
            case 5:
              //print alarm alarmed status
              break;
            case 6:
              //print out last time alarm set off
              break;
            case 7:
              //print out time allowed lights to turn on
              break;
            case 8:
              //print out arduino time
              break;
            case 9:
              //print out system summary, (time,voltage,temp,yaw,pitch,roll,accel
              break;

          }//END SWITCH
         }//END THREE
      else { //BEGIN TWO B //SET VALUES
      int ValueToGet = Serial.parseInt();
          switch(ValueToGet) {// BEGIN SWITCH
            case 0:
              //set global rgb value set LEFT
              break;
            case 1:
              //set global rgb value set RIGHT
              break;
            case 2:
              //set global alarm value
              break;
            case 3:
              //set global angle to start flashing emergency led's
              break;
            case 4:
              //set turn signal RGB value
              break;
            case 5:
              //set time that lights are ok to turn on
              break;
            case 6:
              //set light override value
              break;
            case 7:
              //set pattern enable
              break;

          } //END SWITCH

      }//END TWO B

          }
        }//end two
      }//end one
    }//end function
    //**********************END SERIAL FUNCTION**************************

```

I would like to know if this looks like it can work, or am I going about this all wrong?

(I don't have access to my Arduino currently to test the code)

# Answer
Unfortunately your code could end up dropping data quite easily, or parsing it incorrectly.

Let's say your code has successfully read the first couple of bytes into `NumberOfIncomingBytes`. However, when it reaches `begin two`, let's imagine the sender hasn't finished sending all the data yet.

Your code will drop through to `end two`, discarding the `NumberOfIncomingBytes` value it just read. Next time round, it will start all over again from scratch, and attempt to read `NumberOfIncomingBytes` again. However, that data isn't there anymore. The next data waiting on serial will actually be the timestamp from the previous message.

From there, it could end up parsing arbitrary data with unpredictable results, getting completely out-of-sync with the sender.

A way to fix it would be to store the `NumberOfIncomingBytes` value outside the function (e.g. as a global variable), along with a flag indicating if you're still waiting for the rest of the data to arrive. At the start of `CheckSerialData()`, the code should check that flag. If it's true, then it should skip trying to read `NumberOfIncomingBytes`. Instead, go straight on to `begin two`.

An alternative approach would be to avoid using `NumberOfIncomingBytes` at all. Each call to `CheckSerialData()` would read whatever serial data is available, and accumulate it in a buffer. As soon as it hits a newline character, it will stop reading, and parse the data it's accumulated. If it runs out of serial data before it hits a newline, it should stop and carry on from there next time it's called.
> 2 votes

---
Tags: serial
---


# Question
Title: What is the smallest microcontroller capable of running Arduino?
I'd like to know which is the most powerful, lightest, and perhaps least expensive micro controller capable of running Arduino.

# Answer
Well, your questions is quite vague and perhaps overly broad. I'll answer your main question "what is the smallest," assuming you meant dimensionally, while keeping in mind that you also want the most powerful one in that size. The pricing of different chips like this will be fairly similar so I'll ignore that.

Next, I'm not sure what you meant by saying "capable of running Arduino" which may mean capable of having the Arduino bootloader installed or could mean being capable of running code written with Arduino libraries. I'll assume the latter since it's the most practical requirement. I'll also assume you want an Atmel chip since it will be the most directly compatible with the Arduino libraries.

So what is the most powerful of the smallest Atmel microcontrollers capable of running Arduino code?

The answer is probably the Attiny 10 which comes in a 2 x 2mm 8-UFDFN Exposed Pad package, or a 2.9 x 1.6mm SOT-23-6 package for about one dollar in small quantities.

Also see this Hackaday article on how to use the Attiny10 with Arduino.

Edit: After more research, I was unable to find an Arduino core for the Tiny10. So while you can program it with an Arduino using assembly or something, writing Arduino code for it won't work. The smallest Attiny with an Arduino core I could easily find is the Attiny13 in a 3 x 3mm 10-VFDFN package. The upside is that while not being that much bigger or more expensive, it's a way more capable chip for your project.
> 6 votes

---
Tags: power, motor, wifi
---


title: Stacking shields without headers

text:
# Question
Title: Stacking shields without headers
In the project I am working on, I have a limited space with which I can work. I am using an Arduino Uno with 2 Adafruit motor shields, and when I stack them using normal, female stacking headers it is too tall to fit. I thought that one way to solve this would be to lay them out side to side rather than one on top of the other. So, instead of this

```
+--------Motor shield 2 ----------+
|||||||||||||||||||||||||||||||||||
+--------Motor shield 1 ----------+
|||||||||||||||||||||||||||||||||||
+---------Arduino Uno ------------+

```

it would look like this

```
               -----------------------------------------Wires -------------------------------
+---------Arduino Uno ------------+    +--------Motor shield 1 ----------+    +--------Motor shield 2 ----------+

```

Would this be possible if I were to connect all of the pins with wires, and has anyone successfully done this before?

# Answer
It is possible to have some success with this, but keep in mind that the longer the wire, the higher the inductance and voltage drop across the wire. Prefer to use a star topology rather than a chain topology, with the Arduino in the middle of all the shields in use.
> 1 votes

# Answer
Yes, no problem running individual wires, and also like Craig says, only run the wires you need. For some inspiration, here's a project I did with a bit of hand wiring. And then there's this project with kinda epic wiring.
> 0 votes

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


title: Arduino Master-Slave Pins

text:
# Question
Title: Arduino Master-Slave Pins
Can I change the pins on the communication for a Master-Slave arduino Wire transmission? I want to communicate between 2 arduinos, but on one of them A4&A5 are taken

# Answer
> 4 votes
You cannot. Wire uses hardware I2C, and on the Uno only A4 and A5 are connected to the TWI peripheral on the MCU. You will need to either switch to a bit-bang I2C implementation or change the protocol you're using.

# Answer
> 1 votes
To complete Ignacio's answer, there's indeed no other hardware I2C on AVR Arduinos.

The only options you have to use other pins is:

* to use bitbang i2c, which is way slower ;
* or you can switch to the Arduino Due which features two TWI ports ;
* or you can use an SPI to I2C serial bridge such has that one.

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


# Question
Title: Sending data from a GUI to an Arduino nano via USB
Can somebody point me in the right direction for information on sending data to an Arduino nano?

My project is to send data that is updated from a GUI (presently written in Python) to an Arduino nano that then makes adjustments to a number of servo motors.

I have the servo code working but am presently using potentiometers to control the servo positions & would like the control done via a GUI.

What libraries would I need to be looking at. Have any of you done anything similar.

Thanks

Nic

# Answer
> 1 votes
Arduino Nano supports FTDI i.e. Virtual Serial Port. So all you have to do is initialize the serial communication using pySerial.

When the data is entered into the GUI, store it in some variables. Send the data in variables to Arduino using Serial Communication. You might have design your own communication protocol on top of Virtual Serial Port in order to identify the data.

You can also use the same library to send the acknowledgement or some data from Arduino to PC, if you want.

Hope this helps you.

---
Tags: arduino-nano
---


title: Timestamp in Arduino

text:
# Question
Title: Timestamp in Arduino
```
int sensorArray[32] ;
int selectPinZero = 8;
int selectPinOne = 9;
int selectPinTwo = 10;
int selectpinthree=11;
int Enablepin=7;

int inputPinOne = 0;
int inputPinTwo = 1;

int sensor1;
int sensor2;
int voltage1;
int voltage2;
int Current_Sensor1[16];
int Current_Sensor2[16];
int row;
int column;

int array[17][5]={
                    {0,0,0,0,0},
                    {0,0,0,0,1},
                    {0,0,0,1,0},
                    {0,0,0,1,1},
                    {0,0,1,0,0},
                    {0,0,1,0,1},
                    {0,0,1,1,0},
                    {0,0,1,1,1},
                    {0,1,0,0,0},
                    {0,1,0,0,1 },
                    {0,1,0,1,0},
                    {0,1,0,1,1},
                    {0,1,1,0,0 },
                    {0,1,1,0,1},
                    {0,1,1,1,0 },
                    {0,1,1,1,1},
                    {1,0,0,0,0}
                 };

unsigned long StopTime=0;
int Counter=0;

void setup(){

  Serial.begin(9600);
  pinMode(selectPinZero, OUTPUT);
  pinMode(selectPinOne, OUTPUT);
  pinMode(selectPinTwo, OUTPUT);
  pinMode(selectpinthree,OUTPUT);

  pinMode(inputPinOne, INPUT);
  pinMode(inputPinTwo, INPUT);
}

void loop()
{

  for(row=0;row<17;row++)
  {

    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(selectPinZero,array[row][1]);
    digitalWrite(selectPinOne,array[row][2]);
    digitalWrite(selectPinTwo,array[row][3]);
    digitalWrite(selectpinthree,array[row][4]);
    sensor1=analogRead(inputPinOne);
    sensor2=analogRead(inputPinTwo);
    voltage1=sensor1 * ARDUINO_ANALOG_SCALING;
    voltage2=sensor2* ARDUINO_ANALOG_SCALING;
    Current_Sensor1[row]=(10*voltage1)-25;
    Current_Sensor2[row]=(10*voltage2)-25;
    Serial.print("Currentsensor1:");
    Serial.println( Current_Sensor1[row]);
    Serial.print("Currentsensor2:");
    Serial.println( Current_Sensor2[row]);
     Counter=Counter+1;
    Serial.print("Counter:");
    Serial.println(Counter);
    Serial.println(".......................");
        delay(1000);

     }
}

```

Here is my Arduino code. I wanted to activate Digital pin for every 1000ms delay.

During each delay the analog value should be stored in an array of index.

I don't know how to keep track of analog value read, or from which port I am reading. I could flicker the LED on the hardware side but it doesn't make any sense. Any method you can suggest here?

Application:

I have 32 hall sensors connected via mux circuit. I wanted to know which sensor is reading value. I want any idea to might suggest to me to keep track here.

# Answer
> 1 votes
You should download timer1 library from http://playground.arduino.cc/Code/Timer1

Init timer1 with a value of 1000000 and it will perform an overflow every second. On every overflow it will perform an action, put your code to activate a pin there. And do the serial readings in your loop.

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


title: bootloader uploading into Atmega328

text:
# Question
Title: bootloader uploading into Atmega328
Here is mine circuit. Intially i used arduino UNO directly for programming. Now i am Using atmega 328 IC for programming. I am trying to connect 32 hall sensor via Mux circut. I wanted to How to upload boot loader or HExfile Here. Will avr pocket programmer satisfy above circuit or i need to add addtional circuit here AVr pocket programmer

# Answer
> 4 votes
The AVR pocket programmer should work fine. Sparkfun has a good guide for doing this.

Here's the pinout of the Atmega328:

You'll want to connect your programmer as follows (note, these are the pins for the bare Atmega328 chip *only*. The pin numbers on an Arduino board are different.):

```
Programmer Pin		Atmega328 Pin
5V			Vcc (7)
GND			GND (8)
MOSI			Digital 11 / Physical 17
MISO			Digital 12 / Physical 18
SCK			Digital 13 / Physical 19
Reset			Reset (1)

```

Note that the physical pins on the chip are numbered differently than the logical pins. In the table above the "Digital" pin numbers are those colored yellow in the figure, while the "Physical" pins correspond to the black-on-white numbers around the edge.

If you already have the ICSP header connected to those pins (it's not completely clear in the schematic if that is the case), you can connect the programmer to those pins instead. This can be easy if you have a 6-pin ICSP cable with your programmer.

Also, if you are already powering your Atmega328 from some other 5V power supply you can omit the `5V-Vcc` pin. However, the programmer and the Atmega328 *must* share a common ground, so be sure the GND pins are connected.

Connect your programmer to the computer using USB, open the Arduino IDE, select the correct serial port of the programmer, and pick "Arduino Uno" in the "Board" menu. You can program the bootloader by selecting "Burn bootloader" in the Tools menu, or you can simply write your program by selecting "Uploading using programmer" in the File menu.

# Answer
> 0 votes
Uploading Hexfile to your arduino can be done using this application:

http://kmtronic.com/upload-hex-files-to-arduino.html

---

This is how you upload an Arduino Bootloader on an empty ATmega328 / ATmega328P-PU. Using an Arduino. (No need for a separate ISP Programmer).

From Arduino Uno to other Arduino Uno.

1. Open the ArduinoISP firmware (in Examples) to your Arduino board.
2. Select the items in the Tools \> Board and Serial Port \> Arduino Uno.
3. Upload the ArduinoISP sketch.
4. Wire your Arduino board to the target as shown in the diagram below. (Note: you'll need to add a 10 uF capacitor between reset and ground.)
5. Also connect TX from Arduino A to the RX of Arduino B and RX from Arduino A to TX Arduino B.
6. Select Target Board in Tools \> Board \> Arduino Duemilanove w/ ATmega328
7. Select programmer in Tools \> Programmer \> Arduino as ISP
8. Use the Burn Bootloader \> Arduino as ISP command.
9. Go to Tools and Select Burn Bootloader. Done.

To upload on a breadboard without External clock.

1. Download: Breadboard.zip
2. Put boards.txt in your Arduino directory under Hardware \> ATmega328. (For windows usually (C:/Program files/Arduino/Hardware/ATmega/boards.txt))
3. Close Arduino IDE and reopen it.
4. Open the ArduinoISP firmware (in Examples) to your Arduino board.
5. Select the items in the Tools \> Board and Serial Port \> Arduino Uno.
6. Upload the ArduinoISP sketch.
7. Hook pin13 from Arduino to pin19 on Chip
8. Pin12 from Arduino to pin18 on chip
9. Pin11 from Arduino to pin17 on chip
10. Pin10 from Arduino to pin1 on chip
11. pin0 from Arduino to pin3 on chip
12. pin1 from Arduino to pin2 on Chip
13. connect 5V from Arduino to pins 7 and 20 on chip 14, connect GND from Arduino to pins 8 and 22 on chip
14. Select Target Board in Tools \> Board \> ATmega328 on breadboard (8 MHz internal clock)
15. Select programmer in Tools \> Programmer \> Arduino as ISP.
16. Select Tools \> Burn Bootloader. Done.

It's also possible with an Arduino Leonardo but you'll have to change some settings for that.

Note: You will need to put target board to Arduino Duemilanove w/ ATmega328 for programming the new chip (Uploading a code to it) instead of targeting Arduino Uno.

---
Tags: arduino-uno, bootloader
---


# Question
Title: Decimals missing when using radio.write(); with Arduino
I'm adapting a sketch I found to send sensor data over a wifi chip (Nrf2401), and although I get the message through, the value I send contains decimals (e.g. 24.59), but the received message will only be 24.

I'm sure there's something wrong on the transmitter part of the code, but I can't see what.

Here's my code:

```
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>

OneWire oneWire(4);

DallasTemperature sensors(&oneWire);

// ce,csn pins
RF24 radio(8,7);

// init data buffer to hold a sensor type byte and one uint16_t sensor data
unsigned char data[3] = {
  0};
unsigned long count=0;
void setup(void)
{
  sensors.begin();
  Serial.begin(57600);
  Serial.println("**************V1 Send Sensor Data***********");
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.setChannel(0x4c);

  // open pipe for writing
  radio.openWritingPipe(0xF0F0F0F0E1LL);

  radio.enableDynamicPayloads();
  radio.setAutoAck(true);
  radio.powerUp();
  Serial.println("...Sending");
}

void loop(void)
{

  sensors.requestTemperatures();
  float currentTemp;
  currentTemp = sensors.getTempCByIndex(0);

  //assign 'T' to represent a Temperature reading
  data[0] = 'T';

  data[1] = currentTemp;

  count++;

  sprintf(data, "T %5.2f\n", currentTemp);  // build command in data[]
  radio.txMode(strlen(data));               // set # bytes to xmit
  radio.write(data);                        // send bytes

  // print and increment the counter
  Serial.print("Temperature sent:  ");
  Serial.println(currentTemp);
  // pause a second
  delay(500);
}

```

In this example, when I print currentTemp, it will display the decimals, but if I print data\[1\], it won't.

What am I missing?

**EDIT:**

I've modified the code to include the answer from JRobert (updated code above), but it comes back the following error:

```
nrf24SendSensorDataV1_ino.cpp: In function 'void loop()':
nrf24SendSensorDataV1_ino:56: error: invalid conversion from 'unsigned char*' to 'char*'
nrf24SendSensorDataV1_ino:56: error: initializing argument 1 of 'int sprintf(char*, const char*, ...)'
nrf24SendSensorDataV1_ino:57: error: 'class RF24' has no member named 'txMode'
nrf24SendSensorDataV1_ino:57: error: invalid conversion from 'unsigned char*' to 'const char*'
nrf24SendSensorDataV1_ino:57: error: initializing argument 1 of 'size_t strlen(const char*)'
nrf24SendSensorDataV1_ino:58: error: no matching function for call to 'RF24::write(unsigned char [3])'
C:\Users\Zuh\Downloads\arduino-1.0.1\libraries\RF24L01/RF24.h:281: note: candidates are: bool RF24::write(const void*, uint8_t)

```

Any thoughts?

**EDIT 2**

I've made a dirty fix that will solve the issue.

In the transmitter code I've added:

```
uint16_t sensorValue = currentTemp*100;
//do the bit shift to put uint16 into uint8 array
data[1] = sensorValue >> 8;
data[2] = sensorValue;
// print and increment the counter
radio.write(data, sizeof(uint16_t)+1);

```

This will send the (temperature value)\*100

On the receiver end, I just convert the uint16\_t to a float element and divide it by 100.

```
uint16_t sensorValue = data[2] | data[1] << 8;
float temp = (float) sensorValue/100;
Serial.print("T: ");
Serial.println(temp);

```

Dirty, but effective!

Many thanks guys for the help, it really pointed me and my lousy programming skills to the right direction.

# Answer
> 0 votes
From the Arduino playground documentation for the Nrf2401 library, the .write method accepts either: a byte to transmit, a pointer to your `unsigned char` buffer; or a void argument meaning use the library's internal buffer. You must have called the .txmode() method first.

Since you're trying to use your own buffer, you'll need to make it long enough to contain the message you want to transmit (plus one byte for the terminating NUL). You'll need a character representation of the value you want to send, not the binary number itself. At a quick read of the library doc I didn't see the message format the library wants, but assuming it's something like: `T<space>12.34<newline>`, you'll need something like this (untested, it may need tweaking)

```
sprintf(data, "T %5.2f\n", currentTemp);  // build command in data[]
radio.txMode(strlen(data));               // set # bytes to xmit
radio.write(data);                        // send bytes

```

# Answer
> 0 votes
Since I can't comment yet I will place this as answer.

But have you tried to use `radio.print(data[1], DEC);` ?

DEC stands for Decimal for if you want to force something to print it in Decimals. When you want something to be printed in Hexadecimals you can use HEX for example. Hope this will help you.

# Answer
> 0 votes
data\[\] is an array of three chars. You assign the letter "T" to data\[0\] (the first char of the array), then data\[1\] = currentTemp attempts to assign a float to the second char in the data array - floats won't fit in chars.

---
Tags: wifi
---


title: Reset fuses on atmega328p using Arduino

text:
# Question
Title: Reset fuses on atmega328p using Arduino
I bought a few atmega328p chips but unfortunately they came with the Arduino bootloader and they are set to use the external clock. I want to reset their fuses using avrdude so I can use the internal 8mhz clock but it's not working. How can I (if even possible) reset their fuses using the Arduino? I have no other programmer and here are the arguments I use for avrdude as well as the response:

```
avrdude -C .\avrdude.conf -p m328p -c arduino -P \\.\COM12 -b 115200 -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

```

Response:

```
avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude.exe: Device signature = 0x1e950f
avrdude.exe: reading input file "0x62"
avrdude.exe: writing lfuse (1 bytes):

Writing |  ***failed;
################################################## | 100% 0.06s

avrdude.exe: 1 bytes of lfuse written
avrdude.exe: verifying lfuse memory against 0x62:
avrdude.exe: load data lfuse data from input file 0x62:
avrdude.exe: input file 0x62 contains 1 bytes
avrdude.exe: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.00s

avrdude.exe: verifying ...
avrdude.exe: verification error, first mismatch at byte 0x0000
             0x62 != 0x00
avrdude.exe: verification error; content mismatch

avrdude.exe: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n]

```

# Answer
You cannot set the fuses using the Arduino bootloader, since they cannot be self-programmed. You must use either serial or parallel programming via ArduinoISP or an external programmer to set them. Since the chip is configured to use an external crystal you must either connect a crystal up to the chip appropriately (see sections 9.3 or 9.4 of the datasheet) or use parallel programming. You will then be able to use the `lfuse`, `hfuse`, and `efuse` memory types to read and write the fuse bytes.
> 3 votes

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


# Question
Title: util/delay.h from arduino _delay_ms not delaying in accurate time with my hardware configuration
I have configured my arduino as a flash programmer and i'm sending data to an atmega328P. It is actually working and the data is send to my atmega328. But what is strange that the \_delay\_ms from from the Arduino library is not delaying in accurate seconds.

\_delay\_ms(1000) who should wait from 1s, is actually more 8 seconds from my atmega328P hardware point of view.

My question is what could possibly turn the program wrong. I'm strongly assuming that this a misconfigured clock cycle from my Atmega, but this is my newbie guess, it can be something else, that's why I'm posting my question here. Can someone can hint me what's wrong with my configuration?

Here's the sample code, a dumb toggle pin on / off:

```
#include <util/delay.h> // from arduino library

/*
*/

 DDRB |= 0b0000001;

  while (1) {
    PORTB = 0b00000001;
    _delay_ms(1000); // it should be 1 second, but on my hardware it is more ~8 seconds

    PORTB = 0b00000000;
    _delay_ms(1000);
  }

```

And my configuration is (from arduino IDE)

*Arduino Pro / pro Mini (3,3v 8 Mhz) / Atmega 328*

I have tried with

*Arduino Pro / pro Mini (5v 16 Mhz) / Atmega 328*

expecting that more power will affect speed, but the result is actually the same.

# Answer
> 5 votes
At a 30000 ft. level, it's because the defined `F_CPU` value doesn't match your hardware. This can happen because the incorrect device is chosen in the IDE or because the device is misconfigured in boards.txt, or because the hardware is somehow different from what is expected.

Given that you are using a bare ATmega328P, assuming that you've selected the correct crystal, and that the apparent time scale is 8x, it is likely that the CKDIV8 fuse is set. This means that the chip is running at 1/8 the crystal speed. You will need to unprogram (set to 1) bit 7 of the low fuse byte in order to reset it. Use AVRdude from the command line to read the low fuse byte (`-U lfuse:r:-:h`), set the bit (lfuse | 0x80), and then write it back (`-U lfuse:w:0xnn:m`).

---
Tags: spi
---


# Question
Title: help with input in a Simon arduino uno game
I' making a Simon game with the arduino uno.

I know something is wrong with the inputs but i don't know why or how to fix it.

The problem is the program takes an input and says it is correct no matter what it is or the length

```
#define NOTES

int tones[] = {NOTE_E5, NOTE_E6, NOTE_CS6, NOTE_A6};
String sequence;

void setup() {
    pinMode(13, OUTPUT); //green
    pinMode(12, OUTPUT); //yellow
    pinMode(11, OUTPUT); //blue
    pinMode(10, OUTPUT); //red
    pinMode(7, INPUT); //green
    pinMode(6, INPUT); //yellow
    pinMode(5, INPUT); //blue
    pinMode(4, INPUT); //red
    Serial.begin(9600);
}

void loop() {
    while(true) {
        delay(1000);
        randomSeed(random(random(1000000000)));
        sequence = String(random(4));
        boolean run = true;
        while(run) {
            for(int i = 0; i < sequence.length(); i++) {
                simonOut(sequence.charAt(i) - '0');
                delay(500);
                simonClear();
                delay(100);
            }
            for(int i = 0; i < sequence.length(); i++) {
                int input = simonIn();
                while(input < 0 || input > 3) {
                    delay(50);
                    input = simonIn();
                }
                if(sequence.charAt(i) - '0' == input) {
                    flash(0);
                    run = false;
                    goto reset;
                }
                else if(i = sequence.length() - 1)
                    flash(3);
            }
            sequence += random(4);
        }
        reset:;
    }
}

void boolOut(long pin, boolean val) {
    digitalWrite(pin,val ? HIGH : LOW);
}

void simonOut(long num) {
    boolOut(num + 10, true);
    tone(2, tones[num]);
}

 void flash(int led) {
     delay(300);
     for(int i = 0; i < 5; i++) {
         simonOut(led);
         delay(100);
         simonClear();
         delay(100);
     }
 }

 void simonClear() {
     for(int i = 0; i < 4; i++){
         boolOut(i + 10, false);
     }
     noTone(2);
 }

 int simonIn() {
     int ret = -1;
     for(int i = 0; i < 4; i++) {
         if(simonIn(i)){
             ret = i;
         }
     }
     if(ret != -1) {
         simonOut(ret);
         delay(500);
         simonClear();
         delay(100);
     }
 }

 boolean simonIn(long num) {
     return digitalRead(num + 4) == HIGH;
 }

```

# Answer
The problem in your code is there:

```
int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
}

```

This method never returns any value, so that means the caller will just tke whatever is in the stack at that time:

```
            int input = simonIn();
            while(input < 0 || input > 3) {
                delay(50);
                input = simonIn();
            }

```

`input` could be anything there.

So the fix should be easy:

```
int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
    return ret;
}

```

It's surprising you did not get a **warning from the compiler** on that one, which IDE do you use?

Finally, regarding your code, I would also advise you the following improvements:

* break down the `loop()` code further into functions that do **ONE** thing, e.g. `showSequence(sequence)`, `checkInput(seuquence)`, `readSimonInput()` (this last function would only return a value between 0 and 3 included. That would make your code much clearer.
* use the right types for your variables: I see you abuse usage of `long` where `int` or `byte`, or you mix different types for the same data, thus forcing the compiler to cast data on some function calls.
* avoid hardcoding constants in your code, e.g. you could define the number of buttons, the first pin of buttons, the first pin of LEDs, the various delays.
> 2 votes

# Answer
Is it possible that your problem might be just a typo?

> #define NOTES
>
> int tones\[\] = {NOTE\_E5, NOTE\_E6, NOTE\_CS6, NOTE\_A6};

In your array you talk about NOTE and you defined NOTES (See the S?)
> 1 votes

---
Tags: arduino-uno
---