# Question
Title: Dallas Temperature Sensor DS18B20 not showing correct Result with Ethernet Shield
I am using Arduino Uno R3 board and a wiznet W5100 ethernet Shield. The temperature from the One wire sensors before using Ethernet Shield was showing correct. However later after connecting the shield, the temperature is showing to be 85. The server and everything else works fine, but the data is all wrong. Now I am pretty sure the connections are correct and it is not in parasite mode. Any suggestions of how I might get the accurate reading ?

```
/*
  Web Server

  A simple web server that shows the value of the analog input pins.
  using an Arduino Wiznet Ethernet shield.

*/

#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
            0xF0, 0xBF, 0x97, 0x67, 0xF6, 0x98
        };
IPAddress ip(192, 168, XXX, XXX);

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
EthernetServer server(80);

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    sensors.begin();
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }
    // start the Ethernet connection and the server:
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.println(sensors.getTempCByIndex(0));
    Serial.print("Siddhartha Temperature ");
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
}

void loop() {
    // listen for incoming clients
    EthernetClient client = server.available();
    if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();
                Serial.write(c);
                // if you've gotten to the end of the line (received a newline
                // character) and the line is blank, the http request has ended,
                // so you can send a reply
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    client.println("Refresh: 2");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println("<html>");
                    // output the value of each analog input pin
                    for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                        float sensorReading = sensors.getTempCByIndex(0);
                        client.print("Temperature ");
                        client.print(analogChannel);
                        client.print(" is ");
                        client.print(sensorReading);
                        Serial.println(sensorReading);
                        client.println("<br />");
                    }
                    client.println("</html>");
                    break;
                }
                if (c == '\n') {
                    // you're starting a new line
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // you've gotten a character on the current line
                    currentLineIsBlank = false;
                }
            }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
    }
}

```

# Answer
> 0 votes
The Solution was actually much simpler. Apparently the Ground on the voltage I/O ports wasn't the right place to connect the ground terminal of the sensor. rather The Ground of the Digital I/O should be connected. Mistake retrieved by trail and error!! Its working just fine now.

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


# Question
Title: Turning all 35 leds on sequentially with MM5451
I've been struggling for a long time trying to get the MM5451 chip to light up all 35 leds sequentially without any luck. I've had intermittent help from the arduino forum, someone on youtube, and even found source code on here. But all I've been able to accomplish is either to get all the lights lit up at once, or every other led lit up at once, or having two sets of 8 leds lighting up sequentially together. I can't figure out how to get all of them lit on and off sequentially. I'm sure it has to do with shifting bits but can't figure out how to do this. Here's two sets of code that either light two sets of 8 bits together sequentially, and another program that lights every other led all at once.

Sequential lighting of two sets of 8 bits

```
#define CLK 2 // to MM5451 pin 21
#define dataBit  3 // to MM5451 pin 22

 byte singleled[]=  {1,2,4,8,16,32,64,128};
//   0b00000001, 0b00000010, 0b00000100,
 //  0b00001000, 0b00010000, 0b00100000,
 //  0b01000000, 0b10000000, 0b11111111 };

  byte singleled2[]=  {1,2,4,8,16,32,64,128};
 //  0b00000001, 0b00000010, 0b00000100,
 //  0b00001000, 0b00010000, 0b00100000,
 //  0b01000000, 0b10000000, 0b11111111 };

void setup() {
  pinMode(CLK, OUTPUT);
  pinMode(dataBit, OUTPUT);
  digitalWrite(CLK, 0);
  digitalWrite(dataBit, 0);
  Serial.begin(1200);
}

// the loop routine runs over and over again forever:
void loop() {

  for (int i=0; i<8; i++)   {
        // start bit
    digitalWrite(dataBit, 1);
    pulseCLK();
    // the "+ 0x80" turns on DP
    ssrWriteLSB(singleled2 [i]); // MOD myCount = 0-9
    ssrWriteMSB (singleled [i]); // eight LEDs binary count 0-255
      delay(500);
   // ssrWriteMSB(myCount);
    //Serial.println(myCount);
    delay(500);
   // Serial.println(myCount);
    zeroWrite(29); // pad remaining bits with 0s
    delay(500);
  }

} // end loop

void pulseCLK()   {
  digitalWrite(CLK, 1);
  digitalWrite(CLK, 0);
}

// LSB out first!
void ssrWriteLSB(byte value)   {
  Serial.println(value);
  for(int x =0; x < 8; x++)   {
    byte temp = value & 0x01;
    if (temp == 0x01)   digitalWrite(dataBit, 1); // data bit HIGH
    else digitalWrite(dataBit, 0); // data bit LOW
    pulseCLK();
   value = value >> 0x01; // shift right
  }
}

// MSB out first!
void ssrWriteMSB(byte value)   {
 Serial.println(value);
  for(int x =0; x < 8; x++)   {
    byte temp = value & 0x80;
    if (temp == 0x80)   digitalWrite(dataBit, 1); // data bit HIGH
    else digitalWrite(dataBit, 0); // data bit LOW
    pulseCLK();
    value = value << 0x01; // shift left
  }
}

void  zeroWrite(byte num1)   {
  digitalWrite(dataBit, 0); // data bit LOW
  for(int x = 0; x < num1; x++) pulseCLK();
}

```

Turns on every other light all at once:

```
#define dataBit 3
#define clk 2

void setup()  {
  Serial.begin(1200);
  pinMode(dataBit, OUTPUT);
  pinMode(clk, OUTPUT);
  digitalWrite(dataBit, 0);
  digitalWrite(clk, 0);
}

 void loop() {
     //digitalWrite(dataBit,1);
     for(int index=0; index < 36; index++)  {
          digitalWrite(dataBit,1);
          digitalWrite(clk,1);
          digitalWrite(clk,0);
          digitalWrite(dataBit,0);
          digitalWrite(clk,1);
          digitalWrite(clk,0);
      }
  }

```

Thanks in advance.

Bryan

# Answer
I think you need something like this.

```
#define CLK 2 // to MM5451 pin 21
#define DATA  3 // to MM5451 pin 22

void setup()
{
    pinMode(CLK, OUTPUT);
    pinMode(DATA, OUTPUT);
    digitalWrite(CLK, 0);
    digitalWrite(DATA, 0);
    Serial.begin(1200);
}

// the loop routine runs over and over again forever:
void loop()
{
    for( byte led=0; led<35; led++ )
    {

        lightLed(led);

        delay(1000);
    }
}

void lightLed(byte index)
{
    //always send a one first
    sendOne();
    // turn off all leds preceding index
    for( byte i=0; i<index; i++ )
        sendZero();
    // one led on
    sendOne();
    // pad with leds off
    for( byte i=index+1; i<35; i++ )
        sendZero();
}

void sendOne()
{
    digitalWrite(DATA, HIGH);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}
void sendZero()
{
    digitalWrite(DATA, LOW);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}

```
> 1 votes

---
Tags: shift-register
---


# Question
Title: Program arduino via USB while using a Bluetooth module (HC-06)
I have my Arduino Nano connected to the HC-06 module (with the RX/TX pins).

My issue is that when I try to upload new code to my Arduino (via the Arduino IDE, through the USB connection) the Arduino IDE doesn't succeed.

I get this error:

> avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x00

I believe that it is just trying to upload the code to the HC-06 (instead of the Arduino). Is there a way to overcome this issue?.

Thanks.

Note: I found this entry https://stackoverflow.com/questions/27175937/arduino-program-upload-while-btooth-module-connected-avrdude-stk500-getsync indicating that it wasn't possible (that I need to unplug the module). I am trying to confirm it.

# Answer
The link in question was correct... you do need to unplug it.

The Arduino's serial chip uses pins 0 and 1 to communicate with the ATmega 328 PU chip onboard, thus you have two independent devices connected to the same wires and both the Arduino main chip and the Bluetooth module are trying to communicate at the same time (rendering all data unreadable by the computer).
> 2 votes

---
Tags: bluetooth
---


# Question
Title: how to send input values from host computer to arduino
how to send input values from host computer to arduino,such that speficing the number of rotations for a stepper motor etc

# Answer
The easiest method is to use the serial communication. Use the sample code at http://arduino.cc/en/Tutorial/SwitchCase2, upload that to an Arduino, start the serial monitor (Ctrl+Shift+M), make sure the baud rate is the same as set in the code (9600 in this case), then write the commands and send them to the Arduino.

**Edit** Since the serial characters are usually read one by one you need a character that will signal the end of the string. This is usually a newline `\n`, but can be any character you choose (and can be sent to Arduino).

Sample code (`processString` would be your function to do something with the string):

```
char buf[64];
byte cnt = 0;
void loop()
{
    while (Serial.available()>0) {
        byte c = Serial.read();
        // Check for terminator character or the size of buffer
        if (c == '\n' || cnt >= 63) {
            // Add the terminating 0
            buf[cnt] = 0;
            // Process the full string
            processString(buf);
            // Prepare to read the next string
            cnt = 0;
        } else {
            // Not terminator - add to string
            buf[cnt++] = c;
        }
    }
}

```
> 1 votes

---
Tags: arduino-mega, motor, firmware
---


title: trying to delay between sequences

text:
# Question
Title: trying to delay between sequences
I am trying to build a set of four stars using an Arduino, potentiometer and a four channel relay to control how fast it speeds across the stars. My question is how can I delay the process, say for 20 or 30 seconds before it starts again?

# Answer
Use Delay( ). Or this code

```
long previousMillis;

void setup(){
  previousMillis = millis();//in void setup
  bool lS=LOW;//in void setup
}

void loop(){
  long currentMillis= millis();//in void loop

  if(currentMillis-previousMillis>=20000){
     if (lS==LOW){
       digitalWrite(pinNo,HIGH);
       lS=HIGH;
     }
     else
     {
       digitalWrite(pinNo,LOW);
       lS=LOW;
     }
     previousMillis= millis();
  }
  delay(1);
}

```

While this does not serve your purpose, it shows you an how to switch on and off and LED after every 20 sec without keeping the Arduino idle for 20 sec.You could improve on it and make your own code.
> 3 votes

# Answer
If you want to just provide a delay use this function

```
delay(ms) -> where the argument is an integer value that represents the time in milliseconds.

```

For example, 1s = 1000ms

If you wanna stop everything and wait 1s, just use like that:

```
delay(1000);

```

Note that the atmega controller will stop everything it is doing and wait the amount of time. If you need to count or wait for something while other things are occurring, use timer interrupts. So the counting process is done in background and your main loop continues to do its jobs.
> 1 votes

# Answer
`delay()`:

```
delay(20000); // wait for 20 seconds

```
> 0 votes

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


title: Arduino IDE doesn't find header file

text:
# Question
Title: Arduino IDE doesn't find header file
I'm trying to start with the SainSmart 4x20 serial LCD, and copied the library to the Arduino library:

So `LiquidCrystal_I2C.h` is included. But when I try to compile an example sketch it says

> Arduino: 1.7.0 (Windows 7), Board: "Arduino Uno"
>
> HelloWorld\_i2c.pde:2:31: fatal error: LiquidCrystal\_I2C.h: No such file or directory
>
> compilation terminated.
>
> Error compiling.

Any ideas how to fix this?

# Answer
I copied the SainSmart library to the IDE's library folder, not noticing that there was already a folder named "LiquidCrystal". Apparently the files added to the existing folder are being ignored.

Renaming the SainSmart library before adding it solves the problem.
> 4 votes

# Answer
There is not enough info to give a specific answer so I will give some troubleshooting tips:

1. First make sure at the top of your code you have: #include \<LiquidCrystal\_I2C.h\> - with angle brackets
2. You may also need the Wire header file: #include \<Wire.h\> - with angle brackets
3. Make sure you Include Serial
4. Make sure there are no extra folders in the library for example there should be a folder called liquidcrystal inside the liquidcrystal folder
5. If all fails copy the code from the header file make a new file in the IDE paste it in there and call it LiquidCrystal\_I2C.h

Hope one of those solves your problem.
> 0 votes

---
Tags: library
---


title: output of yun is not 3.3

text:
# Question
Title: output of yun is not 3.3
After execute the program of below, the 13 pin output is 4.8v. Why it's not 3.3v?

```
void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(13, HIGH);
}

```

# Answer
> 1 votes
The Atheros chip on the Yún is run off 3.3V, but the AVR chip, which is what is connected to the external pins, runs off 5V. What you are seeing is normal (a bit low though, but within spec).

---
Tags: arduino-yun, voltage-level
---


title: Isolating IR receiver from disruption?

text:
# Question
Title: Isolating IR receiver from disruption?
I'm using a simple IR receiver connected to the Arduino through A0 analog pin. The problem is that I want to stabilize the output of IR receiver when it's not receiving an IR signal from a specific IR source, or at least minimizing the disruption to a specific range that I can handle, no matter where its position, But in my case moving the IR receiver a few inches in any direction will results in different voltage output. the difference between values on disruption is very random to handle.

What can I do to isolate IR receiver, may be a specific material or a specific color?

# Answer
> 0 votes
I would suggest two things. First You could put electrical tape around the receiver in such a way that it will only pick up signals from a certain direction. Also you could use low and high pass filters to accept input only in the 38khz range(range of most infra red remotes). Keep in mind that you will need a couple of rounds for it to work effectively.

---
Tags: arduino-uno, ir
---


# Question
Title: How do I send an IR signal from an Arduino
I want to send a generic (not Sony, etc.) remote's signal from my Arduino. I have already used a IR decoder program to capture the timing of the signal:

```
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    88, 88,
    174, 88,
    86, 86,
    88, 86,
    88, 88,
    86, 86,
    88, 174,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 2252,
    88, 88,
    174, 88,
    86, 86,
    88, 88,
    86, 88,
    86, 86,
    86, 176,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 0};

```

Now I need to send this through the IR LED. I have never written a program that can modulate a signal at this microsecond level. How would I do this?

# Answer
> 1 votes
Use the IRRemote library as mentioned and use the IRecord example. This will allow you to input a signal and then push a button which will send that signal from the infra-red LED on the arduino.

# Answer
> 0 votes
Please, take a look at Ken Shirrif's IRRemote library, as it is what you need. I used it in some project and worked better than other solutions that I coded.

---
Tags: ir, signal-processing, timing
---


# Question
Title: What is the circular gold pad on arduino mega 2560 v2 and above?
Could someone point me to the documentation that describes the gold dot and surrounding gold circle on the front of my arduino mega v2 board. It is right above the ICSP header and reset button, and directly underneath the letter 'U' in the silk screened word 'communication' I've not been able to find any reference to it anywhere. Is is a jumper, a test pad, RF pad???

# Answer
> 9 votes
That is most likely a Fiducial Mark for the vision system of a pick-and-place assembly robot to key off of in order to more precisely place the components on their pads.

If you look carefully, you will see a second one located below the DC barrel jack.

Boards like this are manufactured in a gridded panel having a number of copies in each direction, and only cut apart after they are largely complete. With such a large workpiece, any linearity error in the manufacturing could result in a high-density component being misplaced far enough to cause problems. Having a pair of fiducials on each individual board in the panel can help calibrate out errors not only which might otherwise accumulate over the large dimensions of the entire panel, but also rotational skew of the panel in its holder.

You can see both on this picture of the Arduino Mega 2560 from the arduino.cc site

# Answer
> 1 votes
To add to Chris's answer: fiducials appear at three levels. First there are fiducials at the panel level, which contains one or more PCBs, depending on their size. Next there are fiducials for the PCB, acting as a position reference for component placement. Sometimes you can see component fiducials close to some fine pitch components, to make sure they are placed with high precision. You'll sometimes see these latter fiducials on opposite corners of QFP (Quad Flat Package) parts. (The AVR controller on the Arduino Mega 2560 is in QFP.)

---
Tags: arduino-mega
---


title: DS3231 DTCXO and GPS

text:
# Question
Title: DS3231 DTCXO and GPS
I am experimenting with this idea: keep a DTCXO in sync with some frequency standard. I have all the parts I can afford, but I cannot figure out a way to do it.

Parts I have: Arduino Leonardo, a `u-blox 6010` based GPS module with PPS output, and a proto shield with `DS3231` DTCXO chip mounted.

My big idea is that `DS3231` have aging registers that would affect the clock frequency. By keep counting the 8192Hz square wave output of `DS3231` and keep it in sync with the 1Hz signal from the GPS module, I can keep the DTCXO in sync with a reference clock. This, in turn, would give me a relatively good 32768Hz clock reference that I can build a frequency counter on.

Both 8192Hz and PPS are interrupt driven.

Anyone have an idea on how to do it? Does this spell Artificial Intelligence on AVR, as my instructor suggests?

# Answer
> 1 votes
Hope you get this. Trimming the aging compensation in the DS3231 is not worth the trouble. You won't significantly improve the temperature accuracy or aging drift due to the crystal used, etc. On the other hand, 10MHz Double Oven Reference Oscillators are available for under $50 on EBAY. These are good to 2x10-12 short-term, or about 1x10-6 yearly drift. For timekeeping purposes, you can ignore the short-term drift, could not measure it anyway :). On the other hand, the aging drift will be large because you do not know how long these have been in service. The good news is that aging drift is very stable if temperature is kept constant, the reason for the double ovens. So once you determine how far off frequency the OCXO is, you just periodically add a count to your divider during one period to keep it synched to the GPS signal. For more info write mhuss103athotmaildotcom

---
Tags: gps, rtc
---


title: Wi-Fi Module communication?

text:
# Question
Title: Wi-Fi Module communication?
I bought a Arduino Wi-Fi Module it does not have any manual or catalog

my project is to turn on/off a motor wireless it is working grate for the serial/usb cable but i couldn't make it work for wireless/wifi

after some walking around i found that my wifi module is making a wifi network called "HL-link\_A49D" with password from 1-8 and after network scanning i found that the module ip is 192.168.16.254/ username and pass are admin/admin here is what i found

my question is how could i connect to the wifi module and send commands to it ?

# Answer
Good detective work so far!
In the admin page you found one can see the name of the module: `HLK-RM04`. Googling on that I found the manufacturer/seller page.

A PDF with some information can be found here.

Also one link with somebody's experience with the module.

For other projects you might want to try as well the ESP8266 - very cheap and seems a lot of people have experience with it, so you might find more information on the net.
> 1 votes

---
Tags: arduino-uno, wifi, tcpip
---


# Question
Title: How do I update the serial monitor without printing a new line each time?
I'm testing out an accelerometer and I want to know if there's a way to make it so that the serial monitor will update the values without printing a new line. Ideally the serial monitor would say something like:

```
Accelerometer X: $xval
Accelerometer y: $yval

```

and then instead of printing two new lines each time, it just updates the values. Is there anyway to do that in Arduino? Thanks.

# Answer
> 6 votes
The ultra-basic "serial monitor" in the Arduino IDE cannot do what you want.

Instead you need to either write a special client program, or use a more standard serial terminal program, such as Tera Term (Windows), Minicom (Linux), etc.

These standard serial terminal programs use a special sequence of characters called *ANSI escape codes* which manipulate the display, doing such things as setting colours, moving the cursor around, etc.

More information on ANSI escape codes can be found here: http://en.wikipedia.org/wiki/ANSI\_escape\_code

# Answer
> 3 votes
No. The serial monitor does not support terminal handling. Either use a serial communications program that does and use those features, or write a custom client that will only update those values in its interface.

# Answer
> 1 votes
You might want to look into processing. You can use that to view the accelerometers position in 3d and see the values changing if that's what you want. The official Arduino site talks about it here. Here is a great tutorial on it.

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


title: Line Follow Vehicle

text:
# Question
Title: Line Follow Vehicle
I know this is very common project and it's already been done, however, most of the guides don't have a clear instruction, and being this inexperienced, I struggle to understand exactly what's going on.

I'm currently working on a line following robot, but I'm largely inexperienced. For the most part, I'm going to be using SparkFun's Magician Chassis with Inventors Kit. The main sensor available is the Line Sensor Breakout(QRE113), which I have 3 of, but I'm not sure if whether I should use the Digital or Analog model.

Also, I'm having trouble finding how to wire this circuit. I know as much that, I have to connect the motors, diode, simple transistor(with emitter, collector, and base), some sort of resistors, and maybe a capacitor(this one I'm not too sure of). All of this has to be set on a breadboard, and be jointly connected to the arduino. I think there has to be two identical circuits on the breadboard for each motor, as the voltage of the sensor is expected to decrease when it encounters a white reflective surface(tape), this in turn will slow down the motor, which would allow the robot to turn in the direction of the tape, due to the other wheel not slowing down. One part of the circuit, should handle the motor drive circuit, this should be the output of the transistor, but I'm not sure how to use the arduino(redboard) to control the speeds of the motors using the sensors, which I think will go into the base of the emitter. Which pins should I use basically?

Apart from this, how will the code look? But I think this is dependent on how I wire it, right?

This is what I'm using...

https://www.sparkfun.com/products/12060

https://www.sparkfun.com/products/9453

# Answer
You should, really, cut this complete project into smaller little projects. Actually, first you should get clear what you want, there are a lot of possibilities.

* Try to get one line sensor working
* Try to get one motor working (check Pulse Width Modulation)
* Try to get the two motors working and put them on the chassis.
* Make the motors drive around a little, turn and reverse.
* Get the three line sensors working (I think you're following a single line withouth crossroads etc.?)
* Make your arduino check for changes in the pattern 0 1 0 respectively for the line sensors would mean that you're on the line. If the pattern is 0 0 1, you're driving off the line to the left.
* Use the engines to adjust back onto the line.

I've actually done a project similiar to this one, but we used a motor-board instead. Driving the motors with a transistor&diode(&mosfet?) should indeed also be possible... but it'll get difficult once you want to be able to also reverse the motor (check H-Bridge motor driver).

For the patterns, you should make a `switch case` which checks the last pattern and keeps steering until he finds the right pattern again. But this can be achieved in many other ways.

Try to get a line sensor working, be sure to check some tutorials before you ask here and try to use different kinds of tape, blue tape didn't work for us :)

It's a really fun project, with lots of possibilities.

---

Below the schematics we used in the project.

* We used a motor controller board.
* Bluetooth module to receive command/routes from the server.
* (LS) line sensors, 5 of them, to see crossroads/sideroads.
* (Infrarood) IR sensors for collision detection.
* (RS) I actually have no idea which sensors these are.
* (Ultrasonic Sensor) Ping sensor to determine distance to other robots.
> 1 votes

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


# Question
Title: ttyACM0 no such file or directory On Ubunutu 14.04
I have an Arduino Uno which communicated with the computer (Ubunutu 14.04) fine till 6 days ago (I assume some software update is to blame).

Now when trying to upload I get

processing.app.SerialNotFoundException: Serial port '/dev/ttyACM0' not found. Did you select the right one from the Tools \> Serial Port menu? at processing.app.Serial.(Serial.java:191) at processing.app.Serial.(Serial.java:77) at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:77) at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:175) at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67) at processing.app.Sketch.upload(Sketch.java:1671) at processing.app.Sketch.exportApplet(Sketch.java:1627) at processing.app.Sketch.exportApplet(Sketch.java:1599) at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380) at java.lang.Thread.run(Thread.java:745)

When I sudo ls /dev/ttyA\*

I get

```
ls: cannot access /dev/ttyA*: No such file or directory

```

So it does not look like a permission issue.

when I lsusb

I get

```
Bus 001 Device 002: ID 8087:8000 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 002 Device 003: ID 04f2:b39a Chicony Electronics Co., Ltd
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

```

So it does not even see the device (which is connected and pulling current).

when I dmesg before and after connecting the Arduino, I don't see anything new.

I tried switching USB cables, and switching USB ports on the machine (both ports work with a mouse), but in vain.

What went wrong and how do I fix it ?

Thanks, David.

# Answer
Ok, it sounds like there is an issue with the ATMega(8/16)U2 chip or its surroundings. It might just need its firmware refreshing (which can be done with another Arduino as a programmer) or it might be plain dead.

Another possibility is the USB socket itself. I have two UNOs, one which is perfectly fine, and one where I need to hold the cable at just the right angle for it to connect properly. You can try using a fine needle to try and raise the four metal strips in the USB connector a fraction to make better contact.
> 2 votes

---
Tags: arduino-uno, uploading, usb, linux
---


# Question
Title: Lithium Polymer/LiPo set to power Arduinos
I want to switch from using disposable 9V blocks to a proper setup of 3.7V LiPolys for all my portable Arduino (Uno/Mega) projects consisting of:

* only 3.7V LiPo units
* charger
* upconverter (to 5V)

My questions:

* Is this generally a good idea? Or is there a better solution for portable Arduino power?
* How should I actually hook the LiPolys up to the Arduino? They usually ship with JST connectors. Should I use the Vin/GND Pins or should I build my own JST/DC-Connector adaptor? I want to create a robust, pluggable solution.
* Am I actually losing power twice that way (once in the upconverter and then in the Arduino voltage regulator)?

# Answer
If you can get away with it, I recommend not using a boost converter and instead connecting the battery directly to the supply voltage input (the "5V" pin).

The AVR chips used in most Arduinos (but not the Due or Zero \[and the Yún and Tre are a totally different kettle of fish entirely\]) can operate with anywhere between 2.7 and 5.5 volts, with the ATmega328P found in the Uno able to run with as little as 1.8V. This is a *much* larger range than the 3.0-4.2V available from rechargeable Li-ion/Li-poly/LiFePO4 cells.

Naturally you will need to make sure that any external components can run with the reduced voltage as well, but quite a few are able to work with anything from 2.0 to 5.5 volts.
> 5 votes

# Answer
Sparkfun do the ideal solution for you - their "LiPower" shield:

It contains the Li-Ion / Li-Poly charger, 5V boost converter, and MAX17043G+U fuel gauge chip.
> 1 votes

# Answer
Consider using 2 x LiPo is series (2S). Vmax is 2 x 4.2V = 8.4V
This may be attractive compared to boosting from a single cell.
This is still \< the 9V you used previously.
Vmin is say 2 x 3V = 6V - but higher is better for the LiPos.
You can use a buck converter or a linear regulator as desired, and could use one or other depending on project.
You could even use linear + buck in parallel for applications where sleep current is very small and buck converters may find efficiency at very low I challenging.

Using 5V rather than less than 5 is attractive in that you do not need to ensure the processor speed will accommodate the lower voltages.

Using a linear regulator and 5V:
Efficiency at 4V/cell = 5/8 = 62.5%.
Efficiency at 3V/cell = 5/6 = 83%.
Any sensible buck regulators will be more efficient at more than a few mA but at very low currents that may be acceptable.

2 LiPo in 2S will notionally need balancing occasionally but this is easy to do informally occasionally or using any of the many available charging ICs.
> 1 votes

---
Tags: power
---


title: Intterupts For Arduino

text:
# Question
Title: Intterupts For Arduino
I am making a moving robot that will be autonomous in many respects. However if something goes wrong I want to be able to use a remote to push a button and it stop in its tracks no matter what function its in. My understanding is that interrupts can do that. The official site I did not find to be helpful. Any ideas? Or if the scheduler library would be of use.

# Answer
An interrupt can not *always* stop the code, although that is almost always the case. Certainly having an interrupt based kill switch would be better than a "regular code" polled one, which would still be better than nothing. If possible I would feel safest with a cut-power-to-the-whole-thing style safety switch.

Many functions that have sensitive timing constrains disable interrupts while they are active. It is rare for any of these to take a noticable amount of time, but it is possible that a bug in an interrupt dissabled function or another interrupt function could cause it to block and in that case your stop switch wouldn't work. rare, but possible.

I suppose you could turn on the chip watchdog timer, have a regular timer based interrupt reset the watchdog timer at a certain interval, and have your interrupt safety switch enabled. Then if interrupts ever stopped firing for too long the chip would reset itself. Checkout AVR132: Using the Enhanced Watchdog Timer. I've never used the watchdog myself, but it exists for a reason.

I don't have enough experience with a scheduler system to know if they would be helpful.
> 1 votes

# Answer
If you are using an arduino uno, pin 2 and 3 are the hardware interrupt pins. You may send rising , falling, high or low signals to these pins using a Bluetooth module (for eg). Say for eg when you press the remote switch, Bluetooth gets a low signal and triggers an interrupt. If the output of Bluetooth is connected to pin 2, then in the setup you have to declare

```
attachInterrupt(0, stoprobo, LOW);

```

And in the function stoprobo, you can write the code to stop your robot.
> 1 votes

---
Tags: interrupt
---


# Question
Title: How to precisely control servo motor by changing duty cycle?
I developed a PWM using timer1,using arduino uno and digital output, and identified that when I send a wave with duration of 0.6ms in High level, the motor goes to 0º. If I send 2.1ms, it goes to 180º. I tried to make a relationship between these scales to send the angle and change the time period in order to achieve that angle and it did not work.

I would like to move with a precision of 1 degree, is that possible? Just adjusting the time period.

The model of the motor is mg996r. Maybe I am missing something.

My code just generates an interrupt over 50 microsencods and I use this to set the frequency of 50Hz and the duty cycle in ms using digitalWrite associated with pin 9.

```
#include <TimerOne.h>

double t = 0.0;

double period = 0;

void setup()
{
  t = 0;
  Serial.begin(9600);

  pinMode(9, OUTPUT);
  Timer1.initialize(50);
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here
}

void loop()
{
  // Main code loop
  // TODO: Put your regular (non-ISR) logic here
  if (Serial.available() > 0) {
    float grau = Serial.parseFloat();

    // receive data as angle
    if (grau > 180) grau = 180;
    if (grau < 0) grau = 0;

    // set period for that angle
    // relationship developed between angle and period in ms
    //set it to period
    period = (0.00833*grau + 0.6)*1E-3;
  }

}

/// --------------------------
/// Custom ISR Timer Routine
/// --------------------------
void timerIsr()
{
    t += 50E-6;
    if (t <= period) {
      digitalWrite(9, HIGH);
    }
    else if (t < 20E-3) { // periodo max de 20ms -> 50Hz
      digitalWrite(9, LOW);
    }
    else {
      t = 0;
    }
}

```

**UPDATE**:

I just got it working by creating a timer1 interrupt on CTC mode with a frequency of 100kHz and counting the necessary time to get increments (~ 10us each) of around 1 degree on my servo motor.

More info here.

# Answer
The best is to use 10us Period, instead of 50us.
That precision will be close to 1°
> 3 votes

---
Tags: arduino-uno, motor, pwm, servo
---


title: Communicating with Arduino

text:
# Question
Title: Communicating with Arduino
In this Question how does the code `Processing` work? Which programming language is it written in? How to run it?

# Answer
> 2 votes
"Processing" is a simplified programming language/environment based on Java. It's designed to be very easy for non-programmers to use, and is quite a popular choice for using alongside Arduino projects.

You can download it for free (and get lots of tutorials/documentation) from here:

As a side note, the Arduino IDE was based on Processing, so it will probably look familiar!

---
Tags: programming
---


# Question
Title: What is the physical location of the U1A symbol on Arduino Uno?
I'm trying to find an easy way to allow an Arduino Uno to determine if it's being powered from USB or the DC barrel jack. In this thread, one user recommends wiring the output of the on-board comparator op-amp (U5A pin 1) into the digital input pin.

I couldn't find U5A on the current schematic, but I think he's actually referring to U1A pin 1. Is this correct?

Unfortunately, I'm not sure where on the physical Arduino that device is located. I have one in front of me, and almost none of the parts are labeled on the silk screen. How do I find out where it is? I've googled for Arduino Uno part placement schematics, but all I'm finding are blurry unlabeled low-res images.

# Answer
The op-amp is a LM358 so you can look at the ICs themselves. Also it's a dual comparator with 8 pins. On my example image below you can see it below the crystal. I can't comment if that's the correct way to sense what you need, but it seems the comparator output should be 1 if there is external power applied. You could check with a multimeter.
> 9 votes

---
Tags: arduino-uno
---


# Question
Title: Porting Arduino code to AVR/C++ input not working?
So. I'm trying to read an input on the Arduino Nano using C++/AVR/Eclipse instead of the regular arduino IDE. The code below is working in the arduino IDE

```
void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(digitalRead(5)){
    digitalWrite(13,1);
  }else{
    digitalWrite(13,0);
  }
}

```

I'm porting the code to AVR/C++ in Eclipse, regular blinking leds is working... but I can't read inputs for some reason...

```
#define F_CPU 16000000UL //16MHz
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;//Setting all portB pins to output (D13/PB5 - LED)
    DDRD = 0x00;//Setting all portD pins to input  (D5 /PD5 - INPUT)

    while(1){
        if(isset_bit(PORTD,PD5)){//if input... doesn't work?
            set_bit(PORTB,PB5);//Set output (Tested to be working)
        }else{
            clear_bit(PORTB,PB5);//Clear output
        }
    }
}

```

# Answer
> 4 votes
During the creation of this question I found out the answer... Though I wanted to share it with you guys for later reference. It has been quite a time since I have worked with AVR.

**You should read pins from PINx**

**You should set pins in PORTx**

**Set DDRx to 1 for OUTPUT and to 0 for INPUT**

^ This is fun because PIC/Microchip MCU's use 1 for input and 0 for output.

See code below:

```
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;
    DDRD = 0x00;

    while(1){
        if((PIND&(1<<PD5))){
            set_bit(PORTB,PB5);
        }else{
            clear_bit(PORTB,PB5);
        }
    }
}

```

---
Tags: avr
---


title: Alternative to Tone( )

text:
# Question
Title: Alternative to Tone( )
Is there any way to make sounds using an Arduino without using the tone function?
It must be possible via this new method to control frequency of sound.

# Answer
I've used a somewhat more complex method with some success, which uses 2 timers to play 8kHz sampled audio. The idea is that one of the timers runs at 8kHz to determine the PWM duty cycle of the other, which runs at as fast a frequency as possible.

While the original code uses a short stored sample (On an Arduino, you could store maybe 3 seconds of audio that way), my usages involved computing the audio on the fly by overlapping several sine waves or using table lookups with varying strides. As long as computation is kept simple, this just barely works.
> 4 votes

# Answer
Thanks a lot, but anyway, I got an answer myself.
I can use the simple delaymicroseconds( ) .
Also, I can use timer interrupts to do basically the same thing
And these are a lot less complicated than the other answers I got.
> 0 votes

---
Tags: programming
---


# Question
Title: Uploading/Flashing different programs to two different Arduino uCs, using one USB
I'm designing a custom dual-uC board, where I want there to be two Arduinos both running different programs - kind of dual core arduino. In order to load new programs onto the uCs, yes, I could have two USB ports each connected to one of the uCs (say a ATmega32u4). But I'm trying to work out strategies with just one USB port (and no usb-hub).

Also, I don't need the USB functionality for general use, only for program updates.

Option 1:

Switch access to each USB capable Arduino (e.g. ATmega32U). Program one uC, toggle switch, program other uC

EDIT: this is fine, however I ideally want to use zero additional end-user buttons - I want the end-user to do as little as possible.

Option 2:

The arduino UNO has two devices, ATmega16U2 and a ATmega328. During normal operation the 16U operates as a usb-to-serial. However, I'm aware that there are custom firmwares that allow different functionality (such as USB-Joystick etc) - it is possible to switch firmawares between a custom-firmware and default firmware, to allow the ATmega328 to be programmed normally but also to run the custom program. But it seems that Arduino.h doesn't support the ATmega16U2, so I would have to program this device using the AVR or another framework.

Alternatively, the ATmega32U4 is supported by Arduino.h but there doesn't seem to be Arduino usb-serial 'firmware' for the 32U (only the 8U & 16U)

Option 3:

Can I use a ATmega32u4 with Arduino-ISP programming an ATmega328p?

EDIT: above seems valid: https://petervanhoyweghen.wordpress.com/2012/09/16/arduinoisp-on-the-leonardo/

Other simple recommended approaches?

EDIT: the firmware update should be physically as hands off as possible, as to be used by end-user, and preference for solutions that require zero additional buttons/etc

UPDATE:

I tried the Arduino as ISP method (option 3), and it works

# Answer
> 1 votes
Provided that you are okay with producing a customized PC side tool (which you would probably want anyway for user convenience) automated target selection should be far superior to manual.

You should be able to use one ATmega16u2 with a minimally customized firmware as a front end to program two distinct ATmega328p's. This could be as simple as selecting the target based on the baud rate, having it hold the de-selected one in reset the whole time, and using some resistors on the shared TX lines for safety. Last I checked the stock firmware used a soft serial at some rates, and that can be put on different pins, so it could be another way to de-conflict and select targets.

Your idea of using a 32u4 both as a functional part and as a buddy-programmer for another part is perfectly valid too - you can do that programming to a serial bootloader (it should be a simple matter to port the 16u2 firmware, or find another example), or via the ISP pins.

Now that I think about it, there's been a version of this question here before, as I remember writing about an idea for using two ATmega328p's permanently wired to a stock USB-serial, but with their bootloaders customized to use unique baud rates, and a little logic added so that on reset each would leave its serial TX pin tristated if it didn't detect bootloader traffic at its individually unique baudrate, thus allowing the other to be programmed without interference.

# Answer
> 1 votes
Option 1 using three header pins and a jumper wouldn't take up much board space, is simple to implement, and easy to use. Even easier if the jumper has a handle.

---
Tags: uploading
---


# Question
Title: Motion sensored speaker with display screen?
I want to create a motion sensored system, if the motion sensor detects motion it will make a speaker play a sound and a screen will record the time. This needs to be a loop that turns on for x number of hours and off for z number of hours. Also, I need the speaker to loop through different sounds...

I'm new to this sort of programming so any help anyone can give me on how to write this code would be greatly appreciated, thanks.

# Answer
Good project idea...This breaks down very nicely into parts that you can build and test individually.

First, I would start with the blink example, this will be helpful when debugging the other parts and it will guarantee that you have everything setup and can program the Arduino with the IDE.

Then there's the actual pieces to get the project working.

\*Play a Sound \*Display Information \*Record Time of Day \*Enable and Disable based on Elapsed Time or Time of Day \*Motion Sensing

To play a sound you have a couple of options. The simplest would be to get a buzzer since you can control these right from an Arduino pin. If you want to play a specific MP3 or wav file, you will need a slightly more involved setup. Here is an example for playing a tone with a buzzer. http://www.arduino.cc/en/tutorial/tone

For the motion sensing you probably want a PIR sensor. You can find them everywhere (Ebay, Sparkfun, Adafruit, Amazon, etc). You can also google Arduino PIR Example. Here is one result. http://playground.arduino.cc/Code/PIRsense

Once you've got those two bits working you can play a tone, when motion is detected. Next is the display. Outputting to an LCD is pretty easy. There's a few ways to do this. You may want to find a tutorial for the specific LCD screen that you decide to buy. (While you are looking, check out the OLED screens from Adafruit, they are pretty neat). Anyway, get the screen working in code by itself, then you can connect it to the rest of your system to print something when you trigger the motion sensor and play the tone.

So, the timing...This is a little more involved. The Arduino does not have a real time clock (RTC) so it can't tell the time. You would have to get a separate RTC module and set the time on it. I haven't worked with those before but...there are a few ways to interact with time. If motion is triggered, you can check the time and if it is between the times that are valid (which you would define) then trigger the speaker, otherwise don't.

Once you can get the time from the RTC, you can display that information to the screen.

That should get you started.
> 1 votes

---
Tags: sensors
---


title: Arduino Ultimate GPS Logger Issue

text:
# Question
Title: Arduino Ultimate GPS Logger Issue
I am new to electronics and learning how to play around with arduino. I recently purchased the Arduino ultimate GPS Logger, and despite also buying an external anntenae the GPS data shows that it does not fix at all. Despite leaving the unit powered for more than 5 minutes. Please advise on what could be wrong. Is it normal to take so long to get a GPS fix? This is the Arduino in question. https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/overview

# Answer
This style of antenna can be very finicky. GPS on this module may take 15 or 30 minutes to lock, not just 5. I would suggest you take this outside away from any walls or buildings and see if it will lock then. I also suggest that you run it off a battery. (one of those USB battery packs for charging your phone will work great). Once you get a lock try changing one variable at a time (power supply / location) and see if you can get it to look again.

The reason this module takes longer to lock than your cellphone is that your cellphone is cheating by doing a warmstart. The cellphone can get a semi-accurate time/date and also your regional location. This warm start data improves GPS lock time down to 5 seconds or less sometimes.
> 1 votes

---
Tags: gps
---


title: Problem with NFC on Arduino MEGA

text:
# Question
Title: Problem with NFC on Arduino MEGA
My Objective :

I am trying to send my Mifare's unique number with some other parameters to my server database. As soon as the tag come closer to NFC, it detects, and some additional details are passed to the server Database.

Steps done :

1. I have Arduino UNO, Arduino GSM shield and Adafruit NFC shield . I had tried my test with UNO and works well. But to add some more features, due to memory salvation it could not be achieved through UNO. Then we moved to MEGA.
2. There are some changes need to be done with MEGA to make \[url\]http://arduino.cc/en/Guide/GSMShieldLeonardoMega\[/url\] GSM shield coordinate with the microcontroller\[Take the Pin 2 out from GSM shield and with jumper connect Pin 2 with Pin 10\]. Then we did and we tested it with GSM web client example and worked fine.
3. Now to accomplish our goal, when we placed NFC shield above the GSM shield and executed same GSM web client example, it is not working. And Suddenly once in a blue moon it connects to the GSM network and works . But often, it fails.

\[code\]

```
/*
  Web client

 This sketch connects to a website through a GSM shield. Specifically,
 this example downloads the URL "http://arduino.cc/asciilogo.txt" and
 prints it to the Serial monitor.

 Circuit:
 * GSM shield attached to an Arduino
 * SIM card with a data plan

 created 8 Mar 2012
 by Tom Igoe

 http://arduino.cc/en/Tutorial/GSMExamplesWebClient

 */

// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

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

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

// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/asciilogo.txt";
int port = 80; // port 80 is the default for HTTP

void setup()
{
  // initialize serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;

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

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

  // if you get a connection, report back via serial:
  if (client.connect(server, port))
  {
    Serial.println("connected");
    // Make a HTTP request:
    client.print("GET ");
    client.print(path);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.available() && !client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    for(;;)
      ;
  }
}

```

What is the problem? and where is the problem ?

# Answer
> 1 votes
It is likely that placing the GSM shield between the Arduino Mega and the NFC shield is interfering with the GSM antenna. Antennas react in strange and usually less useful ways when large conductors are placed nearby.

You could try reversing the order of attaching the shields, or you could try spacing the shields further apart using "stackable Arduino headers" (you can do a web search for suppliers). If there is an option for an external antenna, that would be even better.

If you get GSM working, you might still have some trouble with the NFC shield, as it's possible that the GSM transmitter being so close could interfere with the NFD's circuitry - not because they use the same frequences, but just because any conductor so close might pick up electrical noise, and there will be various sensitive circuitry in the NFC electronics.

# Answer
> -1 votes
if your design allows , the NFC is available on a module rather than a shield allowing you to separate the GSM and NFC. like this on ebay

---
Tags: arduino-mega, gsm
---


title: Debugging modified BlinkWithoutDelay

text:
# Question
Title: Debugging modified BlinkWithoutDelay
I have some level of programming background, however never with Arduino's. I've just started hacking at the examples - I'm not even sure what language I'm currently writing. I presume it's C++.

Anyway, I figured I'd try out the pin 13 LED with the BlinkWithoutDelay example. I've got that running fine (which I was very excited about), however I've tried to modify it to blink out SOS in Morse code, but it doesn't appear to be working.

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

// Variables will change :
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change :
//unsigned long interval = 1000;           // interval at which to blink (milliseconds)

// Number of times to blink
const long blinkMax = 10;
// Counter for number of times blinked
unsigned long blinkCount = 0;

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

void loop()
{
  int loopCount = 0;
  // S O S
  int values[] = {1000, 1000, 1000, 200, 200, 200, 1000, 1000, 100};
  blink(values[loopCount]);
  loopCount = loopCount + 1;
}

void blink(int interval)
{
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(ledPin, ledState);
  }
}

```

As you can see, I've assigned the time values (1000 for long and 200 for short) to an array and had the loop function call my blink function each time. Every time it loops, it increments and goes to the next value.

I know it's able to pull values from the array fine, as I've tried manually modifying loopCount just before the blink() and it blinks at the specified timeout. I presume the loopCount increment is fine (I also did loopCount++; - no luck).

If someone could point me in the right direction, this would be great. Thanks!

# Answer
> 1 votes
Since it's blink without delay, the next loop will happen immediately. Not after the blink function is don't. So `loopCount` will increment continuously. You don't limit loopCount to 9, so it will after a few milliseconds try to access, e.g. `values[12]` which doesn't exist. (see @jfpoilpret's comment)

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

// Variables will change :
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated
int blinkValues[] = {1000, 1000, 1000, 200, 200, 200, 1000, 1000, 100};
int loopCount = 0;

// constants won't change :
//unsigned long interval = 1000;           // interval at which to blink (milliseconds)

// Number of times to blink
const long blinkMax = 10;
// Counter for number of times blinked
unsigned long blinkCount = 0;

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

void loop()
{
  blink();
}

void blink()
{
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= blinkValues[loopCount]) {
    previousMillis = currentMillis;
    loopCount = (loopCount + 1) % 9;
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(ledPin, ledState);
  }
}

```

Also note that the blink function will **toggle** the led, after the interval. So you need to add intervals, for how long the led should be off between flashes. But I leave that for you to figure out.

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


# Question
Title: Global Variable not able to be accessed in function?
I am trying to compile an Arduino program that takes analog input. However, when I declare multiple global variables, it often will not compile and because it throws an error that the variables aren't within scope of the functions within the program. I am not super familiar with Arduino IDE, but this doesn't programmatically make sense to me.

This is the program:

```
/*
*  By Hannah Perner-Wilson, www.plusea.at
*  Modified 3/30/2012 By Brian E Kaminski, www.AdvancerTechnologies.com
*
*  IMPORTANT!!:
*  Scroll down to set your serial port
*  Scroll down to set your thresholds
*/

import processing.serial.*;

// definition of window size
// you can change the size of the window as you like
// the thresholdGraph will be scaled to fit
// the optimal size for the thresholdGraph is 1000 x 400
int xWidth = 1200;
int yHeight = 750;

// xPos input array, using prefix
int[] xPosArr= {0,0,0,0,0,0};

//
int[] messageArr= {0,0,0,0,0,0};

// Arrays for threshholding
int[] threshMax= {0,0,0,0,0,0};
int[] threshMin= {0,0,0,0,0,0};

// variables for serial connection. portname and baudrate are user specific
Serial port1;

//Set your serial port here (look at list printed when you run the application once)
String V3 = Serial.list()[1];
String portname1 = V3;
int baudrate = 9600;

int prefix = 10001;
boolean myCatch = false;
String serialIN = "";
String serialINPUT = "";
String buffer = "";
int value = 0;

// ThresholdGraph draws grid and poti states
ThresholdGraph in;

void setup(){
  // set size and framerate
  size(xWidth, yHeight);
  frameRate(25);
  background(255);
  strokeWeight(5);
  stroke(0);
  smooth();
  strokeCap(ROUND);

  // establish serial port connection
  port1 = new Serial(this, portname1, baudrate);
  port1.bufferUntil('\n') ;
  println(Serial.list());  // print serial list

  // create DisplayItems object
  in = new ThresholdGraph();

  // THRESHOLD VALUES:
  // using the thresholdGraph you can determine the MIN and MAX values
  // of your sensors. Enter these here. They must lie between 0 and 1000.

    //MIN trashhold
    threshMin[0] = 20;   // one
    threshMin[1] = 20;   // two
    threshMin[2] = 20;   // three
    threshMin[3] = 20;   // four
    threshMin[4] = 20;   // five
    threshMin[5] = 20;   // six

    //MAX trashhold
    threshMax[0] = 600;   // one
    threshMax[1] = 600;   // two
    threshMax[2] = 600;   // three
    threshMax[3] = 600;   // four
    threshMax[4] = 600;   // five
    threshMax[5] = 600;   // six
}//end setup

// draw listens to serial port, draw
void draw(){

  // listen to serial port and trigger serial event
  while(port1.available() > 0){
        serialIN = port1.readStringUntil('\n');
        //println((int)float(serialIN));
        if(serialIN != "")
          serialEvent(serialIN);
        else
          Serial.println("found empty");
        }

  // threshold serial input
  threshHolding();

  // draw serial input
  in.update();
}//end draw()

```

The error that are being thrown are:

```
testproject.ino:100:17: error: 'threshHolding' was not declared in this scope
testproject.ino:103:3: error: 'in' was not declared in this scope
Error compiling.

```

# Answer
The problem is that this is not an Arduino Sketch, but a processing file which is noted by the initial import statement that is Java based. Because the Arduino IDE is not very sophisticated, it didn't shout out obvious errors such as `import type not defined` or even `ThresholdGraph` not defined.

To use this file it is necessary to use the following IDE: https://processing.org/reference/environment/
> 2 votes

---
Tags: programming, variables
---


# Question
Title: How exactly is voltage measured on an Arduino?
*How do the analog pins on an Arduino measure voltage?*

Do they either measure current and calculate the voltage with Ohm's law? (If so, why can we only read voltage and not current directly?)

Or do they compare the unknown input voltage with a known internal one? (If so, how does that work? What's the known voltage?)

# Answer
> 1 votes
Known voltage is usually provided by a diode or similar reference. The atmega328p chip has a separate aref pin so you can choose your own reference.

An ADC or analog to digital converter http://en.m.wikipedia.org/wiki/Analog-to-digital\_converter is a collection of comparators. A comparator is a logic gate that simply tells which of two inputs has more voltage. This aref voltage is divided evenly into 2^10 values (it's a 10 bit ADC). Then the incoming signal is compared against all of these and the largest comparator which triggers is the reading you get in your arduino code.

# Answer
> 1 votes
The Arduino uses a **10 bit *Analog to Digital Converter(ADC)***. A good ADC is made such that it has only as many comparators as is the resolution of the ADC (in BITS) . Therefore the Arduino should have only ten comparators.
More detailed:
Comparator Number Trigger voltage
1.(LSB).............................. (5/1024)V
2........................................ (5/512)V
3........................................(5/256)V
..........and so on till
4.(MSB)..............................(5/2)V
So, for a voltage of say 2.75V, you will get a value of 768(11000000 in Binary)

Update:If you choose to give and use a separate Ref Voltage to the Arduino, It replaces the 5V with the new ref voltage.
Update 2: Sometimes a single comparator may be used in exchange of all 10 comparators.i.e., it is used to trigger all the bits .But the voltage at which each bit is triggered remains same.

# Answer
> 0 votes
The Arduino uses a analog-to-digital converter. For instance on the Arduino Uno there is a 10-bit ADC. Therefore the resolution is 2^10 bits which is 1024 different representations. As the Uno runs at 5V, each step represents 4.9mV.

The actual inner workings of the ADC can be quite complex and I don't exactly know which specific type it uses, but there can be many ways. One example is measuring time to discharge of a known capacitor. Another is comparing the voltage to the running voltage and using a counter.

# Answer
> 0 votes
I'm not sure what the answer is or why no one has addressed the second part of your question. To calculate current you need to know voltage and resistance (I=E/R). The ADC is giving you the voltage but I don't know what value to use for resistance in order to calculate the current. I do better with digital electronics but I suspect you might be able to use a resistor divider network to measure the voltage drop across a known resistor to measure current but do not take my word for this.

---
Tags: analogread, electronics
---


title: Exceed AREF voltage

text:
# Question
Title: Exceed AREF voltage
Let's say that I use a 5V Arduino board, and I set AREF to 3V, thus 0-3V equals to 0-1023 of the analog inputs.

If I exceed the AREF voltage, powering an analog pin with 4V, could that damage the analog input pin? If not, what would be the reading?

Thank you.

# Answer
The reading would saturate at 1023 when the voltage on the input pin exceeds AREF.

The datasheet (for the ATmega328P) states as absolute maximum rating for the "Voltage on any Pin except -RESET with respect to Ground" VCC \+ 0.5 V. So applying 4 V to AREF for a 5 V Arduino board should not (necessarily) damage the ATmega. (But you also won't be able to extend the 10-bit resolution range, if that is what you're after...)

In short, choose the reference voltage above the maximum expected voltage.
> 2 votes

---
Tags: power
---


title: 16 bit register addressing through i2c

text:
# Question
Title: 16 bit register addressing through i2c
Note: I'm using just the atmega chip and atmel studio. Not exactly a full arduino.

I have been using the atmega168 with a MAX17040 fuel gauge in a project. The I2C interface between the atmel and the fuel gauge is working fine and I am able to read data from the fuel gauge.

Due to the power requirement of the project, the fuel gauge requires its compensation value to be adjusted. This is a 16 bit register, so according to the manufacturer I have to write 0x1234 across address 0x0C and 0X0D in one go. Otherwise the values are discarded.

All the datasheet and online forums talk about 8-bit I2C addressing (which I have working), but instruction on addressing 16 bit register is limited. I was wondering if anyone can help me on this.

My basic code is pasted below. The I2C\_start takes care of TWCR, TWDR, etc. It could be something to do with Repated\_Start, but not sure.

```
uint8_t I2C_write_register(uint8_t device, uint8_t address, uint8_t value)
{
    device <<= 1;

    uint8_t ret = I2C_start(device | TW_WRITE);
    if (ret)
        return 1;

    if (!ret)
        ret = I2C_write(address);
    if (!ret)
        ret = I2C_write(value);
    I2C_stop();

    return ret;
}

uint8_t I2C_start(uint8_t address){
    // reset TWI control register
    TWCR = 0;
    // transmit START condition
    TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);
    // wait for end of transmission
    while( !(TWCR & _BV(TWINT)) );

    // check if the start condition was successfully transmitted
    if((TWSR & 0xF8) != TW_START){ return 1; }

    // load slave address into data register
    TWDR = address;
    // start transmission of address
    TWCR = _BV(TWINT) | _BV(TWEN)|_BV(TWEA); //|_BV(TWEA) added
    // wait for end of transmission
    while( !(TWCR & _BV(TWINT)) );

    // check if the device has acknowledged the READ / WRITE mode
    uint8_t twst = TW_STATUS & 0xF8;
    if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1;

    return 0;
}

```

# Answer
Ahh, was just able to solve it. Essentially, do not use TW\_REPEATED\_START. Just keep sending data 8 bit at a time. 1 bit at the beginning of each 8 bit will be lost, so make sure you shift them first.

Wire library uses a very similar concept for use with arduino.

```
uint8_t I2C_write_register(uint8_t device, uint8_t address, uint8_t value, uint8_t value)
{
    device <<= 1;

    uint8_t ret = I2C_start(device | TW_WRITE);
    if (ret)
        return 1;

    if (!ret)
        ret = I2C_write(address);
    if (!ret)
        ret = I2C_write(value);
    if (!ret)
        ret = I2C_write(value2);
    I2C_stop();

    return ret;
}

```
> 1 votes

---
Tags: i2c, atmega328, atmel-studio
---


# Question
Title: The IDE says my (brand new) Arduino UNO is on COM 1
I recently bought an Arduino Uno and installed everything necessary. I tried it on both USB ports on my computer. However, the Ports menu only shows COM1. There is a line on the bottom of the IDE which says Arduino Uno on COM1.

Any program I try fails to upload to the board. When I tried the Blink example, the following error message appeared:

```
Arduino: 1.6.3 (Windows 7), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for
local variables. Maximum is 2,048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x43

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x43

```

and so on. Until,

```
This report would have more information with
"Show verbose output during compilation" enabled in File > Preferences.

```

I have a Windows 7 64 bit desktop.

Any help will be appreciated.

# Answer
> 0 votes
Here are a few troubleshooting tips:

1. First check if the board is listed as Arduino Uno in the IDE by going to Tools --\> Board
2. Check this site.
3. Also, try reinstalling the driver.
4. Check your cable.
5. As a last resort you can try re uploading the bootloader.

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


# Question
Title: Problem programming Mini Pro via Arduino as ISP
I just picked up a pair of Arduino Mini Pro 5v clone boards (Inland, sold at Microcenter, currently $4 USD) and I wanted to use my Uno as an ISP like I've done with ATmega328 and ATtiny85 chips before. I've programmed the Uno with the instructions at the ArduinoISP tutorial page and I've connected up the Uno to the Mini Pro using the instructions at this page. I cannot get the Arduino IDE or avrdude from the command line to successfully program these boards no matter what I try. Except that I can use the Arduino IDE to burn a new bootloader to the Mini Pro.

I've connected up the status LEDs as well (pins 7, 8 and 9), and I can see that the programmer has an error condition (pin 8) when I attempt to program anything besides the bootloader.

Here is my avrdude command line where I tried to set the fuses on the Mini Pro:

```
avrdude -P /dev/tty.usbmodema0121 -b 57600 -c avrisp -p atmega328p -U lfuse:w:0xff:m -U hfuse:w:0xdb:m -U efuse:w:0xfd:m

```

I get the following back from avrdude:

```
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

avrdude done.  Thank you.

```

I've not had any problems with using pretty much this exact same setup, but with a ATmega328 or ATtiny85 chip on a breadboard with avrdude in the past, so I'm at a loss as to what is happening here.

I've also taken a look at the ArduinoISP code, and I'm not really sure what the resp=0x1c is. I don't see a 0x1c value defined in the STK Definitions section of the code, so I'm not sure what might be causing this.

Any pointers here would be appreciated. And yes, I do know that I can use the Uno board with the ATmega328 chip pulled to use as a programmer as well. But I want to be able to overwrite the bootloader area with my own code like I can with a regular ATmega328 chip.

Thanks!

# Answer
After poking around for a bit more, it turns out my problem was the baud rate. I could make it work by setting it to 19200, just a little slower. Alternatively, you can modify the ArduinoISP sketch to enable higher baud rates. I used this post to enable 115200 baud and I was able to successfully use avrdude at the higher rates.

Not sure how I missed this before, but it's an easy to solve at least.
> 7 votes

---
Tags: arduino-pro-mini, avrdude, isp, clones, arduinoisp
---


title: Error in Compiling

text:
# Question
Title: Error in Compiling
The error shown is

```
C:\Users\SIDDHA~1\AppData\Local\Temp\build3397782103973366883.tmp/core.a(Tone.cpp.o): In function `__vector_7':
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Tone.cpp:536: multiple definition of `__vector_7'
C:\Users\SIDDHA~1\AppData\Local\Temp\build3397782103973366883.tmp\IRremote\IRremote.cpp.o:C:\Users\Siddharth Yadav\Documents\Arduino\libraries\IRremote/IRremote.cpp:361: first defined here
collect2.exe: error: ld returned 1 exit status

```

Why is this happening?

The code is:

```
#include <IRremote.h>

const int echo = 7;// connected to ultrasonic sensor's echo
const int trig = 8;// connected to ultrasonic sensor's trig
const int Right1 = 10;
const int Right2 = 11;
const int Left1 = 12;
const int Left2 = 9;// change this to any other pin; except pin 13
const int buzzer = 5;
const int rightIR = 3;// change here
const int leftIR = 2;// change here
int RECV_PIN = 4;
const int forward = 51;
const int backward = 36;
const int left = 19;
const int right = 0;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  pinMode(buzzer, OUTPUT);
  pinMode(echo, INPUT_PULLUP);
  pinMode(rightIR, INPUT_PULLUP);
  pinMode(leftIR, INPUT_PULLUP);
  pinMode(trig, OUTPUT);
  pinMode(Right1, OUTPUT);
  pinMode(Right2, OUTPUT);
  pinMode(Left1, OUTPUT);
  pinMode(Left2, OUTPUT);
  sing(1);
  Serial.begin(9600);
 irrecv.enableIRIn(); // Start the receiver

}

void loop() {
  digitalWrite(13, HIGH);
  if (calcDistance() > 30 && !isRight() && !isLeft())
  {
    if (irrecv.decode(&results))
    {
      Serial.println(results.value, HEX);
      irrecv.resume(); // Receive the next value
      delay(50);
    }
    else {
      moveForward();
    }

  }
  else
  {
    delay(10);
    int dist = calcDistance();
    if (dist < 30 && isLeft() && isRight())
    {
      Serial.println("Moving backward");
      tone(buzzer, 4699, 10);
      moveBackward();
      delay(1000);
    }
    else if (isLeft())
    {
      turnRight();
      digitalWrite(13, LOW);
      tone(buzzer, 104, 10);
      Serial.println("Turning Right");
    }
    else if (isRight())
    {
      turnLeft();
      digitalWrite(13, LOW);
      delay(300);
      tone(buzzer, 880, 10);
      Serial.println("Turning LEft");
    }
    else if (dist < 30)
    {
      turnRight();
      digitalWrite(13, LOW);
      tone(buzzer,  104 , 10);
      Serial.println("Turning Right");
    }

  }

  delay(20);
}

```

# Answer
> 1 votes
As the error message says you have multiple definitions of \__vector\_7 which is defined in: IRemote.cpp:361 and Tone.cpp:536

Tone.cpp is arduino standart lib. If IRemote is a lib of yours then you should edit the cpp file and change the symbol to sth else.

# Answer
> 1 votes
The IRemote.cpp and Tone.cpp would be using the same interrupt vector. I believe it's `ISR(TIMER5_COMPA_vect) {`

* You could. I don't think it's the best solution, but go to Tone.cpp and comment the `ISR(TIMER5_COMPA_vect) {` like `/*ISR(TIMER5_COMPA_vect)*/void XunusedX(void) {`. And be sure to never use any function from ...
* You could also try to find a way on how not to invoke Tone.h with core.a. `include <Tone.h>` could be replaced with `//include <Tone.h>`
* You could use another timer in `IRRemote.h`

---
Tags: programming, remote-control
---


# Question
Title: Mechanical requirements for Arduino compatibility
If I want to design an Arduino-compatible board I guess I'll have to use the same outline, and connector positions to fit existing enclosures. (Beats me why they didn't choose a simple rectangular board, which would have been cheaper.) But I wonder if the ICSP header's position is standardized. Some enclosures have a hole above it, but many don't. Can I move the ICSP header to another position?

---

(Can somebody add a "compatibility" tag? Thanks. Also, neither "mechanical" nor "board" nor "layout" seem to exist as tags. Feel free to improve my generic tagging.)
The "shield" tag was suggested, but this isn't about shields, it's about the ICSP header.

# Answer
> 1 votes
Depends on what you define as "Arduino compatible".

My "Arduino Nano" is 'Compatible' but a whole other design.

Or well, it already separates here. "Software compatible" working with the Arduino IDE and/or Libraries. In general, any board with ATMega 328P / USB or ICSP / Bootloader could be considered compatible.

But, however, for an "Arduino clone" being "Hardware compatible" you could also look at:

* Pin placement (Thus being compatible with shields).
* Using the same FTDI chip, thus being directly compatible with arduino drivers (not sure)
* Using "exactly" same electronic specifications.
* Size and/or shape or even weight of the board.

Strictly, moving the ICSP header will make it 'incompatible' for some shields. But, well, for most shields it won't be a problem. For casings that have an opening for the ICSP header it'll mostly just look funny. By replacing the ICSP header it might touch components of other shields/casings and thus be not compatible with it.

---

(update) The website and file below are from the arduino site and could thus be considered to be the 'standard' as it's set by arduino. You can however make your board how you want it and compatible with what you want. But changes will often make it incompatible with (some) shields/adapters.

The arduino website with specifications on the board: http://www.arduino.cc/en/Main/ArduinoBoardUno

EAGLE files: http://arduino.cc/en/uploads/Main/arduino\_Uno\_Rev3-02-TH.zip

---
Tags: arduino-uno, mechanical
---


title: Arduino Watchdog Timer

text:
# Question
Title: Arduino Watchdog Timer
I want to work with interrupts and heard that the watchdog timer is effective way to deal with them. I haven't been able to find a good tutorial on them though and was wondering if someone could head me in the right direction or give me a couple tips and an example.

# Answer
> 0 votes
For the Uno, you can set an interrupt on digital pins 2 and 3. Check out http://www.arduino.cc/en/Reference/attachInterrupt for more details.

Here is the example code from that page:

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

void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}

void loop()
{
  digitalWrite(pin, state);
}

void blink()
{
  state = !state;
}

```

In this case, blink() will be called anytime pin 0 changes state. If you only want the rising or falling edge, change the call to attachInterrupt to say RISING or FALLING instead of CHANGE.

# Answer
> 1 votes
Since you talk about the watchdog I presume you want timer interrupts. (There are also I/O interrupts, for instance when the level of a pin changes state.) Like Russell McMahon says the watchdog is not a good source. The ATmega has several timers (8-bit and 16-bit) which serve your exact purpose. Let's view some example code:

```
// timer interrupts
// adapted from code by Amanda Ghassaei
// June 2012
// http://www.instructables.com/id/Arduino-Timer-Interrupts/

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
*/

// timer setup for timer0, timer1, and timer2.
// For arduino uno or any board with ATMEL 328/168.. diecimila,
// duemilanove, lilypad, nano, mini...

// this code will enable all three arduino timer interrupts.
// timer0 will interrupt at 2kHz
// timer1 will interrupt at 1Hz
// timer2 will interrupt at 10kHz

// storage variables
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;

void setup() {

  // set pins as outputs
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);

  cli(); // stop interrupts

  // set timer0 interrupt at 2kHz
  TCCR0A = 0; // set entire TCCR2A register to 0
  TCCR0B = 0; // same for TCCR2B
  TCNT0  = 0; // initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124; // = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

  // set timer1 interrupt at 1Hz
  TCCR1A = 0; // set entire TCCR1A register to 0
  TCCR1B = 0; // same for TCCR1B
  TCNT1  = 0; // initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624; // = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  // set timer2 interrupt at 10kHz
  TCCR2A = 0; // set entire TCCR2A register to 0
  TCCR2B = 0; // same for TCCR2B
  TCNT2  = 0; // initialize counter value to 0
  // set compare match register for 8khz increments
  OCR2A = 199;// = (16*10^6) / (10000*8) - 1 (must be <256)
  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS21 bit for 8 prescaler
  TCCR2B |= (1 << CS21);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

  sei(); // enable interrupts

} // end setup

ISR(TIMER0_COMPA_vect){ // timer0 interrupt 2kHz toggles pin 8
  // generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle0 = HIGH - toggle0;
  digitalWrite(8, toggle0);
}

ISR(TIMER1_COMPA_vect) { // timer1 interrupt 1Hz toggles pin 13 (LED)
  // generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle1 = HIGH - toggle1;
  digitalWrite(13, toggle1);
}

ISR(TIMER2_COMPA_vect) { // timer1 interrupt 10kHz toggles pin 9
  // generates pulse wave of frequency 10kHz/2 = 5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle2 = HIGH - toggle2;
  digitalWrite(9, toggle2);
}

void loop() {
  // do other things here
}

```

This sets up 3 different timers: one at 500 µs, one at 1 s, one at 100 µs. For the details about each timer, look up the registers in the datasheet.
With each timer goes a timer interrupt service routine (ISR). These perform the action required when an interrupt occurs. It's a good practice to exit an ISR as quickly as possible. Only do the things which are really time-critical, but for the rest set a flag to indicate that the interrupt occurred. Then in the main loop you continuously check that flag, and when it is set, perform the necessary actions. Don't forget to clear the flag when you're done.

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


title: Simulating touchscreen input using PWM

text:
# Question
Title: Simulating touchscreen input using PWM
I'm porting a project from a teensy microcontroller to the arduino. Essentially the project uses a microcontroller to simulate touchscreen input for the Nintendo 3DS console. I am doing this by unplugging the touchscreen digitizer of my Nintendo 3DS and putting my arduino in its place. See the link below for the original teensy code and schematics that I'm trying to modify. (The oscilloscope picture below is also credit of author of the teensy code) https://github.com/dekuNukem/3xtDS

**This is a fairly generic touchscreen I'm trying to simulate input for, so I'm not sure what's going wrong.** I am not sure if my schematic has a problem, or if the Arduino's PWM frequency limitation is the problem. The teensy code was setup to output at 90khz, while the highest I can possibly set my arduino is around 31khz. I believe this should be good *enough* because I believe the Nintendo 3DS only samples at around 100 microsecond intervals.

**What I have done:**

* I'm connecting two of my arduino pins to the X+ and Y+ pins where the Nintendo touchscreen digitizer used to be.
* I have used a voltage divider to change the arduino's output voltage from 5v to 1.8v, which is the VCC of the nintendo device.
* I have used a 0.22uf capacitor and 1k resistor as a DAC to change the PWM output to analog.

**I tried troubleshooting by:**

* using 68 & 120 ohm resistors in my voltage divider for smoother analog PWM response, instead of 68k & 120k resistors
* adding a 1N914 diode between the capacitor and ground (since I am using ceramic capacitors, which are bidirectional)
* eliminating the `while(analogRead(senseY) < 46)` line in my code and instead using a static delay of 100 microseconds

**Touchscreen press I want to simulate (Yellow is Y+, blue is X+):**

**My Schematic:**

**Teensy code ported to arduino:**

```
// I've included the setPwmFrequency() function listed on the arduino site,
// but I'm omitting it here for clarity reasons.

// The main change between the Teensy and arduino is that the teensy uses
// software to lower the PWM voltage from teensy's native 3.3v down to the
// nintendo's 1.8v, while I have instead used a voltage divider on the PWM
// output of the arduino.

// X+ pin of touchscreen.
int touchX = 9;

// Y+ pin of touchscreen.
int touchY = 10;

// Pin to monitor arduino's output of Y+
int senseY = 11;

void setup() {
  // -Change pins 9 and 10 to have 31,250 hz PWM frequency. This is the
  // highest I can set it. Teensy originally set their frequency to 90khz.
  // My difference in frequencies MIGHT be the cause of my problems.
  // I picked pins 9 and 10 because they won't affect timing for millis()
  // and delay.
  setPwmFrequency(9, 1);
  setPwmFrequency(10, 1);

  // Original teensy code set analog write resolution to 9bits.
  // This was necessary because the nintendo touchscreen is 320x240, which is greater than 255 for an 8bit resolution.
  // However, I don't mind this minor accuracy loss! arduino's analog resolution is accurate enough for me.
  pinMode(touchX, OUTPUT);
  pinMode(touchY, OUTPUT);
  analogWrite(touchX, 0);
  disable_touch_screen();
}

void touch_screen_click(unsigned int x, unsigned int y, unsigned int duration_ms) {
  // Calculate PWM value to write  based on the xy touchscreen coordinates we want.
  unsigned int x_potential = ((double)x / 320) * 255;
  unsigned int y_potential = ((double)y / 240) * 255;

  // Start outputting the x value.
  analogWrite(touchX, x_potential);

  // Pull Y+ to ground.
  enable_touch_screen();

  unsigned int start = millis();

  // Keep touch screen pressed for tap duration.
  while(millis() - start < duration_ms) {
    // wait until Y+ pin is in output mode
    // original teensy code checked for 512, which was half of the max value 1024.
    // we're outputting 1.8v with our circuit, but reading analog at 5v
    // so the value we check for is half of this max value: 1.8/5*255=92
    // I COULD have used arduino's Aref, but math is faster than soldering
    while(analogRead(senseY) < 46)
    delayMicroseconds(490);

    // now Y+ pin is in output mode
    analogWrite(touchY, y_potential);
    delayMicroseconds(180);

    // pull Y+ down again to keep interrupt going
    enable_touch_screen();
  }
  disable_touch_screen();
  analogWrite(touchX, 0);
  delay(50);
}

void disable_touch_screen() {
  analogWrite(touchY, 255);
}

// pull Y+ pin low to initialize 3DS's touch interrupt
void enable_touch_screen() {
  analogWrite(touchY, 0);
}

// the loop routine runs over and over again forever:
void loop() {

delay(800);
// tap at 150x150 for 100ms.
touch_screen_click(150, 150, 100);

delay(800);

// tap at 50x50 for 100ms.
touch_screen_click(50, 50, 100);
}

```

# Answer
To confirm your analysis that the issue is caused by the lower pwm frequency on the Arduino, did you try reproducing the problem with the teensy? Just divide by 3 the PWM frequency on the Teensy and see if you get the same problems that you are experiencing with the Arduino.
> 1 votes

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


# Question
Title: How to control Arduino robot wirelessly?
I have a few potentiometers connected to analog inputs in an Arduino UNO. These are then processed and then the servo motors start moving to move the bot. I would like to keep the motors with the uno and send signals from the pots to the uno. I do not want to use a laptop or another arduino as the remote control. However.. XBEE and other related stuff will do... Thanks

Edit- The wireless solution has to cover a long range preferrably 1 mile.(I dont think I will get any that will cover a mile but I'll give it a try.)

Edit 2- I have 8 servos and 4 potentiometer. I don't necessarily need an xbee. However it may be used.

# Answer
A 13 year old programming an embedded device? Good luck to you, if you conquer it you will be years ahead of your age group.

What you need to understand are the fundamentals; how can you transmit a 'pot' over an XBee? That is an electronics question, start there. You will find that another arduino or laptop is probably required. The XBee itself requires some sort of host adapter, and it might as well be another Arduino since something has to electronically read the 'pots'.

Then you need to develop your own protocol for signals sent between the 2 Arduino (over XBee or on a serial wire , it is the same). There are many already out there, but they assume you know the basics before you use them (eg firmata). This is the basics.

The fact that your google results showed nothing similar is probably a good indication it can not be done as you had hoped.

update: I like @gerben comment, but even as an advanced person, I would find it challenging.
> 1 votes

# Answer
You can use so many methods to achieve it,as you are a newbie.i would prefer bluetooth and an android app.use bluetooth hc-05 module and use an android app to control.use this app and send string and control arduino. https://play.google.com/store/apps/details?id=mobi.dzs.android.BLE\_SPP\_PRO&hl=en
> 1 votes

# Answer
You need to find a way to do this without having individual wireless communication from each pot. There are boards that can communicate wirelessly that are small, however, most of these are around the size of a quarter developed by an electrical engineer. This presents two problems, first the wireless modules will be too big, second, you will need to do a lot of work before you have the experience necessary to build something like this. I recommend changing a design decision.

Thus, in order to help you further we will need to know more information about your setup.
> 0 votes

---
Tags: arduino-uno, robotics, remote-control
---


# Question
Title: Converting Arduino LCD Programs to Serial I2C LCD code
I just got a Serial LCD and wanted to test it out with a game. I found this site with game conversions and wanted to use this game. However since my serial LCD use the LiquidCrystalic2 library the code in its current state won't work. Is there a simple method of converting or porting liquidcrystal to LiquidCrystalic2? Or if someone knows of a simple game in regards to hardware that uses a serial lcd and could direct me to a link that would be great.

# Answer
i got my lcd working on I2C following the steps in this link http://forum.arduino.cc/index.php?topic=128635.0
> 0 votes

---
Tags: lcd, arduino-nano
---


# Question
Title: Why does the pin 2 of arduino Mega stay always HIGH?
Without declaring the pin 2 as INPUT or OUTPUT, it remains constantly HIGH. Can anyone explain why is it so?

# Answer
Pin 2 connects to the controller's PE4, which is a GPIO pin, which can also be used for PWM. You should be able to use it either as input or output, and both high and low. It could be that setup initializes it as output high, while you would usually have uninitialized pins as input.

Have you tried to make it low, or make it input?

```
digitalWrite(2, LOW);

```

should make it low, while

```
pinMode(2, INPUT);
int pin2Status = digitalRead(2);
digitalWrite(13, pin2Status);

```

will copy the status of pin 2 to the on-board LED.
> 2 votes

---
Tags: arduino-mega
---


# Question
Title: How to interface DS1801 digital resistor with Arduino DUE SPI interface? What clock rate so use?
I am trying to program a digital resistor and set it's wiper resistance. The general circuit looks a little like this where "pot" represents the Maxim DS1801 digital resistor and DUE is, of-course the 3.3v Arduino DUE.

```
POT       DUE
CLk ----> SCK
D    ----> MOSI
RST ----> CS (ChipSelect) (PIN10)

```

Now so far, I have sucessfully been able to interface with the DS1801, but I am having issues determining how to properly set the wiper resistance values. The DS1801 datasheet says the it accepts a 16bit input and from application example online it looks like the values range from 0 to 64. Here is my code:

```
// include the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;
int mute = 64;
int loud = 63;
int soft = 0;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode (slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.setBitOrder(LSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);
  SPI.begin();
  delay(10);
   digitalPotWrite(mute, mute);
}

void loop() {

  // Raise the volume from off to loud
for(int i = 0; i <= 63; i++){
  digitalPotWrite(i, i);
  delay(5);
    }
  }

void digitalPotWrite(int left, int right) {
  // take the SS pin low to select the chip:
  digitalWrite(slaveSelectPin, HIGH);
  //  send in the address and value via SPI:
  SPI.transfer(left);
  SPI.transfer(right);
  // take the SS pin high to de-select the chip:
  digitalWrite(slaveSelectPin, LOW);
}

```

I THINK my issue lies with setting the clock rate for the DS1801. The data sheet say the chip runs at 10MHz which is why I wrote

```
SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);

```

to divide the 84MHz default speed down to 10MHz.

Anyone have suggestions on why my code is not working??? At the moment, I have LED's connected to chip with series resistors to limit current below 2mA. The resistors just blink randomly with the code posted above.

# Answer
> 1 votes
Well, it turns out that apparently my issue was not having the AGND pin hooked up. In addition to that, I was trying to switch the wiper resistance value too quickly. By putting at least a 10ms delay between calls, it works much better.

Also, it does seem to work even at 10MHz just fine...

# Answer
> 1 votes
There is ***no way in hell*** you're going to get a 10MHz signal down that line. Shorten it to 3 inches total *maximum* and reduce the clock rate to 2MHz or lower. It is possible to get a 10MHz signal through, but you'd need to switch to twisted pair wiring and proper termination to even begin to have a chance to get it to work.

---
Tags: arduino-due, spi, digital, resistor
---


title: Arduino Robot Chasis

text:
# Question
Title: Arduino Robot Chasis
I am looking into building a robot with my Arduino Nano but I don't want to shell out more then 50 bucks. Does anyone have any suggestions for a four wheel robot chassis at this price that I could use to make my robot mobile?

# Answer
There's plenty of options on ebay, you will have to add a DC motor driver and optionally, sensors, but these are a good starting point.
> 1 votes

---
Tags: arduino-nano, robotics
---