title: Getting Push Button Logic To Stick?

text:
# Question
Title: Getting Push Button Logic To Stick?
I'm trying to get a sensor to activate if a push button is clicked. And deactivate when a certain condition is met and reactivate when the push button is pressed again.

```
#include <SPI.h> // Included for SFE_LSM9DS0 library
#include <Wire.h>
#include <SFE_LSM9DS0.h>

#define LSM9DS0_XM  0x1D // Would be 0x1E if SDO_XM is LOW
#define LSM9DS0_G   0x6B // Would be 0x6A if SDO_G is LOW
// Create an instance of the LSM9DS0 library called `dof` the
// parameters for this constructor are:
// [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address]
LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM);

const byte INT1XM = 4; // INT1XM tells us when accel data is ready
//const byte INT2XM = 8; // INT2XM tells us when mag data is ready
//const byte DRDYG = 7;  // DRDYG tells us when gyro data is ready
const int buttonPin = 15;     // the number of the pushbutton pin

int buttonState = 0;

double X;
double Y;
double Z;

void setup(){

  pinMode(INT1XM, INPUT);
  pinMode(buttonPin, INPUT);

  Serial.begin(9600);
  Serial1.begin(9600); // Start serial at 115200 bps
  // Use the begin() function to initialize the LSM9DS0 library.
  // You can either call it with no parameters (the easy way):

  uint16_t status = dof.begin();
  // Or call it with declarations for sensor scales and data rates:
  //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS);

  // begin() returns a 16-bit value which includes both the gyro and
  // accelerometers WHO_AM_I response. You can check this to make sure
  // communication was successful.
  // Serial.println(status, HEX);
  setODR();
}

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.

 // Serial.println(buttonState);

  if (buttonState == 1) {   //if push button is pressed

    printAccel(); //print sensor data

  }

}

void printAccel()
{
  // Only read from the accelerometer if the accel interrupts,
  // which means that new data is ready.
  if (digitalRead(INT1XM))
  {
    // Use the readAccel() function to get new data from the accel.
    // After calling this function, new values will be stored in
    // the ax, ay, and az variables.
    dof.readAccel();

    //Serial.print("A: ");

    // Using the calcAccel helper function, we can get the
    // accelerometer readings in g's.
    X=dof.calcAccel(dof.ax);
    Y=dof.calcAccel(dof.ay);
    Z=dof.calcAccel(dof.az);

    Serial.print(X);
    Serial.print(", ");
    Serial.print(Y);
    Serial.print(", ");
    Serial.println(Z);

    // Serial1.println(Z);

    fall(); //jump to check condition

  }
}

void setODR(){

  dof.setAccelODR(dof.A_ODR_25);
  dof.setAccelScale(dof.A_SCALE_16G);
}

void fall(){

  if(-0.08<X && X<0.08){
    if(-0.08<Y && Y<0.08){
      if(-0.08<Z && Z<0.08){

        Serial1.println("N");
        Serial.println("Fallen!");

        loop(); //if condition is met, jump to loop to wait for push button to be pressed again.

        }
      }
    }
  //else{

    printAccel(); //else continue printing sensor data

  //}
}

```

However I am having some trouble getting it to work, above is what I have worked out thus far.

# Answer
You'll need to store whether the button has been pressed.

```
bool buttonActivated = false;

...

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.
  if (buttonState == 1 ) {
    buttonActivated = true;
  }

  if( buttonActivated ) {
    printAccel(); //print sensor data
  }

}

```

to deactivate, use:

```
buttonActivated = false;

```
> 3 votes

---
Tags: programming, button
---


title: Arduino if else code

text:
# Question
Title: Arduino if else code
I have made this If-Then-Else code, but it doesn't work.

First I tough only the analog code is wrong, but if I take a digital port, the code doesn't work either.

What did I do wrong?

```
int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0.00001;  // variable to

void setup() {
  pinMode(13, OUTPUT);  //LED BORD UIT
  pinMode(12, OUTPUT);  //LED4
  pinMode(11, OUTPUT);  //LED3
  pinMode(10, OUTPUT);  //LED2
  pinMode(9, OUTPUT);   //LED1
  pinMode(8, OUTPUT);   //Elektro Magneet
  pinMode(A0, INPUT);
}

void loop() {
  if (A0 == HIGH) {
     digitalWrite(13, LOW);
     digitalWrite(12, HIGH);   //LED on, magnet off
     digitalWrite(11, HIGH);
     digitalWrite(10, HIGH);
     digitalWrite(9, HIGH);
     digitalWrite(8, LOW);

  } else {
     digitalWrite(13, LOW);
     digitalWrite(12, LOW);   // LED Off, magnet on
     digitalWrite(11, LOW);
     digitalWrite(10, LOW);
     digitalWrite(9, LOW);
     digitalWrite(8, HIGH);
  }
}

```

# Answer
Replace the line:

```
  if (A0 == HIGH) {

```

by this one:

```
  if (digitalRead(A0) == HIGH) {

```

If you plan on using the pin back as an analog input, use something like this:

```
  if (analogRead(A0) > 512) {

```

The explanation is what Ignacio said: you were comparing the pin "name" `A0` directly to `HIGH` instead of reading from the input named `A0`. To make it clearer, the two lines are equivalent:

```
if (A0 == HIGH)
if (0 == HIGH)

```

Get it?

There's more about what pin names to use with digitalRead() and analogRead() here:
> 9 votes

# Answer
You're comparing the pin variable value with `HIGH`. If you want to get the value *at a digital input* then you need to use `digitalRead()`.
> 2 votes

# Answer
You have defined your pin as

```
int sensorPin = A0;

```

Which should be replaced with

```
#define sensorPin = A0

```

And then in your code, you need to read the value from the pin in your `if` statement:

```
 if (digitalRead(sensorPin) == HIGH) {

```
> 2 votes

---
Tags: c
---


# Question
Title: Explanation please, of hardware and software serial links
I am starting to use a Seeeduino GPRS shield (please see note), which is essentially an Arduino Leonardo that, among other things, can be used as a mobile 'phone for sending and receiving texts. I have successfully tried the "blink an led" and "fade an led" sketches, so the compiling and uploading are ok

I am using a desktop computer with Linux Fedora 20.

Now I want to go on to use the cell phone network to communicate with my mobile 'phone. However I am puzzled by something I assume everybody else understands already, and that is the references to "select either software serial port or hardware serial port to be connected to GPRS Shield". Please could someone explain what "software or hardware serial port" is, in simple terms, or point me to a web site that does so? Do I need any wired connection with my PC other than the USB link I use for uploading sketches?

Note: I bought a discounted GPRS shield labelled version 1.0a2. All the information on the 'net is of version 1.0 or 2.0 (with no "a2") and photos and diagrams do not correspond with what I have. I am awaiting official documentation, but meanwhile treating it as an Arduino Leonardo seems to be working.

# Answer
Most small micro controllers, AVR's included, have dedicated hardware for communicating with different serial devices. In arduino these are referenced with "Serial", "Serial1", "Serial2" and so on, depending on how many hardware serial ports your particular arduino has.

Leonardo's are an exception, the first hardware port is "Serial1" and "Serial" refers to the PC's usb connection. On the other arduinos that I know of "Serial" is hardware serial used for PC comms, so using it for other hardware requires sacraficing your PC link.

Software serial ports use the processors more generic pin-change interrupt system to communicate on any pins that support said interrupts, but they have a higher processing overhead and often cannot support the same high speeds as the hardware serial. There are different libraries for Software Serial that have different approaches giving different advantages and drawbacks.

To use a software Serial port you will need to make one to be used in your code, which will look something like this, depending on the type name the library you include uses:

```
SoftwareSerial softSerial( txPinNumber, rxPinNumber);

```

So in short, your processor has dedicated hardware for communicating over serial that should be used first, but if you need more ports the processor can simulate some extras which is referred to as "Software Serial". The documentation to your GPRS shield implies that either will work just fine. You should look at the arduino documentation for your board to see how many ports you have and which pins can be used for serial.

The documentation does not imply you will need any special link to your computer outside of the USB connection.
> 3 votes

# Answer
The hardware serial port is the serial port which connects to the computer this takes up pins 1 and 2 I believe. You can read about this here http://arduino.cc/en/reference/serial.

Software serial ports are only on digital IO pins. You can read more about this here http://arduino.cc/en/Reference/softwareSerial

You should not need anything other the USB connection port.
> 1 votes

# Answer
A `SoftwareSerial` connection is created using the `UART` pins 7 and 8.

Having the device in `HardwareSerial` mode allows the device to connect to pins 0 and 1, allowing direct control from the serial connection to the computer.

In `SoftwareSerial`, you can communicate with the Arduino Via serial, and the Arduino controls the GPRS shield via uart.
> 1 votes

---
Tags: arduino-leonardo, softwareserial
---


# Question
Title: Sense distance with Bare Conductive's Touch Board
How can I sense distance with Bare Conductive's Touch Board, like they suggest in their product video?

I know how I can set the touch and release thresholds, so my Touch Board is more sensitive and triggers before I touch a sensor. What I want to do is get the information how near I am. Not in centimeters or so, but a simple value telling me when I'm nearer to or farther from the sensor like in the video.

# Answer
As a member of the Bare Conductive team, I can tell you that looking at the grapher will be helpful to you. The grapher is a processing sketch that requires the Touch Board to be running the Datastream code. Datastream will give you the sort of raw electrode data that you're looking for.
> 0 votes

---
Tags: sensors, bare-conductive
---


# Question
Title: Lily Pad mp3, nested loops with timing and play randomly choosen mp3, coding problem
The best way to explain my problem is in form of code...

```
    const int ringerPin = A0;
    const int offhook = A4;
    const int onhook = A5;

    void setup(){
    pinMode(ringerPin, OUTPUT);
    pinMode(offhook, INPUT);
    pinMode(onhook, INPUT);
    randomSeed(analogRead(0));

  }

  int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

//ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
void loop()
{
  if (digitalRead(hookon) == HIGH)

void loop(){
delay(randCall);

      //i dont know how to let this loop below here run for 30 seconds.
 void loop()
    {
      //turn audio off - i dont know how to.
    for(int x = 0; x < 15; x++){
      digitalWrite(ringerPin, HIGH);
      delay(50);
      digitalWrite(ringerPin, LOW);
      delay(80);
    }
    delay(2500);
    }
  else
    //play one randomly choosen audiofile out of 10 - i dont know how to
}
}

```

Maybe you can give me some suggestions to my coding problems.? I wrote them inside the code descriptions.

# Answer
Halo, thank you for ansering anything.. I got the loop loop loop thing now runin..

So its about playing an Audiofile if hookon == LOW ........ check it out :-)

The code now looks like this.

```
const int ringerPin = A0;
const int offhook = A4;
const int onhook = A5;
double beginRing = -40000;

void setup(){
    pinMode(ringerPin, OUTPUT);
    pinMode(offhook, INPUT);
    pinMode(onhook, INPUT);
    randomSeed(analogRead(0)); // this starts Arduino's random number generator
}

int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

//ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
void loop()
{
  if (digitalRead(hookon) == HIGH){
    delay (randCall);
    beginRing = Time.elapsedTime;
    while(Time.elapsedTime - beginRing <= 30000 && digitalRead(hookon) == HIGH){
      //turn any audio off???
      for(int x = 0; x < 15; x++){
        digitalWrite(ringerPin, HIGH);   // turn the solenoid on (HIGH is the voltage level)
        delay(50);                           // wait for 50 msec
        digitalWrite(ringerPin, LOW);    // turn the solenoid off by making the voltage LOW
        delay(80);                          // wait for 50 msec
      }
      delay(2500);
    }
  }
  if(Time.elapsedTime - beginRing <= 30000){
    //play one randomly choosen audiofile out of 10
  }
}

```

So, now its about to stop any sound if the hookon is HIGH and to play the randomly choosen file 1 out of 10 if the hookon is LOW (its in the code as description...there i need the right comands)
> 1 votes

---
Tags: programming, sketch, timing
---


# Question
Title: Can I use this replacement motor without modifying the circuit?
I have a demo that spins a motor, but the leads on my motor broke. I happen to have another motor lying around that I'd like to swap in, but it's of a different type. Here's my circuit:

This is the old (broken) motor: https://www.sparkfun.com/products/11696. It has an operating voltage range of 1.0 to 3.0V DC and a no load speed of 6600±10% RPM (@1.0V DC, 110mA).

The new motor that I'd like to use is part of this kit: https://www.sparkfun.com/products/12866. It's a 6VDC motor with a No Load Speed of 90±10rpm and a No Load Current of 190mA(max.250mA).

I'm running this off a Sparkfun Redboard, which is UNO R3 compatible.

Can I swap in the new motor without any circuit changes? Will I have to add additional power for the new motor? Or should I change the circuit with a larger resistor or something else?

# Answer
Regarding voltage, I think there should be no problem as the datasheet for your replacement motor specifies a "suggested voltage 4.5V DC".

However, be careful that there is another important value in motor datasheets: the **stall current**.

Simply stated, this is the current consumed by the motor when it tries to rotate but is unable to, due to its too low torque in comparison with the effort needed for rotation, e.g. if it tries to rotate the wheel of a robot that is too heavy.

The original motor has a stall current of 0.8A according to its datasheet (you can get it from the link you provided).

Your replacement motor has 1A according to the link you provided.

These 200mA can make a big difference for the transistor used in your circuit, a **P2N2222A**.

Indeed, that transistor is specified to switch a maximum of **600mA** current at the collector.

So in the best case, the motor will run correctly without load, but if you provide some load that makes it stall, then the transistor will raise temperature (you could sense that by approaching your finger) and ultimately would get toasted.

Please also note that some poorly designed motors may consume a current near the stall current, due to internal friction (I have already almost grilled a transistor this way...)

So my answer is:

* you can do it for a simple experiment with no load on the motor
* if you really want to do something with the motor, take another transistor with a higher *Ic* current
> 2 votes

---
Tags: arduino-uno, motor
---


# Question
Title: Have Arduino write data to a MySQL database?
Would it be possible to have an Arduino write directly to a MySQL database?

I'm a web programmer, so I'm familiar with how to get records from a MySQL database. I have MAMP installed on my mac, so I have the ability to build an interface, directly in the web browser, that retrives the records from a MySQL database.

What I'm thinking is to connect the Arduino directly to my computer via USB, and write data from the sensors, or the pins, directly to my MySQL database.

I'm using two phototransistor to record whenever something blocks the light. Each sensor records individually a timestamp for when the blocking occur.

Is that possible?

# Answer
It's possible if you forget about the Arduino directly writing to the database.

Simply put, the Arduino is restricted to a serial connection. To directly communicate with MySQL you would need a network connection, and then implement the MySQL protocol - a huuuge amount of work.

The normal way is to have an adapter program running on the PC which receives data from the Arduino over the serial connection, then performs any insert, select, etc instructions on the MySQL for you.

There is a "MySQL Connector" available\* (https://launchpad.net/mysql-arduino) but of course that requires you to have an active network connection of some form to your Arduino. Remember that the Arduino (certainly the Uno) is very limited on memory and program space, so having the Arduino connect direct, and doing anything else, might be mutually exclusive.

---

\*Nice find, @SomeHardwareGuy...
> 4 votes

# Answer
You can do that using an Arduino Yun: the Yun has a linux cpu paired with the ATMega32U4, so you can delegate things like accessing a mysql database, either local or remote.

Take a look at this instructable.

There are different ways for delegating logging sensors readings to the linux side and have them stored on a mysql: the easiest is to code a short python script and call it from the sketch using Process.
> 3 votes

---
Tags: datalogging
---


# Question
Title: Arduino Uno R3 not working after shorting 5V to GND
While wiring up my new Arduino Uno R3 on a proto-board, I accidentally shorted the 5V pin directly to Ground. The LED's immediately turned off and connection was lost. It was powered by USB connection. After 3-5 seconds I removed the short. The LED's have remained out, and I haven't been able to reestablish connection with my computer since. I've unplugged and re-plugged the USB cable and tried the re-set button plenty of times. This short shouldn't have fried the board... what happened? How can I get my Arduino working again??

# Answer
> 6 votes
Have you tried restarting the computer? The computer will shut down the USB port to protect it from a malfunction like this (over-current).

You can also try the ports on the other side of the computer (or front/back) as they're usually on different controllers.

# Answer
> 0 votes
The genuine Arduino boards feature a digital (temperature based) fuse.

When shorting an Arduino, it will heat up the fuse on the Arduino. When the fuse gets to a certain temperature, it will automatically cut off the power from the USB connection to the Arduino board.

When the fuse cools down, it will conduct again.

The motherboards of most computers these days also work with these digital fuses, so you might have heated up both. It wouldn't hurt to reboot the PC and disconnect the Arduino and give it a minute to cool down.

If it still doesn't work, you might have fried the Arduino or the specific USB port. Try a USB port that is likely not connected to the same USB controller in the PC. Meaning, don't just try the first USB port next to the one you used, but try a USB port on the other side of the PC / laptop, they are likely to be connected to different USB controllers.

---
Tags: arduino-uno
---


title: Can the Arduino use this i2c LCD Panel

text:
# Question
Title: Can the Arduino use this i2c LCD Panel
Can the Arduino Mega2560 use the New Haven NHD-0420D3Z-NSW-BBW-V3 LCD panel by controlling it with the New LiquidCrystal library? What cable will you use to connect the LCD to Arduino, are there screw terminals on the LCD board to secure the connections? It seems like only 4 connections are needed, for `GND`, `VCC`, `SDA`, `SCL`.

# Answer
Unfortunately you cannot control that display using that library; the library expects to be connected to a HD44780-compatible driver but the display uses a fully custom control scheme. You may be able to adapt the library to the scheme, but I have not looked at that specifically.

I2C itself only requires 3 connections: SDA, serial data; SCL serial clock; GND, ground reference. Since the display is not powered separately it also requires power, in this case 5V. Since the display can only communicate at 100kHz you don't need to be *too* terribly concerned about cable quality; Cat3 or even telephone cable is acceptable as long as you don't exceed a few feet in length. Don't forget the external pullup resistors though, on SDA and SCL.
> 3 votes

---
Tags: i2c, lcd
---


# Question
Title: What in the example code is different from my test code? LED matrix lights up differently
I'm trying to get my LED matrix to run Conway's Game of Life. After 4 different pin configurations, I've finally been able to run a separate test code, that lights all the LED's in order, and then turns them off in order (Code Below). I've written the entirety of GoL in C#, but the Arduino language is just different enough to where I can write sort of ok in it, but not enough to understand what's going wrong. I got a Game of Life code from here and it won't even light my LEDs, or when it does, it's incredibly dim, unlike my test code. I'll show my pin layout in the code. I've tried changing the pins in the GoL code, copying the setup from one to the other, and but for the life of me, I can't seem to figure out why one would light up the LED's without a hitch, and the other is struggling. Can anybody see the changes I'd need to make that would make the GoL code at that link, work like this test code?

Here's my Test code that works fine:

```
int speed = 4; //the delay time in milliseconds

int pauseDelay = 1;    //the number of milliseconds to display each scanned line

//Pin Definitions
int rowA[] = {14,15,16,17,2,3,4,5};          //An Array defining which pin each row is attached to
                                     //(rows are common anode (drive HIGH))
int colA[] = {6,7,8,9,10,11,12,13};  //An Array defining which pin each column is attached to
                                     //(columns are common cathode (drive LOW))

//The array used to hold a bitmap of the display
//(if you wish to do something other than scrolling marque change the data in this
//variable then display)
byte data[] = {0,0,0,0,0,0,0,0};

//Setup runs once when power is applied
void setup()
{
  Serial.begin(9600);         //Open the Serial port for debugging
  for(int i = 0; i <8; i++){  //Set the 16 pins used to control the array as OUTPUTs
    pinMode(rowA[i], OUTPUT);
    pinMode(colA[i], OUTPUT);
  }
}

//repeats
void loop()
{
 //Example #1 - test pattern
 //Run a small test program which lights up each light in time
  test();

 //Example #2 - static image
 //Display a defined bitmap
/*
  data[0] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[1] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  data[2] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[3] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  data[4] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[5] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  data[6] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[7] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  showSprite(speed);
*/
 }

//An array to store power values to act as bit masks
const int powers[] = {1,2,4,8,16,32,64,128};

//Runs a pattern where each LED is lit one after another
void test(){
  for(int i = 0; i < 8; i++){
for(int ii = 0; ii< 8; ii++){
data[i] = data[i]+ powers[ii];   //Goes through each row of lights lighting each column one after another
showSprite(speed);
}
  }

  for(int i = 0; i < 8; i++){
   for(int ii = 0; ii< 8; ii++){
data[i] = data[i] - powers[ii];   //Goes through each row of lights turning off each column one after another
   showSprite(speed);
    }
  }
}

void showSprite(int speed2){
 for(int iii = 0; iii < speed2; iii++){                 //show the current frame speed2 times
  for(int column = 0; column < 8; column++){            //iterate through each column
       for(int i = 0; i < 8; i++){
           digitalWrite(rowA[i], LOW);                      //turn off all row pins
   }
   for(int i = 0; i < 8; i++){ //Set only the one pin
     if(i == column){     digitalWrite(colA[i], LOW);}  //turns the current row on
     else{                digitalWrite(colA[i], HIGH); }//turns the rest of the rows off
   }

   for(int row = 0; row < 8; row++){                    //iterate through each pixel in the current column
    int bit = (data[column] >> row) & 1;
    if(bit == 1){
       digitalWrite(rowA[row], HIGH);                   //if the bit in the data array is set turn the LED on
    }

   }
   delay(pauseDelay);                       //leave the column on for pauseDelay microseconds (too high a delay causes flicker)
  }
 }
}

```

# Answer
> 2 votes
I ended up using a different PIN layout, and the GoL code had the pins As anodes where they were Cathodes in the other code. Switched rows pins to Columns pins in the code and Problem solved.

---
Tags: programming, led
---


# Question
Title: Help with a function that accepts different parameter types
I'm trying to create a function that prints out an XML tag with a value. I have the code below, but kind of stuck. I'd like to be able to call the function, and pass a value that could be a float, int, string or char. Appreciate any help.

```
char PingTime[6] = "3ms";
char PingText[60] = "ping reply blah blah";
float humidity = "40.56";
int DigialPin = 0;

PrintXMLTag(cl,"pingtime",PingTime);
PrintXMLTag(cl,"PingText",PingText);
PrintXMLTag(cl,"humidity",humidity);
PrintXMLTag(cl,"DigialPin",DigialPin);

void PrintXMLTag_DEC(EthernetClient cl, const char* tag, NotSure?? val)
{
  char tmp [100];
  StrClear(tmp,100);

  // If val type is float ----------------------
  int d1 = val; // Get the integer part
  float f2 = val - d1; // Get fractional part
  int d2 = trunc(f2 * 10000);// Turn into integer
  sprintf(tmp,"<%s>%d.%02d</%s>\n",tag,d1,d2,tag);
  // end float

  // If val type is string ----------------------

  // If val type is int ----------------------

  // If val type is char ----------------------

  cl.print(tmp);
}

```

---

Update, now converting the type to char before calling the PrintXML function resolves my initial issue. If I use the code below it seems to chew up a lot of memory, is there something obviously wrong? As a workaround I'm just printing the XML tags using cl.print and the memory usage is stable.

```
void PrintXMLTag(EthernetClient cl, char* tag,  char* val)
{
  char tmp [100];
  sprintf(tmp,"<%s>%s</%s>\n",tag,val,tag);
  cl.print(tmp);
  StrClear(tmp,100);
}

```

# Answer
> 0 votes
try using this example instead of iostream you can use iostream.h too..

```
#include <iostream>
using namespace std;

int sum (int a, int b)
{
  return a+b;
}

double sum (double a, double b)
{
  return a+b;
}

int main ()
{
  cout << sum (10,20) << '\n';
  cout << sum (1.0,1.5) << '\n';
  return 0;
}

```

# Answer
> 0 votes
take a look at: http://www.cplusplus.com/doc/tutorial/functions2/

```
template <typename SomeType>
SomeType sum (SomeType a, SomeType b)
{
  return a+b;
}

```

This appears to be what you want.

# Answer
> 0 votes
If your goal is really to print the value from XML, you don't need to worry about types, as long as you believe the XML to be correctly formed. The value in the XML file is already character string just print it. The converting from string to variable (sprintf()) and back to string (Serial.print() or printf()) is unnecessary.

---
Tags: programming, variables
---


title: How to split in string

text:
# Question
Title: How to split in string
I want to split this:

```
char* value = "12;32;blue";
or
string value = "12;32;blue";

```

into this vars:

```
TV = 12;
AR = 32;
LED = "blue";

```

is it possible?

# Answer
> 2 votes
For C-strings (`char*`), your best option (in terms of performance and memory consumption) is to use `strtok`:

```
char* value = "12;32;blue";
char* token = strtok(value, ";");
int TV = atoi(token);
token= strtok(0, ";");
int AR = atoi(token);
token = strtok(0, ";");
char* LED = token;

```

**Note 1**: the code above takes it for granted that `value` is properly formatted, i.e. contains 3 parts split by `;`. If it is not sure, then you should add additional checks on `token` value returned by `strtok`.

**Note 2**: `strtok` is modifiying its `value` argument, so that at the end of the code above, `value` will not be equal to `12;32;blue` any longer.

**Note 3**: `LED` variable above will point directly to the character `b` inside `value`, which means that if `value` is modified afterwards, `LED` might be modified as well.

# Answer
> 3 votes
Scan function should do the job.

```
int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);

```

---
Tags: arduino-mega, string
---


# Question
Title: Make upload stuck on osx 10.10 bare-arduino-project
I followed the instructions in here, including to use arduino IDE v 1.0.5, but when I tried to `make upload` it stuck. I can upload it when using Arduino IDE.

Here is what I got:

```
  mkdir -p /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject
 /Applications/Xcode.app/Contents/Developer/usr/bin/make reset
 /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/Arduino-Makefile/bin/ard-reset-arduino  /dev/cu.usbmodem1421
 /Applications/Xcode.app/Contents/Developer/usr/bin/make do_upload
 /usr/local/bin/avrdude -q -V -D -p atmega328p -c arduino -b 57600 -P /dev/cu.usbmodem1421 \
        -U flash:w:/Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject/mySecondProject.hex:i

```

What did I miss?

I use: Bare-Arduino-Project, OSX 10.10, XCode 6.1, Arduino Uno, my Makefile

# Answer
> 2 votes
I'm the maintainer of the Bare-Arduino-Project, thanks for using it :)

Have you installed `pyserial` and `avrdude`?

To install `avrdude` just run `brew install avrdude` and to install `pyserial`, you need `python installed`, then you can run `pip install pyserial`.

https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial

Hope it helps :)

Next time, feel free to open an issue in the Github repo as it might also help others.

**EDIT:** my bad, I did not read your Makefile carefully!

the problem is with:

```
BOARD_TAG         = mega328
# it should be
BOARD_TAG         = uno

```

---
Tags: arduino-uno, avrdude, osx
---


# Question
Title: Measure Water Flow in literes using Arduino Mega 2560 Board and Water Flow Sensor
I have a water flow sensor with Arduino Megs 2560 board. I am trying to conceptualize the concept to calculate amount of water getting dispensed esp. in 1,2,3,4 and 5 liters quantity.

Water flow sensor specification:

http://www.seeedstudio.com/wiki/images/b/b7/Water\_flow\_sensor\_datasheet.pdf

I would connect the sensor input to any pin from 22-53 pin.

Suppose I connect to ping 23 so in my setup() function I would add:

```
attachInterrupt(23, pulseCounter, FALLING);

```

where pulseCounter is an interrupt function triggered on each signal generated from sensor and increments a variable

```
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

```

Now how do I calculate the flowrate and water dispensed in milliliters using this information? How do I know the freqz of the MCU (which is required as water dispensed per pulse is different for different MCUs)?

# Answer
the pulse rate can be derived without knowledge of the CPU clock speed. To achieve the pulse rate from your sensor input you can do two things:

1. count the pulses **dn** within a certain (i.e. fixed) interval **T** of time) or
2. measure the time **dt** between two pulses.

I'll come back later on this concerning accuracy.

To measure time, you can use the function millis(). This function returns you the milliseconds since bootup as an integer upon calling it. Method 2 is rather simple to implement.

* Setup three global integers *a*, *b* and *c*.
* At the end of setup set *a* to current millis();
* In your ISR set b to current millis();
* Also in ISR: set a=b;
* calculate *c=b-a* (i.e. your **dt**);

c holds your current full wave pulse length in milliseconds, which is updated every pulse. You can derive your flow then from it.

The first method uses a counter as demonstrated in your suggestion. You then need a timer outside your ISR, two variables *d* and *e*. Either you poll millis() in your main "loop()" or you install a timer interrupt, both will work here.

* At the end of setup set *d* to current millis();
* If your predefined time **T** is passed (by comparing *d* with millis(),
* save your counted pulses to *e=pulseCount*
* reset: *pulseCount=0*

*e* holds your pulse count during interval **T**, from which you can derive your pulse rate.

## Accuracy

Method 1's accuracy increases with higher **T** and higher flow speeds. Therefore the update rate of your measurement is low. By changing **T** you can easily increase accuracy on cost of responsiveness. This is perhaps a good idea, if you have pulsating flows in your tubings, or the sensor is a bit rattling.

Method 2's accuracy increases with lower flow speeds. It is best to measure very low flow speeds. Update frequency is minimal (1/**dt**).

Regarding this sensor you should calibrate it yourself. It is a cheap and rugged device (I'm using it, too), but its output depends on several parameters like mounting position, fluid viscosity and so on. Make sure, there are no bubbles, foam or contaminants in your fluid systems as they garble the results effectively.

n.b.: make sure to take care of an overflow of millis().
> 0 votes

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


title: Assuring an unsigned long int?

text:
# Question
Title: Assuring an unsigned long int?
Basic question: How far do I have to go to assure that integer math is done correctly? For example, this is probably overdone:

```
unsigned long burnTime = 0UL;
unsigned long curBurnTime = 0UL;
// Do some stuff that sets the above variables to millis() at various times
// Later on...
unsigned long adjustedBurnTime = (unsigned long) ((burnTime + curBurnTime) / 1000UL);

```

Would the math be done correctly if I went to a more minimal last statement (since all the elements of the equation are unsigned longs)? Like this:

```
unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000UL);

```

Or even:

```
unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000);

```

# Answer
Any good C manual will tell you the result type for each basic math operation on given types. But briefly, the basic math operators return a result as wide as the widest operand, with the narrower operand being widened to match the wider one, if they differ. The same with assignment: assigning a result of a given type to a variable of the same type will not involve any conversion.

tl;dr: No, you're not missing anything. You don't need any casts in your example.

PS: One thing you do need to be aware of is whether any of your intermediate results will overflow the arithmetic type you're using. For example, the final result may be not exceed an unsigned long but the expressions `(burnTime + curBurnTime)` must also not exceed it. This is a greater concern with smaller data-types, of course.

PPS: Good on you for tackling fixed point arithmetic rather than just reaching for the floating-point library!
> 3 votes

---
Tags: variables
---


title: Digital Potentiometer not fading LED

text:
# Question
Title: Digital Potentiometer not fading LED
So I am trying to test what will eventually be a Arduino controlling 3 110V motors that are currently controlled by an analog pot. But more on that later.

I am trying to test out using a digital pot (never have before) and am running into some issues with tutorials I have found online. For now, I want to control a LED with the digital pot (Spec Sheet) so that the LED fades in and fades out in a continuos loop.

Here is the tutorial I followed. It uses a different chip model but it seems from the pot I am using that the pins are the same. (I could be wrong?)

I double and triple checked the wiring and it matches below.

Here is the code I am running (slightly modified from the tutorial, also tried the tutorial code)

```
#include <SPI.h>
byte address = 0x11;
int CS= 10;
int i=0;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotWrite(i);
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotWrite(i);
      delay(10);
    }
}

int digitalPotWrite(int value)
{
  digitalWrite(CS, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

```

As a result of the two above, I have an LED that stays lit (at about 50% it seems) and does not fade in/out at all.

Being relatively new to wiring and EE in general, is there a better way to replicate an analog pot without using a digital pot? Can I just use PWM to control it? Why would the LED be just staying lit?

Thanks!

# Answer
> 1 votes
After studying the datasheet differences between **MCP41100** (digital pot used in the tutorial) and **MCP4131** (the one you get), I found **two major differences** between both:

1. Difference in **resolution**:

* MCP41100 has **257 steps** resolution (8 bits + 1): you can see that at the beginning of its datasheet
    * MCP4131 has only **129 steps** resolution (7 bits + 1): you can get this information on page 2 of its datasheet
2. Difference in **commands formats** sent through SPI; both use one "command byte" followed by a "data byte", but have a diffrent format for their command byte:

* MCP41100 command byte is `X X C1 C0 X X P1 P0` where `X is unused`, `C1 C0` is one of 4 possible commands, only 2 being valid commands actually: `01` (Write data), `10` (Shutdown), finally `P1 P0` should be always `01` for an MCP41100
    * MCP4131 command byte is `AD3 AD2 AD1 AD0 C1 C0 D9 D8`, where `AD3-AD0` is the address of the "register" on which to perfom a command. For the MCP4131, the most important address is `00` which means "volatile wiper 0" (this is what allows you to change the resistance value of the pot), `C1 C0` is one of 4 possible commands (read data, write data, increment, decrement), in your example the command should be `00` (write data); finally `D9 D8` are the high order bits of the value to write to the register, but `D9` is unused and should always be `0`. For 257-steps pots, `D8`is used to have the full resistance scale, otherwise it should be `0`

Now that we know aht your MCP4131 expects as commands passed through SPI, we can take a look at what the tutorial program passes:

```
00010001 value

```

The first byte can be broken down as such:

* `0001` address of the pot **wiper register 1** (**not 0**): this wiper does not exist on MCP4131 hecne writing to it will have no impact...
* 00 command bits meaning "Write to register specified in previous address"
* 01 high order bits (D9-D8) of the value to write to the wiper register.

Although I don't have an MCP4131 at hand, I think you should adapt the program as follows:

```
byte address = 0x00;

```

And that should be fine! Indeed, now your program passes:

```
00000000 value

```

Which means "write `value` (between `0` and `128` which matches exactly the 129 steps resolution) to the wiper register 0 of the port".

Note that the MCP4131 has more features than the MCP41100 in terms of commands, for instance you could use the special commands "increment" and "decrement", with the advantage they need only one byte (the command byte), e.g.

```
void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotIncrement();
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotDecrement();
      delay(10);
    }
}

void digitalPotIncrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x04);
  digitalWrite(CS, HIGH);
}

void digitalPotDecrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x08);
  digitalWrite(CS, HIGH);
}

```

---
Tags: arduino-uno, spi, potentiometer
---


title: Proto Shields wthout breadboard?

text:
# Question
Title: Proto Shields wthout breadboard?
I want to use a proto shield (brand is unimportant) and solder some components to it, to make something more premanent than using a breadboard.

My question is can the components be soldered directly to the middle area where there are a lot of small holes?

I would assume this is possible, but everywhere I look people add mini breadboards to their proto shields.

If it's possible, then I assume components and wires can't just be connected in a row like on a breadboard and would instead need some solder between 2 holes where for example a component and seperate wire are connected?

# Answer
There are many different types of photo-shields, sometimes they have interconnected rows or they just have individual solder holes or even breadboards. What you get all depends on what you are doing. My personal favorite are the interlocked rows so I buy that and use a breadboard while I am developing my project then take off the breadboard and solder everything into place.

Example of non interlocked rows and an My favorite proto-shield, it has a little of both kinds
> 1 votes

---
Tags: prototype
---


title: Car dome light fading with arduino nano

text:
# Question
Title: Car dome light fading with arduino nano
So I'm working on my car and now I've got my sights on the electrical system. I've installed a keyless entry system and a pulse timer for the dome light. Now, I'd like to give the dome light the fade effect all the modern cars have. After looking around, it seems an Arduino would be the most reliable.

I currently own an board similar to the Arduino Nano, specifically the SainSmart Nano. So I've determined that I'd power the board with a constant 12V, use pin 7 as input, and use pin 9 as output.

My code:

```
int domeLightIn = 7;
int domeLightOut = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(domeLightOut, OUTPUT);
  pinMode(domeLightIn, INPUT);
  digitalRead(domeLightIn);

}

void loop() {
  // Case 1: State of Door: Open/Closed
  // Case 2: State of Switch: On/Off
  // Case 3: State of KES: Active/Inactive

  //Case 1: If door is closed and led is off, brightness remains 0;
  //Case 2: If switch is off and led is off, brightness remains 0;
  //Case 3: If KES is inactive and led is off, brightness remains 0;
  if (digitalRead(domeLightIn) == LOW && brightness != 255){
    brightness = 0;
  }

  //Case 1: If door is open and led is off, brightness will fade in;
  //Case 2: If switch is on and led is off, brightness will fade in;
  //Case 3: If KES is active and led is off, brightness will fade in;
  if (digitalRead(domeLightIn) == HIGH && brightness != 255) {
    for (brightness = 0; brightness < 255; brightness = brightness + fadeAmount) {
      analogWrite(domeLightOut, brightness);
      delay(35);
    }
  }

  //Case 1: If door is closed and led is on, brightness will fade out;
  //Case 2: If switch is off and led is on, brightness will fade out;
  //Case 3: If KES is inactive and led is on, brightness will fade out;
  if (digitalRead(domeLightIn) == LOW && brightness == 255) {
    for (brightness = 255; brightness > 0; brightness = brightness - fadeAmount) {
      analogWrite(domeLightOut, brightness);
      delay (35);
    }
  }
}

```

I am unsure whether I am using digitalRead() correctly along with wiring the input. So, am I doing this right? or perhaps there is a better way?

# Answer
> 1 votes
You're not using digitalWrite properly. You should do:

```
if (digitalRead(domeLightIn) == LOW && brightness != 255){

```

Just a sidequestion. What is pin7 connected to? If it's a 12v signal, you'd have to convert it down to 5v somehow.

Also, the 12v in the car can be up-to 14v, and can have some huge spikes. Not sure if the sainsmart's regulator can handle those spikes. It might die prematurely. It's also just wasting 60% (generating heat!), turning 12v to 5v. I would suggest adding one of those cheap car-phone-chargers.

# Answer
> 0 votes
You should consider bringing the voltage down to 5v thats very important, when a car is running as stated above the voltage will increase because the battery is no longer running the electronics, the alternator powers everything and charges the battery.

Instead of trying to control this strait from the Arduino, use a transistor such as the TIP 120 darlington in order to control the existing light or you can put in a new one if you want. This gives you the ability to add more powerful lights or add more lights to the circuit, which the Arduino would not be able to power via pwm.

---
Tags: led, pwm, arduino-nano
---


title: MHz Sampling Rate for Arduino

text:
# Question
Title: MHz Sampling Rate for Arduino
How can we increase the Arduino's ADC sampling rate to 1 MHz while maintaining a 10 bit resolution? Can we change the prescaler to 16 to get 1 MHz ADC clock?

If not, what alternatives are there? Another Atmel chip that works with the Arduino library? Or any external ADC?

# Answer
The problem with driving the ADC faster is that the S+H circuit won't have enough time to reach the final value before the conversion is performed, meaning that precision will be lost.

The best thing to do would be to use an external ADC from e.g. TI or Microchip that has the capabilities you're looking for.
> 3 votes

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


title: Dead reckoning with an accelerometer

text:
# Question
Title: Dead reckoning with an accelerometer
Is it possible to use an Arduino, connected to a 3 axis accelerometer, to estimate a platform's continuous change in position and orientation? I have a small mobile robot, and given an initial position and velocity vector and sequence of acceleration changes, I'd like to calculate the current position and velocity vector.

From this question, it sounds possible, but I can't find any reference to projects or code to accomplish it with an Arduino. I understand the main problem will be the build-up of errors over time, but that's ok, as a rough estimate is acceptable. I'm also using wheel encoders to calculate the same values, and I want to use the accelerometer to account for errors in the encoders, like slippage. e.g. If the encoders say we're accelerating at 1cm/sec but the accelerometer says we're at a constant speed, then I know to ignore the encoders because the wheels are probably slipping.

I understand the math behind this, so the problem is how to write it in C to run on an Arduino. Is anyone aware of existing open source code for something like this? I'd like to avoid reinventing the wheel in-case anyone's implemented a similar system.

# Answer
```
for each accelerometer:
   sample the accelerometer;
   low-pass filter its values (current and recent history) to remove noise;
   multiply by the sample interval to get the velocity increment;
   add the increment to a running sum to get velocity;

   sample the velocity (the running sum you just updated);
   maybe low-pass filter, as above;
   multiply by the sample interval, as above, to get the position increment;
   add the increment to a running sum to get position;
end;

```

Noise, the artifacts created by filtering, and the double summation all work against your accuracy. That said, if your problem is to sense traction or loss of it, how about sensing real velocity more directly such as by dragging an encoded but otherwise free fifth wheel? Or if circumstances allow, optically sense the velocity of the surface underneath you as an optical mouse does?
> 3 votes

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


# Question
Title: Can I use a spare Darlington Pair on my ULN2003A to drive a DC motor?
I'm successfully running a stepper from my Arduino via a ULN2003A and a secondary power supply. It uses the first four of the seven Darlington Pairs on the chip, leaving three spare.

A) Is there any reason I wouldn't be able to use one of the remaining pairs to drive a standard DC hobby motor? (For the sake of helping future visitors .. what about running three motors off the remaining three pairs?)

B) Do I need anything other than to connect the motor to the chip? (The chip's board has LEDs and resistors on each of pins 1 - 4, but I don't believe they're in series and thus my guess is they can be left off.)

C) The DC motor is on a PWM Pin. Is that the correct way to control its speed?

The image attached shows the setup in case I haven't been clear.

*(I could probably just build it and see, but I'm new to Arduino and still scared of the blue smoke if I get something wrong!)*

# Answer
> 4 votes
Should work just fine. But you'd have to connect the motor to the positive rail, and since the ULN2003 can only sink current.

Normally when connecting a motor, you'd add a flyback diode. But the ULN2003 already has those inside the chip.

PWM is the easiest way to (somewhat) control the speed of a DC motor.

---
Tags: motor
---


title: Arduino Serial buffer

text:
# Question
Title: Arduino Serial buffer
I am trying to write one code that takes data from serial ie. `0x4E`, `0x20`, `0x--`, `0x0D`.

`0x--` may be any hex in `--`

The user will input these hex one by one and raspi will take all of them in buffer. Whenever 1st, 2nd and 4th data is matched, the 3rd one will be printed in serial ie.

```
Serial.print(3rd); //Decimal value
else Serial.print() // may be 00

```

I was trying with this code:

```
byte buffer[4];
int cnt = 0;

void setup()
{
 Serial.begin(9600);
 Serial.println("Start");
}

void loop(void)
{

 // read max 12 bytes
 if ((cnt <= 4) && Serial.available()) buffer[cnt++] = Serial.read();

 if (cnt == 4)  // all bytes read...
 {
   // assume the arrays are the same
   boolean same = true;

   // the ans array holds the right answer
   byte ans[]={0x4E,0x20,0x01,0x0D};

   for (int i=0; (i<= 4) && same; i++) same = (buffer[i] == ans[i]);

   if (same)
   {
     Serial.println("Yes");
   } else {
     Serial.println("Enter another number");
   }
   Serial.flush();
   cnt = 0;
 }
  //Serial.print("Done");
 // do something
}

```

But I was not able to do it. Anyone have a suggestion?

**Edit: I have tried this state machine in Arduino :** It accepts those data and according to it, it should bi color LED light. But not working properly. Not lighting up anything

```
//int currState;
//int reChk, data, confirm;
const int pingPin = 13;
int inPin = 12;

void setup()
{
  Serial.begin(9600);
    // initialize digital pin 13 as an output.
  pinMode(32, OUTPUT);
  pinMode(34, OUTPUT);

  digitalWrite(32, LOW);
  digitalWrite(34, LOW);
  //currState = 0;
  //reChk = 0;
  //confirm = -1;

}

void loop() // run over and over
{
  static int currState = 0, reChk = 0, confirm = -1;
  int data;
  if(reChk == 0)
  {
    //ultrasonic();
    if(Serial.available())
    data = Serial.read();
    else
    currState = 5;
  }

  switch(currState)
  {

    case 0:
    reChk = 0;
    if(data == 78)
      currState = 1;
    else
      currState = 0;
    break;

    case 1:
    reChk = 0;
    if(data == 32)
    currState = 2;
    else
    {
      currState = 0;
      reChk = 1;
    }
    break;

    case 2:
    reChk = 0;
    switch(confirm)
    {
      case -1 :
      confirm = data;
      currState = 3;
      break;
      case 0 :
            digitalWrite(32, LOW);
            digitalWrite(34, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      case 1 :
            digitalWrite(34, HIGH);
            digitalWrite(32, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      case 2 :
            digitalWrite(32, HIGH);
            digitalWrite(34, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      default :
      confirm = -1;
      reChk = 1;
      currState = 0;
    }

    case 3:
    reChk = 0;
    if(data == 20)
    {
      reChk = 1;
      currState = 2;
    }
    else
    {
      confirm = -1;
      currState = 0;
    }
    break;

    default:
    reChk = 0;
    currState = 0;
    confirm = -1;
  }
  delay(10);
}

void ultrasonic () //ultrasonic
{
      const int pingPin = 13;
      int inPin = 12;
      //raw duration in milliseconds, cm is the
      //converted amount into a distance
      long duration, cm;

      //initializing the pin states
      pinMode(pingPin, OUTPUT);
      //pinMode(greenLed, OUTPUT);
      //pinMode(redLed, OUTPUT);

      //sending the signal, starting with LOW for a clean signal
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);

      //setting up the input pin, and receiving the duration in
      //microseconds for the sound to bounce off the object infront
      pinMode(inPin, INPUT);
      duration = pulseIn(inPin, HIGH);

      // convert the time into a distance
      cm = microsecondsToCentimeters(duration);

      if(cm > 50)
      {
      //printing the current readings to ther serial display
      Serial.print("5");
      }
      else
      {
      Serial.print("0");
      }
      //Serial.print("cm");
      //Serial.println();

      //checking if anything is within the safezone, if not, keep
      //green LED on if safezone violated, activate red LED instead
      //if (cm > safeZone)
      //{
      //  digitalWrite(greenLed, HIGH);
      //  digitalWrite(redLed, LOW);
      //}
      //else
      //{
      //  digitalWrite(redLed, HIGH);
      //  digitalWrite(greenLed, LOW);
      //}

delay(1000);
}

long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
   return microseconds / 29 / 2;
}

```

# Answer
It's unclear how the users input the hex numbers.

If i assume a simple serially attached terminal the user doesn't enter hex numbers but characters.

As an example when the user types `0`, `x`, `4`, `E` the user has only typed one hex number but already four bytes or characters. Instead the user has to type `N`, , `whatever letter`, `Enter`. (Depending on the OS or terminal you will get "CR", "LF" or "CR+LF" when you press enter)

I'm not familiar with C, but your code seems to have also a coding flaw: The 3rd byte will be checked for equality too. You would need something like:

```
boolean same = true;

if (buffer[0] == ans[0]) { same = false }
if (buffer[1] == ans[1]) { same = false }
if (buffer[3] == ans[3]) { same = false }

```

Only three tests not four.
> 1 votes

---
Tags: serial
---


# Question
Title: How to display tilt sensor data on an LCD?
I'd like for a 16x2 LCD monitor from Sparkfun to display sensor data from a 4-directional tilt sensor from Parallax. The Arduino board is a Duemillanove. The board will run and power both programs and modules, but the serial monitor displaying the tilt sensor data will not relay the info to the LCD display. Any suggestions?

Here are the two pieces of code I am trying to get to work together—they are both from Arduino:

For the tilt:

```
void setup() {
   Serial.begin(9600);
}
void loop() {
   Serial.print("Photo 1: ");
   Serial.print(digitalRead(6), DEC); // Display Out 1 value
   Serial.print("; ");
   Serial.print("Photo 2: ");
   Serial.println(digitalRead(7), DEC); // Display Out 2 value
   delay(250); // Wiat 1/4 second
}

```

For the LCD:

```
#include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)
void setup() {
  mySerial.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}
void loop() {
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write(" "); // clear display
  mySerial.write(" ");
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write("movement recorded");
  while(1); //
  wait forever
}

```

Update:

I'm still tinkering with the suggested program from @Ariser shown below, but keep getting a compile error:

tilt\_lcd\_ase.cpp: In function ‘void loop()’:
tilt\_lcd\_ase.cpp:24:43: error: expected ‘)’ before ‘;’ token
tilt\_lcd\_ase.cpp:25:43: error: expected ‘)’ before ‘;’ token

I've done some research and one person had a similar problem, but it was within #include not void loop. The search continues, but if anyone has a suggestion please chime in. The liquid crystal library is also turning up similar errors but it needs a closer look.

# Answer
The serial monitor cannot relay data from different peripheral unit in an arduino system.

I think you have certain misconception of the hard and software. Your USB connection to the microcontroller on the arduino is just a trunk for a asynchronous serial transmission. In the past this was done via a RS-232 interface.

So, what is it, that you see in your serial monitor? That's just a bunch of characters sent by the microcontroller on your arduino. This data is sent from the microcontroller, because some piece of software fills the fifo of its serial interface. In fact, such commands are executed, when you call the method "Serial.print()". Data gets then sent to your PC, Mac or whatever you are running your IDE on.

Now on the very same microcontroller the software for your tilt sensor is being executed. How could the serial monitor (which resides on your PC) route data from your tilt sensor to your LCD display? I'll tell you: It can't.

(In fact you could write a terminal script on your PC which reads data from serial and writes it back to the same interface, but it may cross your mind, that this might be a very big indirection)

So what do you wanna accomplish? You want to put data read from a device connected to your Arduino to another device connected to your Arduino. So you better tell it the Arduino. The serial monitor will not be involved, hence you won't need any calls of Serial.print() to accomplish that.

To help you with that task, we need to see the code you have written so far.

Ok. first thing you need to know: You can't have two arduino sketches running simultaneously on your arduino. This is, because there is nothing like an operating system on your arduino which might provide a scheduler to run both programs. (If you want, look up scheduler on wiki, as it is very useful to know what you can't have)

So you need two pieces of code to run on the same microcontroller (the big black thing on your arduino) one doing the tilt sensor readings and the other printing data on your display. Hence you have to make one program out of two. To accomplish this, you have two problems to solve.

1. you have to execute both code fragments alterantely, which, because the controller is fast enough, boils down to do both task *nearly* simultaneously
2. you have to bring the data which is acquired by code part 1 from the tilt sensor to code part 2 writing to the display. This is (for people into programming) rather simple as it simply has to be stored in a variable.

I recommend you to look up some programming basics at the arduino home page concerning the "setup" function and the "loop" function. But for now: You can have only one of each running on your arduino. Everything which is inside "setup" is executed only once after powerup. Everything which is inside "loop" is going to be executed over and over again consecutively (if nothing breaks).

Your program might look like this:

```
#include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

char gl_senstr1[15];
char gl_senstr2[15];

void setup() {
  mySerial.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}

void loop() {
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write(" "); // clear display
  mySerial.write(" ");
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write("movement recorded");

```

sprintf(gl\_senstr1, "%d", digitalRead(6);

sprintf(gl\_senstr2, "%d", digitalRead(7);

```
  sprintf(gl_senstr1, "%d", digitalRead(6));
  sprintf(gl_senstr2, "%d", digitalRead(7));

  mySerial.write("sensor1: ");
  mySerial.write(gl_senstr1);
  mySerial.write(" sensor2: ");
  mySerial.write(gl_senstr2);

   delay(250); // Wiat 1/4 second

}

```

I did not test it, because I neither own your display nor that sensor. But you can give it a try. You eventually have to dive into the art of programming if you want to accomlish little more than this. This is where the rubber meets the road.
> 0 votes

# Answer
by the looks of it you need to close the brackets of the *sprintf()* statement shown below if you had copied the code from Ariser:

```
sprintf(gl_senstr1, "%d", digitalRead(6);
sprintf(gl_senstr2, "%d", digitalRead(7);

```

replace it with:

```
sprintf(gl_senstr1, "%d", digitalRead(6));
sprintf(gl_senstr2, "%d", digitalRead(7));

```

That is the error you are seeing because of *sprintf()* not seeing a close to its statement ;)
> 0 votes

---
Tags: lcd, arduino-duemilanove
---


# Question
Title: Arduino hangs after 3-4 minutes on battery power, but not on USB
I have a simple sketch running on a BE Leonardo-compatible board.

It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.

Other than that, the only code is serial I/O for debug purposes. (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)

When the board is powered by USB, everything works.

When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength. (There is nothing connected to pin 13.) Even the reset button doesn't work.

If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.

Can anyone offer a possible explanation for (and solution to) this fault?

# Answer
As somebody else suggested, 9V batteries are pretty weak. They only provide a very small number of mAh (milliamp/hours) before their voltage starts to drop. Once the voltage drops to around 7 volts, the regulator in the Arduino can't keep providing 5 volts, so your Arduino resets.

Wire up 6 AA batteries in series. That will provide a much "stiffer" 9 volt supply (more instantaneous current) plus a lot more mAh of total power. If you REALLY want long life, wire up 6 C or D batteries in series, or an external 9V supply through a "wall wart" power supply.
> 4 votes

---
Tags: arduino-leonardo, debugging
---


# Question
Title: How to ensure electronic components make good connection with breadboard
I just began following the projects in the Arduino Projects Book included in the Arduino Starter Kit.

While using LEDs, as in the first few examples of the book, I am having a difficult time keeping them in contact with the breadboard. I can usually move the LED around until it turns on, but even a push of a button can make it lose contact with the board. I haven't used much more than switches, jumpers, LEDs and resistors, so I don't know if any of the other components behave the same. For the more complex projects, it seems like it would be hard to tell if you have it setup properly if you can't be sure the components are making a connection with the breadboard.

Is there a particular way to get all the components to sit nicely in the breadboard, or to modify them to do so?

# Answer
Sounds like you may not be pushing the leads into the board,I find long nose pliers handy for components with thicker leads.
> 4 votes

---
Tags: arduino-uno
---


title: How do you benchmark an Arduino?

text:
# Question
Title: How do you benchmark an Arduino?
I am trying to run a test of the speed of an Arduino, and how it's affected by different temperatures. Does the following code assess this properly?

```
long num = 0;
long startTime = 0;
long endTime = 0;
int duration = 0;
String buffer;

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

void loop(){
  startTime = millis();
  benchmark();
  endTime = millis();
  duration = endTime - startTime;
  Serial.print(startTime);
  Serial.print(", ");
  Serial.print(endTime);
  Serial.print(", ");
  Serial.println(duration);
}

void benchmark() {
  num = 0;
  for(num = 0; num < 1000000; num++);
}

```

I'm using an Uno, if that matters.

# Answer
No.

That is because millis will be equally affected by any frequency change (due to temperature) as the benchmark code. You would need an external clock source that is precise enough.

Note that temperature doesn't have that big an impact on crystal oscillators. Somewhere around 10ppm between -20 and +20 degrees C. The crystal itself is probably already 50ppm precision to start with (higher precision ones are more expensive).
> 2 votes

# Answer
Quite simply, you cannot measure the stability of a device using routines that themselves depend on the device clock.

To do this properly you need an external measuring device that has a clock source at least 10 times more stable than the Arduino xtal. Most frequency counters would qualify. Just set up a timer to provide a constant output frequency, and attach the counter to the pin.
> 1 votes

# Answer
First of all, compiler will just remove your loop, unless you disable compiler optimization, witch will invalidate your test. Also don't worry about clock drift; as clock also run instruction, a faster clock will also mean a faster instruction cicle, so in the end if you calculate instruction/s the value will be valid.

Also serial communication slowness is not a problem as you calculate the value BEFORE sending anything.

Now, exactly what you want benchmark? In your case, you should put some instruction the for, like a variable++, and then print that sum (if you don't use it, again compiler will optimize all away)

But the you are bancharking for and ++. You may use a NOP() instruction, and then a float, a bitshift, a function call, and so on; you will find very different result, sometimes, sometimes compilator will trick your code.

Then when you'll have banchamark, against what will you compare your result?
> 0 votes

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


title: Shift Register 74HC595 not working

text:
# Question
Title: Shift Register 74HC595 not working
I am trying to learn how to make a shift register work. I have been working off of the Arduino ShiftOut tutorial.

My issue is that the shift register isn't working when the circuit is powered and I am not sure what is wrong. I suspect the issue is with pins 10-13 on the 74HC595?

I have done this with an actual board and the 123d.circuits.io simulator with the same result:

http://123d.circuits.io/circuits/444111-shift-register

The code is very simple and taken from the tutorial:

```
// SH_CP; 11
const int clockPin = 9;
// DS; 15
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 10;

void setup() {
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  Serial.begin(9600);
  Serial.println("reset");
}

void loop() {
  for (int number = 0; number < 256; number++) {
    Serial.println(number);
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, number);
    digitalWrite(latchPin, HIGH);
    delay(500);
  }
}

```

# Answer
> 2 votes
Solution: Remove ground from Q0 as Gerben correctly pointed out in comments.

Also: rotate LEDs 90 degrees so that the anode and cathode are on different rows.

What was tripping me up is in the Arduino tutorial diagram is a little unclear on this (I now understand why their way is correct and my way (in the question) was wrong:

---
Tags: shift-register
---


title: Arduino Wire Types?

text:
# Question
Title: Arduino Wire Types?
I don't know what wires to get for my first Arduino project. I am planning on getting a pre-made light strip that I would control with an Arduino from across my room. Is there any specific type of wire to get? It needs to be about 15 feet. There are so many choices, but I don't know what I need. Does anyone else know?

# Answer
> 4 votes
Choosing wire all depends on what you're going to do with it, and most of the choice is based on how much current it will carry and how durable it needs to be. Generally, you're going to use insulated copper wire - aside from that, your answers are mostly here: https://electronics.stackexchange.com/questions/16948/choosing-the-right-type-of-wire

For experimentation - which you will need to do a lot of before attempting your goal project - you can use the little wires which come in the Arduino starter kit. They are "jumper wires" designed for use on a bread board - they can not carry large amounts of electricity.

This product here: https://www.sparkfun.com/products/8431 \- these have "male" ends designed to be stuck into the holes in the breadboard, and connect to the holes on the headers of the Arduino.

Here's an example of a project laid out on a breadboard:

None of those wires carry a lot of current. If you're hooking up 50 LEDs that might be almost a full 1-AMP of current, so I would use thicker wire. Do yourself a favor and start with a kit like in this video, learn the basics, then attempt a 'real' project. Every Arduino user should be able to do all the experiments in the training book and understand them. You will be lost if you jump in deep right away...

https://www.youtube.com/watch?v=pf4qosqpv3A

---
Tags: arduino-nano, wires
---


# Question
Title: Using external power supply to power leds on multiple pins (A0-A5)
I'm totally new to Arduino, and microcontrollers for that matter, so I'm having a hard time figuring out how to connect LEDs to multiple pins, but using a common external power supply...

I've created a starting light that's connected to pin A0-A4 + A5 (turn all LEDs on). I hooked each LED to its own pin directly (A0-A4) for the countdown part ("5, 4, 3, 2, 1, ..."), and then 5 additional LEDs to pin A5 ("GO!").

For the countdown part, when only one LED is on at a time, there's enough power. But if I were to light them all up at the same time, there won't be. So I figured that I should put a relay into the mix for that part, and have them draw power from an external 12 V power supply.

I did manage to make the relay work in the circuit - switching all LEDs on/off, and getting power from the external power supply, but only through one pin.

I'm not sure how to have the start lights use an external power supply, and at the same time get signals from multiple pins. How do I do that?

I'm sorry if my description is unclear. So please let me know if you need more information.

* The LEDs are 3.4 V 20 mA.
* The power supply I'm planning to use is 12 V.

I'm planning to have this start light - which is built in its own casing - use its own power supply, while the Arduino is running of the power from USB. So all I want to do, is to have the signals sent over to this starting light unit, and not power and ground.

UPDATE:

Here's a quick overview of how I'm testing this whole thing at the moment:

The 5 red countdown LEDs (red) is getting powered by the board itself through the pins, while the 5 "GO!" LEDs (green) are getting powered from a 12 V power supply since they're all are going to be turned on simultaneously.

My question is how I can get both the 5 red LEDs, that uses separate pins, to get powered from the external power supply as well?

Since all the LEDs are built in its own casing, apart from the microcontroller because that also handles other stuff...

Did that make any more sense at all?

# Answer
**Caveat: I too am new to this. The answer below is my understanding and I need an expert to confirm.**

Current in your Arduino:

* A single digital pin on a Uno will provide 40mA -- and could conceivably power two of your LEDs.
* The VCC pin outputs 200mA and could therefore conceivably power ten.

So all you need to do is power your LEDs from your VCC, but use your digital pin as a switch. One idea, which you had, was to use a relay. But a relay is an inductor so don't connect it directly to the Arduino. Make sure it's on a shield. But that shield will essentially do exactly what you need to do, but to drive the relay rather than drive your LEDs: It will use the digital pin to switch the VCC and activate the relay.

Luckily this isn't hard. All you need is the most magical of all components: the transistor. A transistor can be used as a switch to turn on a higher current. In your case, the transistor can switch the VCC connection to the LED array when the digital pin is high.

Here's the circuit I believe you need based on my understanding. Note that the values of the resistors and transistors are just made up. Read the docs above to get the correct values.
> 3 votes

# Answer
I think one of the best way for you would be to use 74HC595 chip. You will learn a lot while developing board with this chip. It is well documented Serial to Parallel Shifting-Out with a 74HC595. Using 3 pins you will be able to turn on & off as many LED's as you wish, use external power supply and so on.

Also there is MAX7219 chip. The MAX7219 and MAX7221 Led drivers. And there are a lot more ways to do this.
> 3 votes

# Answer
If you really want an external power supply, you can use ULN2003 / ULN2803, which are 7/8 darlington 500 mA each transistor
> 1 votes

---
Tags: arduino-uno, led, relay
---


# Question
Title: How to Segment Accelerometer Signal at idle points
I'm using an 3 axis Accelerometer(GY-521) to get the acceleration data and also the gyroscope to get the gyro data. I want to segment the signals at the idle points so that i can get the segmented signal at the idle points.

Is there any algorithm or example code that i could use to segment this kind of signal?

Any help would be appreciated.

Thank You.

# Answer
> 2 votes
There are many algorithms you can use. I would advise you to look carefully at the data and the "idle state" and see what is always different. Try everything you can think of and see what works best, or if one does everything you need just stop there.

It might be that you can just calculate if the accelerometer values go over a certain threshold, but that requires that either the orientation be know or the threshold being over 1g.

You could also calculate the rate at which the accerometer value is changing by subtracting the last value (the derivative if you are up on your calculus) and threshold that value, which might produce better results.

You could also calculate a running average and then compare the current value with that. If the numbers match (or are very close) then you can say the accelerometer has been idle. This has the effect of making a changing threshold relative to the most recent activity tuned by the average's response.

I doubt any of these will be perfect, so you might require the algorithm to say "idle" multiple times in a row before changing state from "active" to "idle", or something to that effect.

---
Tags: arduino-ide, accelerometer, signal-processing
---


title: Infrared interruption counter

text:
# Question
Title: Infrared interruption counter
Is it possible to create a infrared based interruption counter with an Arduino Uno? If yes, then what additional hardware would be necessary?

# Answer
You can use photo any transmissive or reflective photo interrupter (wire or TH) ideally with integrated Schmitt trigger and connect to IRQ driven AVR input to have quick trigger reaction. For production is cheaper photo interrupter with external Schmitt but for prototyping it does not matter. Don't forget serial resistor to limit current.

Search e.g. "photo interrupter Schmitt" at Farnell.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino SoftwareSerial library basic example doesn't work
I come to you again because I have a problem with the Arduino SoftwareSerial library. With a basic example I fail to see results in the serial monitor.

The basic code example:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
void setup() {
  mySerial.begin(4800);
}
void loop() {
    mySerial.println("HELLO");
    delay(100);
}

```

I guess it should show the string "HELLO" on the serial port, but nothing appears. I have found that the baud setting is correct. The hardware is simple. Only an Arduino Uno v3 without any connected component.

# Answer
If your Arduino is connected via the built-in USB port then you need to use the hardware serial port (pins 0 and 1). To do that, call `Serial.begin(..)` and `Serial.println(..)`, instead of `mySerial...`.

`SoftwareSerial` is used when you want to connect via serial on some other pins. It allows your program to emulate serial input/output in software instead of relying on dedicated hardware. In this case, your program is trying to setup software serial on pins 10 and 11. That won't show up on the serial monitor because it's not connected to those pins.
> 1 votes

# Answer
Addition to `Peter R. Blommfield`

What is your problem?

Connect your device, run this sketch and you are good to go :)

```
/* TEST */
#include <SoftwareSerial.h>

/* Connect device Rx - 10, Tx - 11 */
SoftwareSerial mySerial(10, 11);

void setup() {
  Serial.begin(9600);   // This will communicate with PC via USB
  mySerial.begin(4800); // This will communicate with device via 10,11 pins with 4800 baud rate
}
void loop() {
    Serial.println("HELLO");   // Sends string to PC to Serial Monitor
    mySerial.println("HELLO"); // Sends string to device
    delay(100);                // Waits here 100ms and then goes on
}

```
> 1 votes

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


# Question
Title: how to calculate correct resistor value to use with LEDs Potentiometer and other devices?
I have been following http://arduino.cc/en/Tutorial/Fade to fade and LED. But I don't know why they are using a 220 Ohm resistor. According to Ohms law if LED is of 2.2 V and it runs on 0.025Amps and is connected to 5V pin of Arduino then the resistor should be of 120 Ohms but why we are using 120 Ohm resistor ? One more thing. How can I collect value of resistor to be used with different output and input devices ?

Thanks in advance

# Answer
If the LED has a forward voltage of 2.2V and is rated for 25 mA, then you're correct that a 120 Ohm resistor should be OK. It's theoretically calculated as the voltage across the resistor divided by the desired current in the LED. (In practice, it's often more complicated than that, but that's a good starting point.)

It's important to note that not all LEDs are rated the same though. I imagine the 220 Ohm resistor was selected for the tutorial to provide a bit of a safety margin, as that should be OK for most LEDs a hobbyist is likely to use. If you don't have access to the full specifications then it's probably better to under-drive it. The LED might be a little dim, but at least it's unlikely to be destroyed.

Here's a useful online tool for calculating theoretical resistor values for one or more LEDs:

For other devices, the resistor values required can depend on a huge number of factors. The best thing to do is to check the datasheets. For some components (such as ICs), you'll often find an "Applications" section towards the back which shows various ways you might want to connect the item to an external circuit. If things like capacitors and resistors are required, it will often explain how to select the correct ones for a given situation.
> 2 votes

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


# Question
Title: How do I change fuse bits - not communicating?
Currently I'm working on a project using an ATmega 2560 microcontroller card with a 10 MHz crystal. My main goal is to use the Arduino IDE to upload sketches to this chip to run my bread board circuit. In the beginning I had planned to use Atmel Studio to upload Arduino Sketches, but I decided to go with the more direct route. I am using two programmers, the Atmel ICE, and the Atmel AVR ISP MKii.

Anyway, here is my issue. I tried to use the Arduino IDE and the MKii to burn the bootloader to the chip. However, it did not work. It uploaded, but I was at that point no longer able to communicate with the device. When I switched to Atmel Studio, and used the ICE programmer, my chip could not be read and recognized (whereas before it could). I can't even program it. (I had bought two.)

I then figured I would try and read the fuse bits on the other programmer and burn the bootloader using Atmel Studio (since the Arduino IDE has no information on this), and I looked up the proper bits to change and then burned the bootloader. It worked fine, and I then changed the fuse bits which resulted in an error and now I again could talk to the device.

I am guessing that something is going wrong with the suggested fuse bits, but I do not know how to change them or how to fix this. The original fuse bits that I read from the device are listed below (before I messed it up).

I checked my wiring a billion times and it is all perfect. I just need suggestions to fix this mess, thanks.

```
BODLEVEL = DISABLED
OCDEN = [ ]
JTAGEN = [X]
SPIEN = [X]
WDTON = [ ]
EESAVE = [ ]
BOOTSZ = 4096W_1F000
BOOTRST = [X]
CKDIV8 = [ ]
CKOUT = [ ]
SUT_CKSEL = INTRCOSC_6CK_0MS
EXTENDED = 0xFF (valid)
HIGH = 0x98 (valid)
LOW = 0xC2 (valid)
LB = NO_LOCK
BLB0 = NO_LOCK
BLB1 = NO_LOCK

LOCKBIT = 0xFF (valid)

Detected device
Device name       ATmega2560
Device signature  0x1E9801

```

# Answer
If AVR is bricked because of wrong fuses I suppose it's typically non-working external oscillator you need provide signal to particular AVR pin to get programmer working again. Thread related to unbricking http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue.
> 0 votes

---
Tags: arduino-mega, isp, atmel-studio
---


# Question
Title: Does porting code to different MCU clock frequency affect serial baud rate?
Tried to upload my Arduino Uno sketch that writes to serial UART at 9600 baud rate onto my ATtiny2313 running at 1MHz. Not getting the signal on the ATtiny, does this have to do with my clock frequency of the MCUs being 16 vs 1MHz?

# Answer
> 3 votes
Yes, it does. As can be seen in the "USART" section of the datasheet the baud rate is generated directly from both *fosc* (aka `FCPU`) and the value contained in UBRR. The tables at the end of the section gives the appropriate value for UBRR for a given CPU frequency, desired bit rate, and state of the USART clock doubler.

---
Tags: arduino-uno, serial, avrdude, avr
---


# Question
Title: How to connect Arduino Pro Mini with PC?
I'm about to buy Arduino Pro Mini (http://arduino.cc/en/Main/ArduinoBoardProMini). As far as I can see it requires FTDI or similar circuit to program it.

Should FTDI be present for communication with PC after sketch is uploaded to chip or there is a way to connect Arduino Pro Mini DIRECTLY to USB cable and PC?

Is this also case with Arduino Pro Micro? (https://www.sparkfun.com/products/12640)

Thanks in advance Petar

# Answer
> 1 votes
V-USB can be used to create a low-speed USB device in software, but you will need to program the chip before you can use it. It also has a number of caveats that must be adhered to regarding electrical and software specifications, so it not the best choice for an absolute beginner.

A USB-UART bridge (not necessarily a FTDI chip, although that is (was?) the most popular solution) will allow you to program and communicate with the chip over its serial port, but any AVR ISP programmer can also be used to program it without requiring a preexisting bootloader in place.

# Answer
> 2 votes
The "Arduino Pro Micro" has its own USB interface so you don't need extra stuff for it to work. However, a number of existing libraries that deals with Arduino shields do not support the new chip inside the Arduino Pro Micro (ATmega32U4) so check first to make sure it will work with what you need.

For the "Arduino Pro Mini" (which I use a lot since it is very very cheap, about $3 from ebay) to program it I use "USPASP" (also cheap ~$3) so I have three of them but you only need one to program as many Pro Minis as you like. And for communication I use a "USB to TTL UART" (based on the "CP2102" chip which works with Linux, Windows and Mac) they are also super cheap (about $2) and you connect it to the serial pins on your Pro Mini.

(Just search ebay for the terms I put in quotes and you will find many of them at low prices, they ship from china so it will take about a month to get to you which is why I ordered more than I need for future projects, or for a little extra you might find local sellers with same products)

---
Tags: usb, communication, ftdi
---


title: Change the backlight of 2x16 LCD

text:
# Question
Title: Change the backlight of 2x16 LCD
Today I ordered a 2x16 character LCD with white characters on black background.

Now I am wondering if I can change the backlight LED, which I guess is white for the characters, with a RGB LED to change the character color.

Did anyone do this before? Is it even possible that way?

I've seen RGB negative LCDs from Adafruit and Sparkfun.

# Answer
The backlight led (sample) is just a simple led with a large transparent panel, the size of the lcd, attached to it. This panel is diffused on the top in such a way that it distributes the light evenly. If you get a rgb led, file the top flat, and glue it to the side of this panel (where the leads get out of the plastic) you should get a pretty good effect.

I tested it on my white-on-blue lcd, by holding and led to the side of this panel, and it worked. Just note that you need a very bright led. Mine was pretty bright but the letters didn't light up that much.
> 0 votes

# Answer
The product you linked looks like a fairly standard LCD module, so it's probably very difficult to swap the backlight LED. Like most electronics, they're not designed to be modified by hand. It would likely need some precision re-soldering.

When you see LCDs with other types/colours of backlight, it's usually because they were originally manufactured that way.
> 0 votes

---
Tags: led, lcd
---


# Question
Title: Manchester Library Won't Compile for Attiny85
I am creating a wireless sensor using an Attiny85. I want to send the data to an arduino uno, so I purchased the 315mhz rf link kit from spark fun. Since the Attiny85 does not have a TX I decided to use the Manchester library however it won't compile on the Attiny85.

I followed the steps from this blog : http://mchr3k-arduino.blogspot.mx/2012/01/wireless-sensor-node-part-2.html?showComment=1338749638806#c853067277980266192

Here is the code I am using:

```
    #include <WProgram.h> //otherwise it says it can't find Arduino.h
    #include <Manchester.h> //include the library to comunicate
    #define TxPin 2 //the pin that is used to send data

 int sensorPin = 4;
 int ledPin = 3;
 int count = 50;

 void setup(){
  pinMode (ledPin, OUTPUT);
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(TxPin, MAN_1200); //set transimt pin
}

void loop(){
  if (count == 50){
   digitalWrite (ledPin, HIGH);
   count = 0;
   }
   int data = analogRead(sensorPin);
   man.transmit(data); //transmits and reads the data
   delay (100);
   count ++;
 }

```

Here is the error message:

```
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp: In function 'void MANRX_SetupReceive(uint8_t)':
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'TCCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'WGM21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'TCCR2B' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'CS21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:369: error: 'OCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'TIMSK2' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'OCIE2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:380: error: 'TCNT2' was not declared in this scope

```

# Answer
attiny is missing an option required to allow the Manchester library to function properly on ATtinyX5 devices, specifically definition of `__AVR_ATtinyX5__` when a device is selected. In fact, it's missing quite a few things.

The package I use for ATtinyX5 support is arduino-tiny. I have verified that it defines that symbol properly. I recommend that you dump your current support package and install arduino-tiny instead.
> 5 votes

# Answer
Having struggled through this myself, I can confirm that Joel's solution works.

There are quite a lot of posts around that suggests that you can't get the Manchester to work with Arduino1.0x and you need 0020. But you can.

The key is to use the arduino-tiny from the link above, put the tiny folder which you get from there in /hardware and then rename it to attiny and “prospective boards” to boards.

I realise that this doesn’t say any more than Joel already has, but there is so much conflicting and contradictory information around I thought it would be worth adding in my experience
> 4 votes

# Answer
Got the same problem using this lib with a 8 MHz Trinket, but managed to solve it by adding `#define __AVR_ATtinyX5__` to the file hardware/attiny/variants/tiny8/pins\_arduino.h. I'm using the Adafruit support package for ATtiny. Perhaps a bit of a hack, but I can still build for the UNO, by selecting board in Arduino IDE 1.0.5.
> 0 votes

---
Tags: programming, arduino-ide, compile, attiny, rf
---


title: Ideas for setting I2C device IDs

text:
# Question
Title: Ideas for setting I2C device IDs
I am using I2C to communicate between a collection of ATtiny85s that are acting as controllers for various parts of a system and the "Main Brain" -- a RaspberryPi. Most of the ATtiny85s only have a couple of free pins left (usually Pins 1 and 2 -- the reset and the pin that can't be used for PWM) so I can't use something like a DIP switch to directly set device IDs. I'd rather not hardcode the device IDs when I push code to the tinys but I can't think of a good, simple, and reliable way to do it otherwise. Anyone here have a suggestion?

# Answer
> 1 votes
You could use the analog input on pin 1.

Have a table in your code to map voltage thresholds to I2C IDs.

Then build a voltage divider circuit as input that you can adjust with switches or by installing different resistors.

# Answer
> 6 votes
Put the address in EEPROM. It's still "on the chip" but it can be programmed independent of the flash, and can be changed on the fly if deemed appropriate.

---
Tags: i2c, attiny
---


title: releasing memory in sub-function

text:
# Question
Title: releasing memory in sub-function
I'm doing a program who get a line from the SD and shows it, this function is called *getData()*

FULL CODE:

```
#include <SD.h>
#include <MemoryFree.h>

File myFile;
int stringIndex = 0;
int cursorPosition = 0;
char inputString [25];
char inputChar;
boolean endOfLine;
char fullPath[11];

void setup(){

  Serial.begin(9600);

  Serial.print("Initializing SD card.");
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

}

void loop(){

  Serial.println(getDataSD());

  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

String getDataSD(){

  memset(inputString, 0, sizeof(inputString));

  getFileNameSD();

  myFile = SD.open(fullPath);

  if(myFile){
    myFile.seek(cursorPosition);

    endOfLine = false;

    while(myFile.available() && endOfLine == false){
      inputChar = myFile.read();

      if(inputChar == '*'){
        while(inputChar != '\n'){
          inputChar = myFile.read();
        }
      }else{
        cursorPosition = myFile.position()-1;

        if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

        while(inputChar != '\n'){
          if(stringIndex < 25){
            inputString[stringIndex] = inputChar;
            stringIndex++;
            inputChar = myFile.read();
          }
        }
        inputString[stringIndex-1] = '\0';
        stringIndex    = 0;
        endOfLine      = true;
      }
    }
    myFile.close();
  }
  return inputString;
}

void getFileNameSD (){

  char folder[] = "/ACC";

  checkFolderSD(folder);

  myFile = SD.open(folder);
  myFile = myFile.openNextFile();

  if(!myFile) myFile.rewindDirectory();

  if(myFile){

    strcpy(fullPath,folder);
    strcat(fullPath,"/");
    strcat(fullPath,myFile.name());

    myFile.close();
  }
}

```

I don't have problem with this function(getDataSD). To get the name of the file, I've created another function who looks for a file in a specific folder, this function is called *getFileNameSD()*

I'm having problem with this last function, it's not releasing or overwriting some data, so every time it's called, it is stored new data in memory

I've included the memory Free library to see where is the problem. When I call the *getDataSD* and write the file manually I dont have problem.

```
myFile = SD.open("/ACC/11001");

```

Serial monitor

```
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/

```

the memory always is the same.

but not when I call the *getFileNameSD()*

```
myFile = SD.open(getFileNameSD());

```

Serial monitor

```
freeMemory()=6571
/-27/-26/-56/
freeMemory()=6540
/-27/-26/-56/
freeMemory()=6509
/-27/-26/-56/
freeMemory()=6478
/-27/-26/-56/
freeMemory()=6447
/-27/-26/-56/

```

I know I'm doing something wrong with *getFileName()* but I don't know what is, can anybody help/explain me?

# Answer
> 1 votes
Well, finally someone found where was the problem. In the *getFileName()* function, I open two instances of the file but I close just one.

here is the answer:

```
#include <SD.h>
#include <MemoryFree.h>

File myFile;
int stringIndex = 0;
int cursorPosition = 0;
char inputString [25];
char inputChar;
boolean endOfLine;
char fullPath[11];

void setup(){

  Serial.begin(9600);

  Serial.print("Initializing SD card.");
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

}

void loop(){

  Serial.println(getDataSD());

  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

void getDataSD(){

  memset(inputString, 0, sizeof(inputString));

  getFileNameSD();

  myFile = SD.open(fullPath);

  if(myFile){
    myFile.seek(cursorPosition);

    endOfLine = false;

    while(myFile.available() && endOfLine == false){
      inputChar = myFile.read();

      if(inputChar == '*'){
        while(inputChar != '\n'){
          inputChar = myFile.read();
        }
      }else{
        cursorPosition = myFile.position()-1;

        if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

        while(inputChar != '\n'){
          if(stringIndex < 25){
            inputString[stringIndex] = inputChar;
            stringIndex++;
            inputChar = myFile.read();
          }
        }
        inputString[stringIndex-1] = '\0';
        stringIndex    = 0;
        endOfLine      = true;
      }
    }
    myFile.close();
  }
}

void getFileNameSD (){

  char folder[] = "/ACC";
  File myDir = SD.open(folder);

  memset(fullPath, 0, sizeof(fullPath));

  if (myDir){
    myFile = myDir.openNextFile();

    if(myFile){
      strcpy(fullPath,folder);
      strcat(fullPath,"/");
      strcat(fullPath,myFile.name());
      myFile.close();
      myDir.close();
    }else{
      // Handle file not found
      myDir.close();
      fullPath[0] = '0';
    }
  }else{
    // Handle directory not opened
    fullPath[0] = '0';
  }
}

```

# Answer
> 1 votes
Ok,

I don't know, why your memory is leaking, but anyway, your program won't work safely. You defined an array (fullPath) inside the local scope of your function. You return it, which means, you return a pointer to this array. But at the same time, this array gets invalid, because you leave the local scope of your function.

Better define that string outside the function and give it as a parameter to the function. Then you aren't in danger of accessing an invalid pointer. Furthermore your memory leak won't appear.

---
Tags: programming, sd-card, memory-usage, code-optimization
---


# Question
Title: how to serially communicate the arduino leonardo to pc through hyperterminal
I have connected mc to a pc using USB. I need data on hyperterminal through serial to USB connection, hence I connected TX, RX and gnd pins of the Leonardo to the rs232 pins and one other side of rs232 to USB to pc. However, the data is still transmitting on serial monitor, but not on hyperterminal.

```
int count = 0;

void setup() {
  Serial.begin(9600);
  pinMode(3,INPUT); // This is the pin to which we have connected the button
  attachInterrupt(0, IRsensor, CHANGE);
}

void loop() {
  if (Serial.available()) {
    /* read the most recent byte */
    /*ECHO the value that was read, back to the serial port. */
    Serial.write(count);
  }
}

void IRsensor() {
  if(digitalRead(3) == 1) {
    count++;
    Serial.println(count);
  }
}

```

# Answer
> 3 votes
To be sure, please add code.

You can use usb on Arduino to communicate with pc. You don't need RS232/USB converter. Just open hyperterminal with the port of arduino. Arduino port can be found in:

1. Arduino IDE Tools\>Port
2. My Computer\>Properties\>Device manager\>Ports

If you really need `SoftwareSerial` then connect Rx,Tx and don't forget GND!

**UPDATE**

To communicate with RS232/USB converter you have to add RS232/TTL converter to Arduino side. The schematic would look like PC \<-\> USB/RS232 \<-\> RS232/TTL \<-\> Arduino:

1. PC - your computer
2. USB/RS232 to convert from usb to RS232. On RS232 side the voltage is -5V to +5V
3. MAX232 RS232/TTL. To convert the voltage
4. Arduino - your MCU

**UPDATE 2**

As i said, connect your arduino to PC like you do while programming.

Next, upload this sketch:

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

void loop() {
  if(Serial.available()){
   Serial.print("\nReceived: ");
   Serial.write(Serial.read());
  }
}

```

Open HyperTerminal: choose port with Arduino,

Connect to arduino, **Serial Monitor has to be closed**

---
Tags: arduino-leonardo
---