title: Arduino IDE has no shortcut in openSUSE

text:
# Question
Title: Arduino IDE has no shortcut in openSUSE
I just installed the Arduino IDE in openSUSE 13.1. I am able to open the application using the run dialogue, so I know it has installed. However, there is no way to open the IDE from any application launcher. I have tried both the Kickoff and Lancelot applciation managers. I have also tried to uninstall and re-install the IDE, both through the 1-click on the Arduino website as well as through the command line.

Does anyone know why I am unable to launch the application from the launcher? Thanks in advanced for any help!

# Answer
I had the same problem and this seems to work. If you right click on the Kickoff Application launcher and open 'edit applications' with KDE Menu Editor, you can 'add new item' where you want and give it a name (ArduinoIDE) and then just put arduino (small case) in the 'command' box, and shut down KDE Menu Editor, it should appear in the menu where ever you placed it. At least it did for me.
> 1 votes

---
Tags: arduino-ide, linux
---


# Question
Title: Is there some sample code for operating a servo with an Adafruit Motor Shield?
I have an Adaruit Motor Shield v2, and a Tower Pro SG92R micro servo. I've got it setup so the shield works with my Arduino Uno, and I've successfully tested using other types of motors on the shield. I could not find any sample code for working with a servomotor though. The shield has two dedicated spots for a servo (labeled "Servo 1" and "Servo 2"). I'm planning to use wall wart transformer to power the motor separately from the Arduino. Any pointers/links to documentation/sample code would be appreciated.

# Answer
> 3 votes
On the Motor shield the servo headers are directly connected to pins 9 and 10 (I think 9 is servo 2 and 10 is servo 1). So you can use the standard servo examples using pins 9 and 10.

If you need to power the servos with an external power supply you must cut a trace on the back of the board -- the silk screen tells you where to cut. Then you need to connect power to the "Opt Servo" input.

The power to the servos is not changed by the power jumper used for the DC/stepper motors.

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


title: Arduino IDE crashes without any warning

text:
# Question
Title: Arduino IDE crashes without any warning
I'm a beginner in Arduino. I just installed Arduino IDE (arduino-1.0.5-r2-windows) but when I try to run its not responding and crashes after few minutes. I tried re-installing it and removing the temporary files but none of those helped.

Can anyone tell me what causes this problem and how to debug it?

# Answer
> 1 votes
Installing Arduino 1.5.6 solved the issue.

---
Tags: arduino-ide
---


# Question
Title: Need some help with controlling a fan through PWM
So lately I've been trying to control the speed of a 120mm 4-pin computer fan using PWM. This is what I've got so far, with the part above void loop() being from this thread

```
// Definition of Arduino type
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define  IS_MEGA  (1)
#define  IS_UNO   (0)
#else
#define  IS_MEGA  (0)
#define  IS_UNO   (1)
#endif

// Analog output (i.e PWM) pins. These must be chosen so that we can change the PWM frequency without affecting the millis()
// function or the MsTimer2 library. So don't use timer/counter 1 or 2. See comment in setup() function.
// THESE PIN NUMBERS MUST NOT BE CHANGED UNLESS THE CODE IN setup(), setTransistorFanSpeed() AND setDiodeFanSpeed() IS CHANGED TO MATCH!
#if IS_UNO
// On the Uno we can only use the OC1B pin, so these pin numbers are both 10
const int transistorFanPin = 10;     // OC1B
const int diodeFanPin = 10;          // OC1B
#else
// On the Mega we use OC1B and OC1C
const int transistorFanPin = 12;     // OC1B
const int diodeFanPin = 13;          // OC1C
#endif

// Definitions for PWM fan control
const unsigned char maxFanSpeed = 80;   // this is calculated as 16MHz divided by 8 (prescaler), divided by 25KHz (target PWM frequency from Intel specification)

void setup()
{
  // Set up the PWM pins for a PWM frequency close to the recommended 25KHz for the Intel fan spec.
  // We can't get this frequency using the default TOP count of 255, so we have to use a custom TOP value.

#if IS_UNO

  // Only timer/counter 1 is free because TC0 is used for system timekeeping (i.e. millis() function),
  // and TC2 is used for our 1-millisecond tick. TC1 controls the PWM on Arduino pins 9 and 10.
  // However, we can only get PWM on pin 10 (controlled by OCR1B) because we are using OCR1A to define the TOP value.
  // Using a prescaler of 8 and a TOP value of 80 gives us a frequency of 16000/(8 * 80) = 25KHz exactly.
  TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << WGM11) | (1 << WGM10);  // OC1A (pin 9) disconnected, OC1B (pin 10) = inverted fast PWM
 #ifdef FAN_AUDIO_TEST
  // test code to get 440Hz output (= concert A) to test the logic
  OCR1AH = 0;
  OCR1BL = 71;  // 50% duty cycle
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);  // TOP = OCRA, prescaler = 256

  OCR1AL = 141; // TOP = 141, 16000000 / (256 * 142) = 440.014
  OCR1BH = 0;
 #else
  OCR1AH = 79;
  OCR1AL = 0;  // TOP = 79
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR0A, prescaler = 8

  OCR1BH = 0;
  OCR1BL = maxFanSpeed;  // max fan speed (i.e. pin 5 initially low all the time)
 #endif

  TCNT1H = 0;
  TCNT1L = 0;
#else

  // On the Mega we use TC1 and OCR1B, OCR1C
  TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << COM1C1) | (1 << COM1C1) | (1 << WGM11) | (1 << WGM10);  // OC1A disconnected, OC1B = OC1C inverted fast PWM
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR1A, prescaler = 8
  TCCR1C = 0;
  OCR1AH = 0;
  OCR1AL = 79;  // TOP = 79

  OCR1BH = 0;
  OCR1BL = maxFanSpeed;
  OCR1CH = 0;
  OCR1CL = maxFanSpeed;

  TCNT1H = 0;
  TCNT1L = 0;
#endif

  // We have to enable the ports as outputs before PWM will work.
  pinMode(transistorFanPin, OUTPUT);
  pinMode(diodeFanPin, OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);
}

// Set the transistor fan speed, where 0 <= fanSpeed <= maxFanSpeed
void setTransistorFanSpeed(unsigned char fanSpeed)
{
  OCR1BH = 0;
  OCR1BL = fanSpeed;
}

// Set the diode fan speed, where 0 <= fanSpeed <= maxFanSpeed
void setDiodeFanSpeed(unsigned char fanSpeed)
{
#if IS_UNO
  OCR1BH = 0;
  OCR1BL = fanSpeed;
#else
  OCR1CH = 0;
  OCR1CL = fanSpeed;
#endif
}

void loop() {
  if (analogRead(A0) >= 800) {
    setTransistorFanSpeed(80);
    Serial.println("HIGH");
    Serial.println(analogRead(A5));
  } else {
    setTransistorFanSpeed(0);
    Serial.println("LOW");
    Serial.println(analogRead(A5));
  }
  delay(100);
  Serial.println("I'm running.");
}

```

In the serial monitor I'm getting the output I'm expecting ("HIGH" and 1023 when I've bridged the arduinos 5V pin to A0), but the signal doesn't seem to have any effect on the fan at all. In the thread linked above there's talk about this being an inverted fast PWM signal, and that it's assumed I'm using an opto isolator. Could this be why the signal doesn't have an effect on the fan? If anyone out there has any experience on this and are able to help me, that would be greatly appreciated.. :)

# Answer
You need to connect the ground of the fan (/12volt power-supply) to the ground of the Arduino. If you don't connect the grounds, there is no path for electrons to flow.
> 3 votes

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


# Question
Title: What is the frequency of PWM output on Arduino
What frequency do Arduinos use for normal PWM when you use analogWrite()?

And is it different for different Arduino model? I'm interested specifically in the Mega 2560, but also want to know if it's consistent between models.

I've seen a passing references to the Arduino using 500 Hz, which seems really slow.

# Answer
> 36 votes
The PWM signal is generated by timers on the AVR chips. Each timer can generate a PWM signal on two or three different pins. Each pin can have it's own duty cycle, but they share the PWM frequency. You can change the frequency of the PWM by changing the clock source for the timers. By default they use the CPU clock divided by 64, ie. they have their prescaler set to 64 by Arduino initialization code. To confuse things more there are two different PWM modes: fast PWM and phase correct PWM. In fast PWM the timer counts to 255, then overflows and starts over from 0 (256 different states). In phase correct PWM the timer counts to 255, then changes direction and counts downwards to zero, changes direction and so on (510 different states).

The Arduino Mega has 5 timers, timer0 - timer4. Because timer0 is also used for the millis and micros functions it uses fast PWM, whereas the other timers are configured for phase correct PWM. This results in different frequencies on different pins:

* Pin 4 and 13, controlled by timer0:
16 Mhz / 64 / 256 = 976.56 Hz
* Other PWM pins, controlled by timer1-4:
16 Mhz / 64 / 510 = 490.20 Hz

The calculation is: Clock / Prescaler / PWM mode number of states

The situation is the same for all other Arduino boards I know of, except they have less timers that connect to different pins.

You can change the PWM frequency by changing the timer prescaler. See this page: http://playground.arduino.cc/Main/TimerPWMCheatsheet

It is also possible to make the timers count to a different value than 255. On the 8 bit timers you will loose an output pin, but on the 16 bit timers you can use the Input Capture Register to define a TOP value. The input capture functionality is a feature rarely used in the Arduino community so you likely won't miss it.

The Arduino libraries only allow you to use 8 bit resolution, even on the 16 bit timers. If you want the higher resolution, you will have to write your own analogWrite, or use a library made for the purpose. On the Arduino Mega timer0 and timer2 are 8 bit, while the rest are 16 bit.

By changing the mode of the 16 bit timers to make use of the full resolution, in combination with changing the prescaler and the TOP value, you can achieve a very wide range of PWM frequencies.

The maximum frequency you can achieve is clock / 4, by setting the prescaler to 1 and TOP to 3 in fast PWM mode - a lower value isn't allowed. This will give you a 4 MHz PWM with 2 bit resolution. It can be on 0%, 25%, 50%, or 75% of the time. A higher TOP value will give you a higher resolution at a lower frequency.

For a longer explanation read this article or refer to the datasheet.

Changing the prescaler, PWM mode, or TOP value for timer0 will mess with `millis()` and `micros()`.

---
Tags: pwm, analogwrite
---


# Question
Title: Does millis() conflict with the PWM pins associated with timer 0?
I've read that the `millis()` function uses the same timer as a couple of PWM pins.

If you're using those PWM pins, will `millis()` still return the correct value?

# Answer
> 7 votes
They do not conflict as `millis()` strictly reads the immediate value in `TCNT0` whereas PWM via timer 0 uses the hardware's ability to compare the value of `TCNT0` with the values in `OCR0x` without affecting the value of any of them.

# Answer
> 6 votes
Just to add to @Ignacio's answer which has directly answered your question. The "conflict" you speak of is in relation to `Timer0`'s prescaler.

For the most part, you can use those pins (incidentally pins 5 and 6 on the UNO) with PWM without an issue, and read the correct value of `millis()` (as well as get the expected delay from `delay`)

Where you run into problems is if you want to change the prescaler (usually to modify the frequency of the PWM signal). If you change this, then you directly affect the calculation and reporting of `millis()` and the length of `delay(x)`.

---
Tags: timers, pwm, millis
---


# Question
Title: How to send multi variable information over serial?
I would like to send information between my Arduino and my computer. Is there a way to send multiple variables from one Arduino? If so, how would I go about separating the variables?

# Answer
> 3 votes
**You have three options for what you want to achieve (if I understand it right):**

* **Have a fixed length for each variable:** If I know each number is going to be two digits, I can send "1234" and the other side can figure out the numbers are "12" and "34".
* **Have a delimiter character:** Have a character that signals a new variable. For example: "213|1234" would translate into "213" and "1234". You could even use the newline character to signal a new line (with `Serial.println();`).
* **Do some sort of validation to separate the data:** If sending a favorite number and favorite color, I can send "12RED345BLUE" and the other side it can find that it's "12" (both numbers), then "RED" (all letters), then "345" (three numbers), and finally "BLUE" (again, all letters).

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


title: Does Arduino run AC or DC

text:
# Question
Title: Does Arduino run AC or DC
Does arduino run AC or DC? Based on my small knowledge on the crystal in an arduino, it seems like AC makes sense. True? No?

# Answer
As a general rule, any modern electronic device with computational ability has to use DC. The reason is that they use specific voltage levels to indicate binary/logical states (i.e. 0's and 1's).

In theory, an ideal DC supply (Direct Current) should provide a constant voltage. That allows the circuit to effectively turn it on an off to represent binary states. (In reality, there's no such thing as truly "off" though, because voltage is relative.)

However, the voltage from an AC supply (Alternating Current) is constantly varying. If you plot it on a chart, you should see a nice sine wave, flowing smoothly between positive and negative several times per second. Hypothetically, if a digital circuit tried to use AC then it would get very confused, because everything would seem to be turning on and off all the time.

With all that said, it's very common to turn AC into DC through a process called rectification. For example, that's what allows DC devices to get power from an AC outlet (e.g. to run your computer or charge your phone).
> 7 votes

# Answer
All digital logic circuits run on DC.

Most Arduino boards include a voltage regulator. You can feed them an input ranging from 7 to 12 volts, and they "clean up" that input and lock it to precisely 5 volts, the voltage needed by the Arduino.

They can also run directly off the regulated 5 volts from the USB connector.
> 3 votes

# Answer
Have a look at this: http://arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf and try and have a guess.

I don't want to be nasty, but have you at least googled this? Google: "Arduino Power Source" and the first hit is http://playground.arduino.cc/Learning/WhatAdapter

It runs from USB as well as from an external power source.

To answer your question: DC
> 1 votes

---
Tags: arduino-uno, current
---


title: Questions on programming logic?

text:
# Question
Title: Questions on programming logic?
So I am learning arduino code by going through examples and playing with them, and I came across something interesting. I am not fluent in any coding language but I am fully familiarized with computer logic and function so I can read what you suggest just fine.

What I want to know is, why are these two code pieces different?

```
const int ledPin =  13;

int ledState = LOW;

long interval = 1000;

void setup() {

pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis = millis();

  if(currentMillis > interval) {

    currentMillis = 0;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    digitalWrite(ledPin, ledState);
  }
}

```

This is my code, or rather modification to this code:

```
const int ledPin =  13;

int ledState = LOW;
long previousMillis = 0;

long interval = 1000;

void setup() {

  pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {

    previousMillis = currentMillis;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    digitalWrite(ledPin, ledState);
  }

}

```

How is it that the first code works, and the second code turns the led on and either terminates or never turns the LED off? The code is designed to blink the LED once every 1 second.

# Answer
Ah yes, *this* problem.

Note the declaration of `currentMillis`:

```
unsigned long currentMillis = ...;

```

And now note the declaration of `previousMillis`:

```
long previousMillis = ...;

```

You wouldn't think that one little word could make that much difference, but it does. It *completely* changes how C performs mathematics. `previousMillis` *must* also be `unsigned` or you will get undesired results.
> 2 votes

# Answer
http://en.wikipedia.org/wiki/Two%27s\_complement \- good read regarding signed numbers in binary format. It really isn't "complex"; the highest bit being "1" denotes a negative number. As there is no "-0" the negative numbers also have an offset of one.

If you mix unsigned and signed - you simply get unexpected results.

You need to be very precise, i.e. check if the signed number is negative and handle it with care to make it "compatible" with the unsigned number before you use them together. What "care" ends up be in reality depends on what you expect to get out of it, as result.
> 0 votes

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


title: How can I make my Arduino code work?

text:
# Question
Title: How can I make my Arduino code work?
I am trying to make an automatic lock which stays open during different times and on different days. I want the door open Monday through Friday 8am to 5pm. On Saturdays and Sundays I want the door locked. I will be using an electric lock strike the + wire to pin 9 and - to ground on arduino. I am using an LED for development purposes for now because I don't have the lock yet. The code I have now works (stays open) for 8am to 5pm through the whole week but i want the door locked for Saturdays and Sundays. This is my code so far:

```
#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if (hour()>=8 && hour()<=17){
  digitalWrite(doorPin, HIGH);
}
else if (weekday()==1 || weekday()==7){
  digitalWrite(doorPin, LOW);
}

```

# Answer
> 6 votes
This is what's happening: it's still between 8 AM and 5 PM on the weekend, so it unlocks it. Since you use an `else if`, it terminates the `if` statement and never checks the day between 8 and 5. I'm almost positive that if you checked it another time in the day, it'd be "locked."

Fixed code:

```
#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if ((hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7)){
  digitalWrite(doorPin, HIGH);
}
else {
  digitalWrite(doorPin, LOW);
}

```

Note: `!` means "not." Thus, the door is locked only if it's not a weekend and it's between 8 and 5.

Additionally, you might want to get a lock that is the other way around: unlocked only with power applied so someone can't unplug the Arduino to get access. EDIT: miscommunication, ignore this part paragraph...

# Answer
> 3 votes
Adding to Annonomus Penguin's answer, it might be cleaner and easier to understand if you extract the variable:

```
bool doorOpen = ( (hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7) );

```

Or in my eyes even nicer if you unnegate the last part, ymmv:

```
bool doorOpen = ( (hour()>=8 && hour()<=17) && (weekday()!=1 && weekday()!=7) );

```

And then use them directly in the code without the if statement:

```
digitalWrite( doorPin, doorOpen ? HIGH : LOW );

```

This way you make sure that the doorPin always gets set and you din't forget a path like in your if-elseif-nothing version.

Another benefit is you can test independently if the doorOpen variable is correct and if the functionality that is triggered by it is correct.

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


# Question
Title: Cannot upload program to Arduino Duemilanove w/ Atmega328
This is the error I receive while trying to upload to the Arduino. I have installed FTDI drivers for mac. (http://www.ftdichip.com/Drivers/VCP/MacOSX/FTDIUSBSerialDriver\_v2\_2\_18.dmg)

The board is part of a quadcopter: https://www.hobbyking.com/hobbyking/store/uh\_viewItem.asp?idProduct=50460

The processor is an Atmel 328P. Do I have the correct drivers?

What else could be the issue?

# Answer
> 1 votes
You may have wrong port: **/dev/tty.usbserial-A9007LXq** works with Duemilanove on my Mac.

---
Tags: arduino-due, uploading, atmega328, ftdi
---


# Question
Title: Error building Arduino WiShield Flash example: 'dflash' was not declared in this scope
I'm using WiShield library from: https://github.com/jcmuller/WiShield

What is wrong with this library?

The code:

```
/*
 * Web Server using Flash
 *
 * A simple web server example using the WiShield 2.0
 * that reads the manufacturing ID from the Flash and
 * displays it on a webpage.
 */

#include <WiShield.h>
#include <dataflash.h>

#define WIRELESS_MODE_INFRA    1
#define WIRELESS_MODE_ADHOC    2

#define FLASH_SLAVE_SELECT 7
#define WIFI_SLAVE_SELECT  10

// Wireless configuration parameters ----------------------------------------
unsigned char local_ip[] = {192,168,1,2};   // IP address of WiShield
unsigned char gateway_ip[] = {192,168,1,1}; // router or gateway IP address
unsigned char subnet_mask[] = {255,255,255,0};  // subnet mask for the local network
const prog_char ssid[] PROGMEM = {"ASYNCLABS"}; // max 32 bytes

unsigned char security_type = 0;    // 0 - open; 1 - WEP; 2 - WPA; 3 - WPA2

// WPA/WPA2 passphrase
const prog_char security_passphrase[] PROGMEM = {"12345678"};   // max 64 characters

// WEP 128-bit keys
// sample HEX keys
prog_uchar wep_keys[] PROGMEM = {   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,     0x09, 0x0a, 0x0b, 0x0c, 0x0d,   // Key 0
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 1
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 2
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00    // Key 3
                            };

// setup the wireless mode
// infrastructure - connect to AP
// adhoc - connect to another WiFi device
unsigned char wireless_mode = WIRELESS_MODE_INFRA;

unsigned char ssid_len;
unsigned char security_passphrase_len;
//---------------------------------------------------------------------------

unsigned char mfg_id[4];

void setup()
{
  initShield();
}

// This is the webpage that is served up by the webserver
const prog_char webpage[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type:     text/html\r\n\r\n"
                                "<html><body style=\"margin:100px\">"
                                "<center>"
                                "<h1>Flash Mfg ID: 000 000 000</h1>"
                                "<form method=post action=\"/upload\" enctype=\"multipart/form-data\">"
                                "<b>FS Image Upload</b>"
                                "<p>"
                                "<input type=file name=i size=40>   <input type=submit value=\"Upload\">"
                                "</form>"
                                "</center>"
                                "</body></html>";

void loop()
{
  dflash.read_id(mfg_id);

  WiFi.run();
}

void initShield()
{
  // there is some contention on the SPI between the flash and wifi chip,
  // so disable both devices at the beginning until they are properly
  // initialized by their respective libraries
  pinMode(FLASH_SLAVE_SELECT, OUTPUT);
  digitalWrite(FLASH_SLAVE_SELECT, HIGH);
  pinMode(WIFI_SLAVE_SELECT, OUTPUT);
  digitalWrite(WIFI_SLAVE_SELECT, HIGH);

  // now init dataflash
  dflash.init(FLASH_SLAVE_SELECT);

  // now init wifi
  WiFi.init();
}

```

# Answer
I doubt anything is wrong with the library, but in your initShield and loop methods you refer to a variable called 'dflash' which does not seem to be defined anywhere.
> 0 votes

---
Tags: wifi, flash
---


# Question
Title: Sending MIDI messages using PING ultrasonic sensor
I am working on a project that uses a potentiometer and an ultrasonic sensor to create MIDI signals. This is my first time working with an arduino. I took a class in C++, but am teaching myself some C in order to program the arduino. So far I have been looking at code that has been written, I've been trying to understand it and mess with it so that my arduino works. The first code creates notes, but I have no control over what notes play or when they play. The first code:

```
#include <SoftwareSerial.h>

int val;
int AnalogValue = 0;
byte note = 0;
SoftwareSerial midiSerial(2, 3);

void setup ()
{

  pinMode(Pingpin, OUTPUT);
  Serial.begin(9600);
  midiSerial.begin(31250);
}

void loop()
{
  val = 0;
  digitalWrite(Pingpin, LOW);
  delayMicroseconds(2);
  digitalWrite(Pingpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(Pingpin, LOW);

  AnalogValue = analogRead(0);
  note = AnalogValue/8;

  pinMode(Pingpin, INPUT);
  val = digitalRead(Pingpin);
  while(val == LOW)
  {
    noteOn(val, note, 0x40);
  }
  while(val == HIGH)
  {
     noteOn(val, note, 0x40);

  }

}
void noteOn(byte cmd, byte data1, byte  data2)
{
    midiSerial.write(cmd);
   midiSerial.write(data1);
   midiSerial.write(data2);
}

```

The second code makes more sense to me, but I get no notes to play. I am lost, and can't seem to get the second code to work. Second code:

```
#include <SoftwareSerial.h>

int val;
int timecount;
int AnalogValue;
int ultrasoundValue;
const int Pingpin = 8;

byte note = 0;

SoftwareSerial midiSerial(2, 3);

void setup ()
{

  pinMode(Pingpin, OUTPUT);
  Serial.begin(9600);
  midiSerial.begin(31250);
}
void loop()
{
  AnalogValue = analogRead(0);
  note = AnalogValue/8;
  Serial.print(note,HEX);
  Serial.print("\t");

  timecount = 0;
  val = 0;
  digitalWrite(Pingpin, LOW);
  delayMicroseconds(2);
  digitalWrite(Pingpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(Pingpin, LOW);

  pinMode(Pingpin, INPUT);
  val = digitalRead(Pingpin);
  while(val == LOW)
  {
   val = digitalRead(Pingpin);
  }

  while(val == HIGH)
  {
   val = digitalRead(Pingpin);
   timecount++;
  }

   ultrasoundValue = timecount;
   ultrasoundValue = ultrasoundValue - 14;
   ultrasoundValue = ultrasoundValue / 5;

  Serial.print(ultrasoundValue);

if(ultrasoundValue > 127)
 {

 }

else
  {

   noteOn(ultrasoundValue, note, 0x40);

  }

}
void noteOn(byte cmd, byte data1, byte  data2)
{
   midiSerial.write(cmd);
   midiSerial.write(data1);
   midiSerial.write(data2);
}

```

# Answer
There is quite a bit that needs to be addressed for these programs to work, and I don't know too much about midi, but i'll use the arduino midi tutorial for info. http://arduino.cc/en/Tutorial/Midi?from=Tutorial.MIDI

The first code will take one measurement of an analog value, set it to note, make one digital reading of pingPin, set that to val, and then write noteOn() forever afterwards. The second code will continually make analog and Ping readings and then write those to serial if the ping reading is greater than 127.

Infinite loop aside, Your programs don't work largely because they send the sensor data in the wrong ways. The first byte sent to noteOn is a command byte, it should not contain sensor data. the arduino tutorial uses the command 0x90 to control the note being played on channel one. the second byte is the note and the third byte is velocity, which seems to work like volume.

to set the pitch and volume of channel one, you need to repeatedly send

```
noteOn( 0x90, note, volume);

```

If you want to play a note based on the analog readings that both of your codes set to "note" only when the ping value is larger than 127, you need something like this

```
if(ultrasoundValue > 127){
    noteOn(0x90, note, 0x45); //middle volume according to arduino tutorial
} else {
    noteOn(0x90, note, 0x00); //make the note silent by using 0 volume
}

```

if you instead wanted to control the pitch with the ultrasoundValue, you would need to scale the value to being within 0-255, and then use that as note instead of the analog reading. You can get much more complicated than this, but you will need to find a reference for the MIDI protocol you can use.
> 3 votes

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


# Question
Title: Can I hook up a compass directly to my GPS module?
I have a Parallax PMB-688 GPS module I'm using with an Arduino and was wondering if I could hook up a compass directly to my GPS. The GPS has an RX port which I hypothesized a compass could be attached to but I don't know if the GPS would be able to comprehend the compass data alone or if I would need to hook it up to the Arduino separately. Please let me know if you have done this or know whether or not it will work. Thanks,

Chris

# Answer
Unfortunately this will not work. If you take a look at the documentation for the module (here and here) you'll see that the RX pin is just there to receive commands for doing things like changing the baud rate and the protocol. The GPS wouldn't be able to comprehend the compass data.
> 1 votes

---
Tags: gps
---


# Question
Title: Breadboard-to-Arduino wiring with flat flex cable assemblies?
I want to wire Arduino Due connectors to a breadboard 8-at-a-time, so they're easier to remove and more reliable.

I tried these Flat Flex Cable Assemblies (FFC assemblies) terminated with "solder lugs" from Digi-Key, but the pins are just a little too short to penetrate the Arduino connectors well. Similarly they barely reach into to the breadboard contacts, so they tend to fall out. Anyone find a workable product for this?

This solution is good but requires a lot of manual soldering. Looking for prepackaged.

# Answer
> 7 votes
Search for male-male jumper wire. Some of what you'll find is individual wires but there are also many that are connected together and you can rip off the width you need.

Here's one from Adafruit but there is no shortage of them on ebay/amazon.

# Answer
> 5 votes
Again similar to Sachleen's answer. You can crimp your own connectors onto a ribbon cable, that way you can have the desired header size.

I've just done this manually with some pliers (I couldn't afford the crimping tool) a bit tricky but I'm pleased with the results. I got all of the bits I needed from www.hobbytronics.co.uk. Anywho I'm happy with the results now after a few failed attempts.

# Answer
> 3 votes
Although Sachleen's answer is preferable in a lot of situations, there are a few other options that you have.

*Quick note on his answer: I find clamping a row of those wires together and rubbing a thin line of superglue over the connectors a useful way to keep them together. It's not very neat, but it works pretty well and, with that many wires connected, can make it more stable than before.*

There are two main alternatives I see:

* **Ribbon cable:** very similar to the wires pointed out in Sachleen's answer, only the connectors come already as one piece.

> *Source: http://www.adafruit.com/blog/wp-content/uploads/2012/06/window-207.jpg*

They are typically two rows, but I've seen them before with one (although pretty rare). You could just ignore one row of those and use some male headers to connect the same side of the ribbon cable to the breadboard/Due.
* **DIY:** although you said that you didn't like soldering, it's still the best solution here IMHO. You'll need soldering later on, and breadboards aren't reliable beyond just simple development, so you'll need to learn at one point or another. This is a great entry project because it's pretty hard to mess a simple thing like this up, unless you accidentally bridge two joints. However, you won't damage an expensive chip if you mess up (which you will on the first few times you solder), you can just clean the joints and start over.

Anyway, just grab some perf board and some wire (twisted pair (similar to CAT5e)/ribbon cable with or without an adapter and plug/loose wires, and a few rows of male headers. The type of wire you choose doesn't really matter, just don't get something too thick or too thin. Anyway, solder some headers to the perf board and then you can solder the wires/the socket (if you choose a ribbon cable with ends) together. You can then cut the perf board to size (you can do this step before soldering) and you're done!

---
Tags: arduino-due, wires, prototype
---


title: What is causing my Uno to wake up?

text:
# Question
Title: What is causing my Uno to wake up?
NOTE: this code was working perfectly fine in another program.

I have a simple piece of code that puts the Arduino to sleep. When it is finished and intergrated into my project, it will only wake the processor up when an alarm from an external RTC triggers one of the hardware interrupts.

```
#include <avr/sleep.h>
#include <avr/power.h>

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

void loop(){
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);        //deep sleep mode
    Serial.println("Device is going to sleep...");
    sleep_enable();        //put device to sleep

    sleep_disable();        //Device restarts here on wake
    Serial.println("Device is awake...");
    delay(1000);        //to slow down serial output
}

```

In theory, the program should shut down the processor indefinitely because there is nothing available to wake it up.

However, the device continues waking itself up immediately after shutting down.

I have tried attaching the interrupts hoping it was some kind of anomalous watch-dog function. I have tried tying the interrupt pins to +5V and also (in a separate attempt) to GND. Nothing has helped.

What is causing the processor (and/or program) to constantly wake itself up?

# Answer
`sleep_enable()` *allows* the MCU to sleep, but it does not *cause* it to sleep. Call `sleep_cpu()` after enabling.
> 8 votes

---
Tags: arduino-uno, programming, interrupt, hardware
---


title: Arduino 433Mhz weather sensor receiver

text:
# Question
Title: Arduino 433Mhz weather sensor receiver
I want to monitor the temperatur around the house and outside. I want to save the data to mysql and then create some kind of webapplication that displlays the data. It is pretty easy to find temperature sensors that transmitts over 433Mhz, and I have thought about Telldus tellstick to receive data and store them. This receiver costs about 30 - 40 $ and 10 - 20 $ for each sensor.

But since I just learned that Arduino can be used for everything, I would love to hear more about it.

Can someone please give me an introduction to what I would need to make this solution? The arduino should basicly receive data from 433 Mhz sensors and store it to MySQL.

What woulds be the challanges when doing something like this?

# Answer
> 1 votes
You could use an Arduino with an ethernet shield to store the data to a MySQL server on the local network. See this blog post for an introduction to a library.

The tellstick is designed to be plugged into a USB host, so it doesn't make much sense in combination with an Arduino. You can get a USB host module but it's an expensive solution and you are using way more hardware than necessary.

Instead you could get 433 MHz receivers dirt cheap on ebay, but I'm afraid they only work on one channel, and there are a bunch of channels in the 433 MHz spectrum. So they might not work with the sensors you are talking about.

Another option would be to use eg. Arduino Pro Mini's in combination with a 433 MHz transmitter, powered by a battery. You could get the temperature reading from the internal sensor, or use an external one. The internal sensor takes quite a bit of calibration work to give a precise reading though.
You can get Pro Mini clones on ebay for a few dollars. You would have to dive into sleep modes and such, if you don't want't the batteries eaten away in a short time. To program it, you'll need an FTDI cable, or another Arduino programmed as an ArduinoISP (In System Programmer).
As an alternative to the Pro Mini board you could use a plain AVR chip, but it will be more work.

---
Tags: temperature-sensor
---


title: Can I speed up the Leonardo bootloader?

text:
# Question
Title: Can I speed up the Leonardo bootloader?
Inspired by an example question before beta, can I make the Leonardo bootloader take less that 8 seconds to run? It is very slow and I want to speed it up somehow.

# Answer
> 1 votes
Detailed instructions on how to shorten the bootloader time of Leonardo etc. are explained \[here\] (as stated by @Chris Stratton).

The crux of the matter was to redefine the timeout period

```
/* ./arduino/hardware/arduino/bootloaders/caterina/Caterina.c */
#define TIMEOUT_PERIOD 8000

```

to a lower value.

However I do not have such issues with Leonardo it boots very fast. So this issue depends on your environment.

There is also **OptiBoot**, an alternative bootloader that really boots faster link:

---
Tags: bootloader, arduino-leonardo
---


# Question
Title: How to add the -F switch for avrdude in Arduino IDE
So, before starting to learn with something else, I'll give it one last try. The avrdude is complaining that the device signature doesn't match. Whatever, I don't care. To me, what's written on it is what counts.

So I'd like to force it to upload the program. It promises to ignore the problem if `-F` is specified.

Where are settings for avrdude parameters, like other IDEs have settings for their compilers?

# Answer
> 3 votes
The error probably means that you have selected a wrong configuration.

To modify the IDE to insert the `-F` seems to be the hard way, however the easy way is to make a wrapper to `avrdude`:

```
$ cd ./arduino/hardware/tools/
$ mv avrdude avrdude.orig
$ cat >avrdude.sh
  #!/bin/sh

  ./avrdude.orig -F $@
  ^D
$ chmod +x avrdude.sh
$ ln -s avrdude.sh avrdude

```

---
Tags: arduino-ide, attiny, avrdude
---


# Question
Title: How does one build a door motion sensor project with Arduino Uno board to send alerts to an Android Phone?
1. What are the materials I will need for the project? We want the project to work like this: When the door is opened, we get an alert to our Android Phone.
2. What is the circuit structure going to look like?
3. Which is simpler, GPRS, Bluetooth or Wifi to get the alert?
4. What is the best IDE to work on for this project?

# Answer
> 2 votes
If I could comment on this, I would say that this question really sounds like you haven't actually done any research to look into a solution.

But, in simple terms:

1. Arduino Uno, Android phone, GSM shield, contact sensor or limit switch
2. The sensor or switch needs to be connected to an I/O pin on the Arduino, and will probably need to be connected to 5V.
3. GSM(GPRS) is going to provide the most mobility
4. Arduino

---
Tags: arduino-uno, arduino-ide, android
---


# Question
Title: Arduino based small LCD screen with camera video capturing
i have a idea to create a small screen which displays video recorded from arduino with camera. so camera will be back side of human and screen will be at near to eye. human can see the pictures from back side.

i have found https://electronics.stackexchange.com/questions/29139/processing-ntsc-video-feed-for-spi-display

but its not give me a clear idea. is there any one who can advice me for that kind project?

# Answer
An Arduino doesn't have anywhere near the processing ability to transcode video from a camera unless you had an abysmal frame rate and very low quality. Even then, you would have to add extra storage because the Arduino would be over capacity in a heartbeat.

I recommend converting this project to a higher powered board like the Udoo. I have the Udoo Quad and it's beastly considering its form factor. You're going to need something a lot bigger than an Arduino!
> 0 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Why PIN3 stays at 1v3 in a IR emitter project?
Here is my very simple IR emitter circuit. OSI5FU5111C-40 is an infrared LED.

I am using the IRremote library from here in this simple sketch,

```
#include <IRremote.h>
unsigned int raw[100]={... *SOME RAW SIGNAL* ...};
IRsend irsend;

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

void loop() {
  if (Serial.read() != -1) {
    for (int i = 0; i < 3; i++) {
      Serial.print("Start sending ...");
      irsend.sendRaw(raw, 100, 38);
      delay(40);
    }
  }
}

```

The problem is when I send `1` to serial monitor,

it outputs triple `Start sending ...` and LED emits no signal.

So I test the voltage between PIN3 and GND before and after sending the `1`. The voltage stays around 1V3.

Would someone please give me some advice? Thank you!

# Answer
A few things. As somebody else suggested, try a normal red LED and make sure that works first.

Note that your resistor is allowing too much current through the LED. A high-current LED might tolerate 20 mA (thousandths of an amp.) With a 47 ohm resistor, you're pumping 5/47, or about 106 mA into the LED, which is likely more than 5 times what it is designed to handle. You will quickly burn out your LED. You should use a 270 ohm resistor instead.

Also try just setting pin 3 to an output with this line:

```
pinMode(3, OUTPUT);

```

And then manually setting that pin to on:

```
digitalWrite(3, 1);

```

If the LED lights up, you know the pin is working correctly. Then use the code you posted with the same setup, and make sure your LED flashes. If THAT works, try putting your IR LED back in the circuit.
> 0 votes

---
Tags: arduino-uno, library, arduino-leonardo, remote-control, ir
---


# Question
Title: Problem uploading big program to arduino
I have an arduino duemilanove with ATmega328.

Been doing several experiments with multiple peripherals

I had no problem uploading at all

But when i try to upload a big program (27,074 bytes (of a 30,720 byte maximum)) it compiles fine, then says uploading...

After some time passes i get this error

```
avrdude: stk500_getsync(): not in sync: resp=0x00

```

The board and serial port connections are fine. Any ideas?

PS: Then i tried to upload the blink example, but i get the same error for some reason Everything worked fine before i uploaded my "big" program

# Answer
> 4 votes
The sync error is a common issue that doesn't have one simple solution (as shown here)

It means that the computer can't communicate with the processor, but it recognizes that it's there (out of sync). This is probably due to something (a peripheral, stray wire) interfering with the transmission from computer to device.

Solutions that have worked in the past:

* Unplugging the Arduino for 30 seconds, then plugging it back in.
* Removing any wires connected to Rx and Tx pins during upload.
* Soldering components connected to Rx or Tx to the board (in this case, I was using a shield that allowed me to do this)

There are lots of solutions available from different sources on the internet, but I have not come across one that names program size as the reason.

---
Tags: uploading
---


title: Using Bluetooth Dongle on Arduino

text:
# Question
Title: Using Bluetooth Dongle on Arduino
I need to communicate my arduino by bluetooth but I'm living in a small town recently so I can't buy a bluetooth shield for my arduino.

Here is my question: Can I use a usb bluetooth dongle on my Arduino **without a shield?** PS: There is no need to re-use that bluetooth dongle with usb again.

# Answer
You'll most likely need a USB host shield (like this) for the Arduino to be able to communicate with the dongle, so that doesn't help. You may (this is a long shot) be able to crack open the dongle, look up some datasheets, and possibly find a serial interface inside that you could connect to Arduino... but like I said, it's a long shot.
> 5 votes

# Answer
Unless your Arduino is based on a AT90USBXX7, no. Bluetooth dongles are highly integrated and have no accessible interfaces other than USB.
> 2 votes

---
Tags: serial, bluetooth
---


# Question
Title: How do I install the firmware on an Arduino Mega clone?
I have a brand new board which is a clone of the Mega2560. I need to install the USB firmware on the 16U2 and the bootloader on the 2650 chip. I have Atmel Studio and a JTAGICE-3. Using those, I can download HEX files compiled with the Arduino IDE, and they run successfully.

But I'm having trouble finding Mega-specific instructions for getting the firmware installed so that I can use the Arduino ISP protocol for downloading new sketches. I can find much more information about the Uno than the Mega. And much of the information I do find seems to be dated.

1) Which are the right files to download?
I've tried to install the 'MEGA-dfu\_and\_usbserial\_combined.hex' to the 16U2 and the 'stk500boot\_v2\_mega2560.hex' to the 2560.

But the IDE won't connect via AVR ISP, and I get no serial communications from a serial sample sketch downloaded with the ICE.

2) What are the correct Fuse settings after I flash those files?

3) Is there a good way to confirm that the 16U2 USB converter is working correctly in isolation from the 2560 chip?

# Answer
> 2 votes
Let focus on one thing at a time, that is flashing the 16u2. You can see if you've successfully done that when you can see the Arduino in your device-manager.

First of, `MEGA-dfu_and_usbserial_combined.hex` is, as stated on the github page, for the 8u2, not the 16u2. Since you already have a ISP programmer you don't need the dfu functionality. You can just flash the precompiled Arduino-usbserial-atmega16u2-Mega2560-Rev3.hex file.

The fuses can also be found in the readme.txt on github: `-U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m`. I don't see any difference in the fuses between the 8u2 and 16u2, so they should work for the 16u2 too.

Hope this helps.

---
Tags: arduino-mega, bootloader, firmware
---


# Question
Title: Whats the difference between RF options (wifi, xbee, NRF24L01)
When doing RF, you have many options. Three of the most basic are in the title box

1. WiFi
2. Xbee
3. NRF24L01

What are the practical differences in using them. What is the purpose of each other and the pros and cons. What would you use depending on the application you had?

I do not have a project in mind, but i want to start learning about Rf. I searched ebay for wireless devices. but i couldnt understand the differences. My goal is simply learning

# Answer
There are many different type of RF networks with various advantages and disadvantages. The main things I consider when choosing a wireless communication method are network topology, data rate and power consumption.

**WiFi:**

High data rate (54Mbit/s +) but also high power consumption. Used when you need to connect directly to the internet, such as an internet-of-things device, and have an external power source.

**XBee:**

Low data rate (250kbit/s) and low power consumption. Used to make mesh-type sensor networks; each XBee device can communication with each other, and *through* each other via the mesh to devices that are out of range. Used for networks of devices, particular home automation and sensors. link.

**Bluetooth:**

Medium data rate and medium power consumption. IEEE standard has different device profiles to enable interoperability between devices. 'Pairing' type network however, so not useful for sensor networks, but good for controlling devices using a laptop or phone which usually have Bluetooth on board. Communicates with Arduino via serial RX and TX pins. link.

**Bluetooth Low Energy, ANT, etc:**

Very low data rate and very low power. These RF chips can run for years on an AA battery and so are used for things like heart rate sensors. The data rate is quite low so only good for transferring a small amount of data such as sensor readings. Most devices are setup as peripherals and can only connect to one 'central' device, so no good for sensor networks. Bluetooth low energy is supported by the latest mobile phones and laptops however. Useful to enable control of a device using a phone or laptop, for example a LED lamp. (See redbearlab for some Arduino options)

**GSM**

Phone connection. TODO

**nRF24L01** **/** **RFM12B** **/** **RFM22B(SI4432)**

Popular proprietary transceivers. They can connect via SPI and have a lot of fancy features like low power modes, multiple channels, channel hopping, frequency calibration, CRC, retransmit and so on. The nRF24L01 from Nordic Semiconductor link operates in the 2.4GHz band, others use the ISM band 433/470/868/915Mhz. These are todays state of the art highly integrated and low cost hardware for reliable telemetry and consumer applications. The range is between 10m and 150m. The SI4432/RFM22B has the range of about 1.5Km.

**Other RF modules**

Simple and cheap serial devices. Single transmitter/receiver or transceiver that operate in the ISM band link. Often used as garage door opener. Useful for sensor network where interoperability with other devices is not required and you can implement your own protocol. link
> 45 votes

---
Tags: wifi, xbee, rf
---


title: Disable Boot Flash completely on ATMega

text:
# Question
Title: Disable Boot Flash completely on ATMega
I want to reclaim the space reserved for the bootloader on my ATMega32u4 (Leonardo chip). But the lowest boot flash size I can see is BOOTSZ=11 which is 256 words (512 bytes). Is it not possible to completely disable it? Basing this off of this: http://www.engbedded.com/fusecalc

# Answer
It is not possible to set the bootloader space to 0, but it is possible to unlock the bootloader space entirely by unprogramming the lock bits as well as to enable normal booting by unprogramming BOOTRST in the high fuse byte. Access to the entire chip will then be fully unrestricted.
> 4 votes

---
Tags: bootloader
---


# Question
Title: Autonomous Quadcopter power distribution and sensing concerns
I've been programming and testing an Arduino based quadcopter for the past 4 months. Until now I did not need to use an external power source for my sensors. Now I want to use the 'BEC' power from my electronics speed controllers.

Each of the 4 ESCs gives 5V @ 2A. I would set these up in a parallel circuit, which would give me 5V @ 8A (theoretically).

I also want to use a cheap chinese voltage sensor to sense the voltage from my 5000mAh 25-50c 11.1v battery. I'm not sure if it is safe to connect my batteries wires to my sensor with the 125A that it can put out.

My question is whether or not it is safe to have a common ground on Arduino with an 8A power supply AND if it is safe to use a 5V 8A power supply with these sensors.

Here is a problem that I've encountered before:

while powering my IMU off the BEC and sending motor PWM signals, my sketch would run for about 10 seconds then freeze. It was not until I powered my IMU off the Arduinos 5V power that I was able to run the sketch flawlessly. What could have been causing that?

I've made a diagram of my circuit in Fritzing (not actually tested yet due to fear of ruining my sensors). I'm using an Arduino Mega.

# Answer
> 2 votes
Your question is quite long. I've broken it up into several parts:

> whether or not it is safe to have a common ground on arduino with an 8 amp power supply

Yes. In fact, if you have any electrical connection (even a signal) between those two, you'll *need* a common ground to ensure integrity of the data being sent.

> if it is safe to use a 5 volt 8 amp power supply with these sensors.

I didn't see how much they drew. Without a lot of information, I'm going to say *yes*. If you don't need that much current, consider removing one of them so you only have 6A or 4A, since 8A is quite a bit if you aren't using it (and you might waste electricity in the conversion process). Make sure to have a thick enough wire for it. A best practice scenario would be to use each ESC separately or use two of the ESCs in parallel (with all of the grounds connected!). This would isolate the current to either 4A or 2A.

> while powering my IMU off the BEC and sending motor PWM signals my sketch would run for about 10 seconds then freeze. It was not until i powered my IMU off the arduinos 5 volt power that I was able to run the sketch flawlessly. What could have been causing that?

I'm not quite sure what would be causing that without seeing the code/circuit for that. The only thing I can think of is the grounds weren't connected and the signal got corrupted.

---
Tags: power, battery
---


# Question
Title: Is it possible to program a few Arduinos at the same time?
I have 10 Arduino Pro Minis and one Arduino Uno. Via breadboard, if I connect Pro Minis in parallel, can I program all of them at same time?

Is it possible?

# Answer
Arduino Pro Mini is programmed through serial, using a bootloader. It uses `STK500` protocol, which is described by Atmel.

In theory, it can be possible to program multiple boards if only one TX Arduino pin is connected to USB-Serial converter, and all RX are in parralel, but this is an unreliable method. Only the board with TX pin connected can send its status back to programmer.

Arduino Mini also requires a physical reset before uploading. Make sure that all Reset pins are connected together when reset button is pressed.
> 4 votes

# Answer
In this case I would recommend considering using multiple USB-to-Serial Ports and simply replacing the ".\arduino-1.5.6-r2\hardware\tools\avr\bin\avrdude.exe" with a batch file that then called 10 (or any number of Serial Ports) of your choice.

---

I would recommend reading my answer from Programming Arduino's from a centralized location.

Where that solution may be a bit more complicated, then needed. But the same pieces would allow you to create a custom programmer that can specifically call the custom avrdude. Allowing the original methods to still exist.

---

Additionally worth noting. Is that you can turn on verbose for the compiling and uploading from the IDE's preferences. This will display the temporary directory that contains the exact location of the bin file and command executed to upload. Which can then be easily re-executed your convenience. Noting the temporary directory is not immediately destroyed. Where you can also change the arguments to execute different ports and sending it to the background. To call others. So that you can simultaneously upload many devices.
> 3 votes

---
Tags: uploading, arduino-pro-mini
---


# Question
Title: How do I attach 4 input pots to arduino?
I am making an arduino game and the requirement is that my arduino reads 4 analog values from the pots. I dont know whether I should use an external battery supply or the 5V from the duino' itself. I dont want my ICs to get fried or nothing happening at all.

# Answer
It doesn't really matter as long as the the voltage across your pots doesn't exceed the ARef or IORef voltage, which is usually equal to Vcc (3.3V or 5V) for the Arduino boards. It's best to use the 5V from your board. The ADC inputs are relatively high impedance so very little current flows through. Don't use very large value pots or you might not get the correct values from your analog inputs.
> 3 votes

# Answer
Set up 4 pins as inputs. Wire the pots as voltage dividers (center wired to the input through a small-value resistor. One of the ends of the pot wired to +5V from your Arduino, and the other end wired to ground.)
> 1 votes

---
Tags: analogread, potentiometer
---


# Question
Title: Digital Read Serial tutorial - calculating the resistor value
The Arduino Digital Read Serial tutorial guides you through the wiring of a simple button. My questions are centered around the resistor.

# Why is the resistor necessary?

I think I understand this, but correct me if I am wrong. To ensure that the input pin reads a low signal, and does not float, we should connect the pin to ground when the button is not pushed. When the button gets pushed, we will have a 5V signal flowing to both the pin and to ground. Kirchhoff's voltage law states that total voltage in closed loop must equal zero, so we have to deal with this 5V that is flowing directly to ground. That is why we put a resistor between the button and ground.

# How was the resistor value chosen?

This is what I am unclear on. Ohm's law states that...

```
resistance = voltage / current

```

This is a 5V supply and the Arduino Uno spec says that the pin provides 40 mA of DC current. So..

```
resistance = 5V / 0.04A = 125 Ohms

```

In the Digital Read Serial tutorial, **why do we have a 10K Ohms resistor?** That is way overkill, right? Which leads to another question: **Can you ever put too much resistance in place, if your only goal is to obliterate voltage?**

Thanks in advance for any feedback!

# Answer
You're very close. The resistor is there to act as a pull down resistor; If the input pin is floating it is just an antenna picking up random static. The key is that when positive is supplied (by pressing the button) the positive source needs to "overwhelm" the pull down resistor so that the input pin reads positive.

If there were no resistance, than the input pin would be reading in the middle of a direct path that does not favor positive or negative. Asside from the direct short that would be occurring, Which state the arduino would read I suspect would either be random or some property of the power supply; It would probably still read ground.

With the resistor, the signal is read directly connected to positive, before the load resistance. This way it will be sure to get a HIGH signal.

The exact size of the resistor is of little consequence. Too small and you waste current, but too much resistance is effectively just disconnecting ground again. There is a very wide range of values that will work fine between those.

I would like to note that when an arduino pin is set to input mode, it will effectively supply no current. It can be moddeled is being in series with a 100 megaOhm resistor. see http://arduino.cc/en/Tutorial/DigitalPins for details.
> 6 votes

# Answer
> **Why is the resistor necessary?**

The Arduino inputs have very high resistance. The datasheed of the Atmega328 says 100 MOhm for ADC, Such high values are good, but have also the drawback to deal with parasitic effects (resistance, inductance, capacitance). Such effects can also be used as Capacitance Sensors.

> **How was the resistor value chosen?**

The resistor needs to have an arbitrary value, that is smaller than the input resistance. 10k and above are good for disabling the input leakage.

However you can also leave out the resistor when you use the internal pull-up resitors. In this case you deal with negative logic:

```
pinMode(3, INPUT);
digitalWrite(3, HIGH);

```

On pin 3 you'll measure `HIGH` and the button needs to be connected to the pin and the ground. The internal I/0 pull-up resistor has the value of 50k.
> 3 votes

# Answer
You've already gotten a couple of good answers on why a pull-down resistor is needed.

To summarize, you need to connect the input to ground to keep the input from floating semi-randomly between high and low. You use a resistor so that when you close the switch, you don't create a short circuit between the +5V supply and ground.

Another point, though. The Arduino's inputs include an optional internal, software-controlled **pull-up** resistor. If you first set up the pin as an input, then write a HIGH value to that port, it activates the pull-up resistor. That causes the pin to read as HIGH when nothing is connected to it.

You can then connect your switch to ground instead of +5V. You then need to change your code logic to treat a HIGH value as not pressed, and a LOW value as pressed. This lets you simplify your wiring a little, since you don't need an external resistor.
> 1 votes

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


# Question
Title: No valid serial ports for Arduino UNO on Mac
**UPDATE:** The issue turned out to be with my work laptop. Our IT department has them configured in such a way that the assignment of serial ports is different somehow. When I plugged in on my personal Macbook Pro it all worked perfectly.

---

I just got my first Arduino. Its an UNO R3. I'm running OS X 10.8.5 (Mountain Lion) and the Arduino IDE 1.0.5

Under **Tools\>Board** I have Arduino Uno selected

Under **Tools\>Serial** Port my options are:

* /dev/tty.Bluetooth-Serial-1
* /dev/cu.Bluetooth-Serial-1
* /dev/tty.Bluetooth-Serial-2
* /dev/cu.Bluetooth-Serial-2
* /dev/tty.Bluetooth-Modem
* /dev/cu.Bluetooth-Modem
* /dev/tty.Bluetooth-PDA-Sync
* /dev/cu.Bluetooth-PDA-Sync

I've tried all of them, but when I try to upload a sketch it fails. Most give the following error:

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

```

The two "modem" options return this message:

```
Serial port '/dev/tty.Bluetooth-Modem' already in use. Try quitting any programs that may be using it.

```

I'm at a loss. None of these serial ports seems correct but there aren't any other options.

Also under **Tools\>Programmer** which option should I be using?

# Answer
The issue turned out to be with my work laptop. Our IT department has them configured in such a way that the assignment of serial ports is different somehow. When I plugged in on my personal Macbook Pro it all worked perfectly.
> 1 votes

# Answer
Have you hooked up your Arduino prior to pulling down the tools\>Serial Port menu? I only see the port for my Arduino listed when it's actually connected and running. (And it's never one of the bluetooth ports.) I don't have my Arduino with me at the moment so I can't tell you exactly what it is.

Also note that on my MBP (running 10.9.4) I have to be sure to plug the USB cable into the CORRECT USB port. The other port maps to a different port in the list of serial ports.
> 1 votes

---
Tags: arduino-uno, serial, mac-os
---


title: Parse JSON with arduino to turn on LED

text:
# Question
Title: Parse JSON with arduino to turn on LED
Hi i'm trying to parse JSON resposne from webserver in my arduino in order to turn on and off a LED light. I'm using the wifi client repeating example to make a get request to my server:

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

Here is what I get printed back from the serial port

```
connecting...
HTTP/1.1 200 OK
Date: Sun, 06 Apr 2014 01:14:37 GMT
Server: Apache
X-Powered-By: PHP/5.5.10
Cache-Control: no-cache
X-Frame-Options: SAMEORIGIN
Set-Cookie: expires=Sun, 06-Apr-2014 03:14:37 GMT; Max-Age=7200; path=/; httponly
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json

19
{"lightstatus":"on"}
0

```

How do i parse the JSON portion of this response only so that I can use it to control my LED?

Thanks

# Answer
I'm aware of a few JSON parsing libraries for Arduino.

I've never used any of these but I did do some simple JSON parsing in a project I'm working on so I'll show you how I did that.

NOTE: I'm reading serial data using the software serial library. You'll need to change this code to work for you. This will only work on very simple JSON strings. It's *very* limited but if that's all you're parsing then it'll work.

Example of JSON response from server:

```
{"id":"TEST1","lat":"38.56050207","lng":"-121.42158374","total":"3","available":"2"}

```

First, only read data between curly braces.

```
String response = "";
bool begin = false;
while (SIM900.available() || !begin) {

    char in = SIM900.read();

    if (in == '{') {
        begin = true;
    }

    if (begin) response += (in);

    if (in == '}') {
        break;
    }

    delay(1);
}

```

This code reads data one byte at a time and once it gets an open brace, it starts saving it into `response`. When it gets a closing brace, it ends it. So here's a clear limitation, you can only have one set of opening/closing braces in your string.

Once I have the string, I use `indexOf` and `substring` to extract relevant information:

```
start = response.indexOf("id\":\"") + 5;
end = start + 5;
nodeId = response.substring(start, end);

```

This code sets `start` to the beginning of `id":"` \+ 5 characters in the string. It's +5 because that's how long `id":"` is. So `start` points to `TEST1` in the JSON string. In my system, the ID is always going to be 5 characters long so end is `start + 5`. I then use `substring` to extract that.

Again, before anyone starts down voting me for this horrible solution: if you know exactly what you're working with, and understand the limitations of this code, then this is not a bad solution. It's a solution that gets the job done.
> 11 votes

# Answer
I have programmed a class that will receive char by char the JSON document. It only will store in memory a few bytes for known JSON structure using a state machine and the results you need. So you can query the class for the results you want and will process the JSON.

Its ideal for your purpose. I have used for connecting to a weather service that returns a json:

```
static const char* queries[] = { "list.0.deg", "list.0.weather.0.main"};
StreamJsonReader jsonreader(queries, 2); // 2 queries
while(char c  =  read()){
      jsonreader.process_char(c);
}

cout << jsonreader.results[0] << endl;
cout << jsonreader.results[1] << endl;

```

Check this blog post I just wrote: http://web.biicode.com/blog/big-json-on-arduino.

Source code is here in Biicode.
> 7 votes

# Answer
I wrote a parser for the PIC that has very low ram use because it works directly with char pointers and does not build a tree structure. If you ask to get item N of a list, it gives you an actual pointer into the direct JSON file right at the start of item N of the list. Then you can ask what type of object the pointer represents, etc. It's buggy and doesn't support floats and I think has a few other limitations(twas a long time ago) but it's all on github:https://github.com/EternityForest/OpenFortune-fortune-like-text-generator You'll need to look in libfortune which is part of the C version.
> 2 votes

# Answer
I wrote a simple JSON-RPC library (on top of aJson) with example of how to turn a led on with JSON-RPC procedure call:
> 1 votes

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


# Question
Title: Problems with using example code for Wi-Fi shield (arduino)
I have problems with the Wi-Fi shield example code.

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

char ssid[] = "*****";          //  your network SSID (name)
char pass[] = "*****";   // your network password

int status = WL_IDLE_STATUS;
char servername[]="google.com";  // remote server we will connect to

WiFiClient client;

void setup() {
    Serial.begin(9600);
    //disable SD SPI
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    Serial.println("Attempting to connect to WPA network...");
    Serial.print("SSID: ");
    Serial.println(ssid);

    status = WiFi.begin(ssid, pass);
    if ( status != WL_CONNECTED) {
        Serial.println("Couldn't get a wifi connection");
        // don't do anything else:
        while(true);
        }
     else {
     Serial.println("Connected to wifi");
     Serial.println("\nStarting connection...");
     // if you get a connection, report back via serial:
     if (client.connect(servername, 80)) {
         Serial.println("connected");
         // Make a HTTP request:
         client.println("GET /search?q=arduino HTTP/1.0");
         client.println();
      }
    }
}

 void loop() {

}

```

The Wi-Fi Shield has connected with the internet Wi-Fi, but the last printing was "Starting connection..." I can't get to connect to (google.com), why?

# Answer
Have you upgraded the firmware in your wifi shield? If not, it will have problems connecting. Compile and upload this sketch. If it shows the firmware version as 1.0.0, then you need to upgrade the firmware. If it shows 1.1.0, then it is current as of today.

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

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while(true);
  }

  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());
}

void loop() {}

```

Please Note: The chips are numbered differently but run the same Wi-Fi firmware. You can upgrade the firmware without any worries.
> 2 votes

# Answer
I had this problem aswell. The problem was a bug with the official editor of arduino. I fixed this by downgrading the editor to version 1.0.3. (from 1.0.5) You can find a download link for it at the Arduino website.

Hope this helped!
-Kad
> 0 votes

# Answer
```
#include <WiServer.h>

#define WIRELESS_MODE_INFRA 1
//#define WIRELESS_MODE_ADHOC   2

// Wireless configuration parameters ----------------------------------------
unsigned char local_ip[] = {146, 227, 174, 29};      // Indirizzo IP
unsigned char gateway_ip[] = {146, 227, 175, 254};      // Indirizzo gateway IP
unsigned char subnet_mask[] = {255, 255, 248, 0};   // Subnet Mask
const prog_char ssid[] PROGMEM = {"enduroam"};      // SSID access point

unsigned char security_type = 3;    // 0 - open; 1 - WEP; 2 - WPA; 3 - WPA2

// WPA/WPA2 passphrase
const prog_char security_passphrase[] PROGMEM = {"EAP-MSCHAP V2"};  // max 64 characters
// setup the wireless mode
// infrastructure - connect to AP
// adhoc - connect to another WiFi device
unsigned char wireless_mode = WIRELESS_MODE_INFRA;

unsigned char ssid_len;
unsigned char security_passphrase_len;
// End of wireless configuration parameters ----------------------------------------
// This is our page serving function that generates web pages
boolean sendMyPage(char* URL) {

    // Check if the requested URL matches "/"
    if (strcmp(URL, "/") == 0) {
        // Use WiServer's print and println functions to write out the page content
        WiServer.print("<html>");
        WiServer.print("Hello World!");
        WiServer.print("</html>");

        // URL was recognized
        return true;
    }
    // URL not found
    return false;
}

void setup() {
  // Initialize WiServer and have it use the sendMyPage function to serve pages
  WiServer.init(sendMyPage);

  // Enable Serial output and ask WiServer to generate log messages (optional)
  Serial.begin(57600);
  WiServer.enableVerboseMode(true);
}

void loop(){

  // Run WiServer
  WiServer.server_task();

  delay(10);
}

```
> 0 votes

---
Tags: wifi
---


# Question
Title: What is the purpose of Galileo (or other unremovable chips)
I know the Arduino is a nice quick and dirty prototyping board. You quickly test your idea, and if you want to proceed you can do so with AVRs.

Your options are:

1. Upload the program to Arduino, then remove the AVR chip and make a PCB (with the bootloader)
2. Start from scratch with AVR (not always feasible because many libs are in Arduino)

Now what is the purpose of a system that has processors that cannot be removed? For example the Arduino Galileo.

Sure, you can do many things with it, but bottom line, you cannot remove the processor and do something with it.

As an example, imagine you are prototyping a system you wish to, then, market and sell. That is feasible with the Arduino Uno family.

But what if you did in in Galileo? Even if it worked, you couldn't sell your system because you rely on the prototyping board. You cannot remove the processor.

Am i missing something?

# Answer
> 3 votes
Edit: As Chris points out, this answer is more about the simple AVR Arduinos. For comment on the Galileo and other more complex MCUs, please refer to Chris' answer.

For Arduino compatibility you can program the Arduino boot loader into the microcontroller using the ICSP pins. You do not need a chip from an Arduino board, you just solder a blank one in. Once the boot loader is on there you can use the Arduino IDE to upload sketches via the UART.

It is not necessary to use the Arduino system to write programs. You include the Arduino library files in a normal C++ project in many different IDEs and use the avr toolchain to compile and avrdude to upload.

Update:

Here is an example of a board I just got back from PCBA. (The picture was sent by the PCB company for checking). Initially I made the board using an Arduino Pro Mini 3.3V, SD card breakout board, LSM303DHLC accelerometer breakout from Pololu, and Real Time Clock (RTC) breakout. Once everything was working I drew up a PCB in Eagle CAD, using the core of Arduino Pro Mini board plus the individual SD card, LSM303DLHC and RTC chips. I also added a 3.3V boost converter so I could get a constant 3.3V off 2 AA batteries.

The board has the ICSP pins broken out. Actually, you will find they are broken out on most Arduino boards. Using another Arduino as ISP I can program the Arduino boot loader via the ICSP pins, and then sketches can be uploaded via the UART using the Arduino IDE. In the IDE the board that is selected is "Arduino Pro Mini 3.3V 8MHz".

The Arduino boot loader is a small piece of firmware that runs on startup. It allows you to send a program over the UART which it stores into FLASH memory itself. It is not absolutely necessary. You can program the chip using the ICSP as well. It is really convenient however. Using software like xloader you can upload Arduino programs without the IDE. Really handy when other people are using the board and you don't want to share your code. Alternatively, you can write a script for avrdude to do it.

This project is for a university so I'm leaving it as Arduino compatible. In a commercial engineering environment, I would choose a more appropriate MCU (one with lower power consumption for a battery device) and rewrite the program to be more efficient and not rely on the Arduino and third-party libraries.

# Answer
> 1 votes
You are right. There are however people that use an arduino for hobby, and don't want to invest more time into learning to make PCB and programming bare AVRs. For some people getting some leds to blink is already very hard.

Also look at the amount of Arduino shields that are available. The target group of Arduino's has shifted from hobby electronics people to just regular people wanting to get some project working. People are okay with sacrificing an entire arduino board, adding some shields and putting it inside a Tupperware box. As long as it solves their problem, or does something cool.

# Answer
> 1 votes
The pentium-class x86 based Galileo mentioned in the question title appears intended to meet project needs which have (memory, compute, or interface) requirements beyond the capability of the simple AVR (or perhaps even ARM) based Arduino boards. It's not uncommon in the Arduino realm to see people trying to use the little processors for tasks which exceed their capability, and it appears intended to address that problem.

While one can breadboard the equivalent of the AVR based Arduinos, or duplicate the functionality of those or even the simpler ARM-based boards on a hobbyist-designed 2 layer PCB, implementing something like the Galileo would require a many-layer board designed by an experienced PCB designer. **For low-volume uses, someone would probably just buy the existing boards and use them** (there is a longstanding market of embedded control modules intended for such use) - only at high volumes would it be cost effective to re-implement the board or its equivalent.

# Answer
> 0 votes
Arduino boards, with or without removable chips, provide a lot of facilities ready to go for experimenters, prototypers, students, artists and other tinkerers who aren't necessarily interested in the electronics but just want a programmable controller to get a job done. They can often be the cheapest way to build a one-off system once you consider the labor to build a less expensive board.

It's really easy to program AVR chips on a breadboard or, in most cases, right on the custom project board. You don't need Arduino to do that. I've built up and programmed ATMega328p projects without ever taking my Arduino out of the box.

This is a project I prototyped on an Arduino Mega2560 and later ported to the project board with soldered-in chip. The cable is a USB FTDI serial cable, a stock item that connects any chip with a TTL UART directly to a computer USB port. (The green daughter board is an X-10 RF transmitter and the reason I prototyped this project on a larger CPU).

Often I develop project code solely on the project board; it's just about as easy. About the only advantages I get from using the larger board is multiple serial lines so I don't have to keep switching my terminal app off and on to allow down loading, and I can include lots of extra debugging code and libraries that I won't need in the project.

Your favorite tool set will work either way. The Arduino IDE, Eclipse, or bare-nekkid ARVdude at the command line. If your project code needs the Rx/Tx pins, you may need to build one board with jumpers to disconnect the project's serial hardware while you're downloading.

---
Tags: prototype, arduino-galileo
---


title: USB cable connector

text:
# Question
Title: USB cable connector
The arduino has a USB port which can connect to a computer. The cable used to make this connection has a standard USB connector at one end (that connects to the computer) and a "larger" connector on the opposite end (that connects to the arduino). See picture below:

What is the name of this "larger" connector?

# Answer
> 3 votes
They are both standard USB. The end which goes into the computer is type A (or USB-A), and the end which goes into the Arduino is type B (or USB-B). The USB-B connector is also commonly used on devices such as printers and scanners. The distinction mainly exists so it's obvious which device is the host (i.e. the computer) and which device is the client (i.e. the Arduino).

As a side note, other types of USB connector exist as well. You will probably be familiar with mini and micro USB connectors, which can be found on various devices such as digital cameras and mobile phones.

---
Tags: hardware
---


title: HC-0# Bluetooth module questions

text:
# Question
Title: HC-0# Bluetooth module questions
I've been playing with the HC-06 BT module lately, but now I want to do more with it and I'm not sure how to. I was wondering if it's possible to get signal strength from the module, or would I have to purchase another HC-0# module to do so? Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

# Answer
> 2 votes
> I was wondering if it's possible to get signal strength from the module

No, it doesn't appear so from the data sheet / AT command list.

> Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

Yes, and it can get the signal strengths. You should be able to get an HC-05 module on a breakout board from Ebay for less than $10 delivered. There's also a method to update the HC-06 firmware to be an HC-05 but it's probably easier for you to buy one.

---
Tags: bluetooth
---


# Question
Title: Is programming the ATTiny85 possible in 1.5?
I upgraded to Arduino 1.5.7 in hopes of using the command line interface for a larger project. However, the old package I was using to program the ATTiny85 chip with the Sparkfun Tiny AVR Programmer no longer works. I'm getting the following error:

```
Third-party platform.txt does not define compiler.path. Please report this to the third-party hardware maintainer.
processing.app.debug.RunnerException
    at processing.app.debug.Compiler.getCommandCompilerCPP(Compiler.java:597)
    at processing.app.debug.Compiler.compileFiles(Compiler.java:275)
    at processing.app.debug.Compiler.compileSketch(Compiler.java:642)
    at processing.app.debug.Compiler.compile(Compiler.java:125)
    at processing.app.Sketch.build(Sketch.java:1589)
    at processing.app.Sketch.exportApplet(Sketch.java:1611)
    at processing.app.Sketch.exportApplet(Sketch.java:1597)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2397)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at processing.app.helpers.StringReplacer.replaceFromMapping(StringReplacer.java:97)
    at processing.app.helpers.StringReplacer.replaceFromMapping(StringReplacer.java:89)
    at processing.app.helpers.StringReplacer.formatAndSplit(StringReplacer.java:37)
    at processing.app.debug.Compiler.getCommandCompilerCPP(Compiler.java:595)
    ... 8 more

```

Does a package exist that will allow me to program the chip in 1.5.7?

# Answer
> 7 votes
You can download a version of arduino-tiny for IDE 1.5.x from here.

---
Tags: attiny
---


title: Debugging i2C from Mac OSX desktop

text:
# Question
Title: Debugging i2C from Mac OSX desktop
I have a raspberryPi and Arduino connected via i2C. On the RPi I have a python script that takes int values and simply sends them to the RPi, which in turn echoes them back. I am trying to debug this, since I am unable to send ints larger than 255.

One thought was that I might be able to connect the arduino slave directly to my Mac, and then use the Arduino serial monitor to help with debugging.

Unfortunately the python script will not run, because I assume i2C can only be run on a Linux kernel.

Am I mistaken?

This is an edited portion of my python code

```
import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    return number

```

# Answer
No, your Mac doesn't have I2C support. It was pointed out in the comments that there might be some legacy port, but it won't be usable due to driver limitations.

You're getting a few things confused. USB is it's own technology, separate from I2C/UART/SPI. I'm not sure how you would even *wire* I2C to your Mac. The serial monitor in Arduino is for USB COM ports, not related to I2C.

As far as debugging, there's a few options. First of all, there are a few ways to debug I2C using an oscilloscope. If that's too expensive, you could also get away with a logic analyzer. The one I just linked was at Sparkfun for $150. If that's still too expensive and you're willing to risk $30, you can find cheap ones on eBay (most with little/no documenation).

I don't know your code, so I can't advise you on how to fix it. If you need to debug at such a low level, extra hardware is needed.

It doesn't seem like a maximum of 255 that odd, since that's the maximum number that you can do with one byte. You might have to split data up into multiple bytes with some sort of delimiter character. With some quick mental math, it seems as two bytes can give you numbers up to 65,535 if you combine both bytes (i.e. `10101010` \+ `01010101` = `1010101001010101`).

Edit: this seems like the Arduino code you want:

```
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int num1 = 0;
int num2 = 0;
int state = 0;
boolean secondByte = false;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
        if(secondByte) {
            num2 = Wire.read();
            number = (num1 << 8) + num2;

            Serial.print("data received: ");
            Serial.println(number);

            if (number == 1){
                if (state == 0){
                    digitalWrite(13, HIGH); // set the LED on
                    state = 1;
                }
                else{
                    digitalWrite(13, LOW); // set the LED off
                    state = 0;
                }
             }
         } else {
             num1 = Wire.read();
         }
         secondByte != secondByte;
    }
}

// callback for sending data
void sendData(){
    Wire.write(num1);
    Wire.write(num2);
}

```

The Python code will have to do the similar thing. Note: the first part of the number (reading left to right) will be sent first.
> 0 votes

---
Tags: serial, python, debugging
---


# Question
Title: I bought USB > FT232RL, can I use it to program a bootloader onto an Arduino?
I bought this thing off of eBay:
eBay Link
Will it allow me to program an ATmega\[xxx\] (Arduino clone) with a bootloader?
--\> If so, how would I go about it? What should I do, and what should I certainly not do?
--\> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?
I'm a bit new to Arduino, and since I learned that a fair amount of the clones being sold on eBay don't have a bootloader, I wondered how to fix this. (and the "barebones" seem to be quite a bit cheaper)

---

**Answer** \- *summarized from different answers below (as I can only mark one answer below as accepted):*
* Can you use an FT232R to burn a bootloader onto an AVR (such as an ATmega328)?
    + =\> Yes you can, though it's a bit annoying to do, as it's slow and a bit more complicated than just plug and play. See the first part of Chris Stratton's answer below.
* I already have a working Arduino style board, can I use that?
* The two options above are too much of a hassle for me, or I don't have an Arduino yet/available, is there another option?

# Answer
In fact, you can, but you are unlikely to enjoy it as it will be fairly slow.

While this module is intended for serial communications - which the ATmega won't support until it has a bootloader on it - the chip around which it is built can also be operated in "bitbang" mode:

http://www.ftdichip.com/Support/Documents/AppNotes/AN\_232R-01\_Bit\_Bang\_Mode\_Available\_For\_FT232R\_and\_Ft245R.pdf

Using reconfigured pins of this wired to the ISP pins of your target, and an implementation of the ISP algorithm running on the PC, it will indeed be possible to load a bootloader on to a new ATmega chip. However, USB is not designed for this type of usage - it is meant to move large blocks of data, rather than to efficiently do sequences of tiny operations. **The result is that the loading process will be drastically slower than with other methods.** You may also spend a fair amount of time tracking down software to do it, or writing your own.

If you have an already working Arduino-style board available, you can use that to program your new chip:

http://arduino.cc/en/Tutorial/ArduinoISP
> 5 votes

# Answer
You must use a ISP or (HV)PP programmer in order to write the Arduino (or similar) bootloader to the chip first. Only once you have done so will you be able to program it via a serial connection.
> 2 votes

# Answer
> Will it allow me to program an ATmega\[xxx\] (Arduino clone) with a bootloader?

NO. The serial device can only be used when the Atmel ATmega chip has a bootloader burned onto it.

> --\> If so, how would I go about it? What should I do, and what should I certainly not do?

To burn a bootloader onto a Atmel AVR chip you need a "AVR ISP (In-System Programmer)". There is a small 2x3 pin contact on your Arduino board.

In the Arduino IDE under the menu "Tools", "Programmer" you will find the different "AVR ISP (In-System Programmer)" that you can use.

Please note that some programmer have an 2x5 pin ISP contact and if that is the case you will also need to buy a 2x3 to 2x5 adapter.

Ref.: http://arduino.cc/en/Hacking/Bootloader

> --\> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

Most Arduino clones bought on ebay have info witch clone of Arduino they are.

> I'm a bit new to Arduino, and since I learned that a fair amount of the clones being sold on eBay don't have a bootloader, I wondered how to fix this. (and the "barebones" seem to be quite a bit cheaper)

Im a bit confused, I have bought ~10 Arduino clones from ebay and all had a bootloader. And they are clones of UNO, Nano, Leonardo and Mini Pro and that is what I uses for settings in my Arduino IDE.

I'm interested in witch ebay clones that doesn't have a bootloader, could you post a comment with that info?

I use a USBASP (example: http://goo.gl/kCiMd) as my external programmer.
> 1 votes

---
Tags: bootloader, avr, isp
---


# Question
Title: Leonardo (32u4): Timer0 problems with CTC mode
I want to use timer 0 to generate a rectangular signal on OC0A (D11) without the use of Arduino specific functions (that use timers for themselves). When I toggle D11 manually using a loop, I hear a sound in the connected piezo, but with my sample code, I don't hear something:

```
#define ALARM_PIN 11

void setup() {
  digitalWrite(ALARM_PIN, LOW);
  pinMode(ALARM_PIN, OUTPUT);
  noInterrupts();

  OCR0A = 60;
  // Toggle OC0A on compare match
  TCCR0A = (0 << COM0A1)
         | (1 << COM0A0)
  // CTC mode
         | (1 << WGM01)
         | (0 << WGM00);
  // prescaler = 256
  TCCR0B = (0 << WGM02)
         | (1 << CS02);
}

void loop() {
}

```

Any idea, what could be wrong?

**Update**

I've played with it a little bit more:

```
#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 250);
}

```

This causes my LED to light very dim, so the timer is running up to 255. But as soon as I set TCCR0A, nothing is lighting up:

```
#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  OCR0A = 60;
  TCCR0A = (1 << WGM01);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 0);
}

```

# Answer
> 2 votes
You should re-enable interrupts after you finish setting up. Use either

```
interrupts();

```

or

```
sei();

```

If you want to don't want to use the arduino specific commands. Even if the code does not need interrupts, background code does use them.

Timer 0 is used in arduino for some basic "house keeping" function like keeping time. I'm not sure if that could be part of your problem. you could try using a different timer.

# Answer
> 0 votes
Your value of `60` for `OCRA` will give you tone of around 16666hz which isn't audible to us humans. Try setting it to 255. That should give you a 4000hz tone, which is audible. (Or get your neighbors dog, and see if he dislikes hearing it)

You can use this online calculator to help you get the correct value for `OCRA`.

Note that you need 2 cycles to get a full wavelength (1 low and one high), so two toggles.

---
Tags: arduino-leonardo, timers
---


title: Best multiplexer for a led cube

text:
# Question
Title: Best multiplexer for a led cube
I had fun making a 3x3x3 led cube. Now I want to build a bigger one. I'd like to find out the best IC for it. I've seen that some projects uses multiplexer like 4051 or 74HC595.

I'd like to make it at least 8x8x8 (so the multiplexer has to easily be spotted in cascade), possibly supporting also the pwm (to fade the leds).

And I'm a little bit scared by the real time with a lot of LED.. do I have to solve the problem in hardware (with a "faster" multiplexer) o via software?

# Answer
Those aren't multiplexing chips. Those are just chips to give you more outputs than your arduino has.

The multiplexing is just done on the microcontroller. But it depends on how you are wiring the leds. You can wire the cube to use less digital outputs, but you'll end up with a less bright leds.

You could use no multiplexing. That way the leds are lid with a 100% duty cycle. But for that you'd need 512 outputs.

You can choose to light up only one level at a time. That way you only need 72 outputs (64 for the leds, and 8 for selecting the level). This is a form of multiplexing. Since only one level is lid at a time, the leds have a duty cycle of 12.5%. Please note that because of the way humans perceive light, it will look more like 1/3rd the brightness, instead of 1/8th (so that's great). Also note that since you only need one level to be on at a time, some people prefer to use a decade counter IC for that.

You could also choose to only light one row at a time. That way you only need 24 outputs (8 for the leds, 8 to select which row, 8 to select which level). But you'd need some additional circuitry to combine row- and level-selection.

There are specialized multiplexing IC, but those only support rows and colums (not level). So you need 1 chip for each level, and more problematically you need to run 8-row and 8-culumn wires for each level to the bottom. That's quite a bit of wire, which might ruin the aesthetics of the cube.

In short. There are quite a few ways of making a 8x8x8 cube. I'd suggest finding a well documented build from someone else that you like and follow that.

Quite a bit of information. I hope it's of help. If you have any more question feel free to ask.
> 4 votes

# Answer
You could use a few TLC 5940 PWM Drivers (http://www.ti.com/product/tlc5940).

Each one has 16 channels which would mean to power an 8\*8\*8 cube would need 32 Drivers.

However, you can use multiplexing to reduce the number of 5940's you would need.

For example, you could use 4 X 5940's which would give you 64 channels and use 8 X time multiplexing to give you 512 channels.

There are 4096 PWM steps giving you lots of control over brightness and can take up to 17v which should be more than enough for any LED.

One of the added features for the 5940 is because it is a current sink, you dont need a resistor on every LED.

I am currently working on a project with TLC5940's that requires control over 512 RGB LED's meaning I have 1536 individual channels to control
> 1 votes

---
Tags: led
---


title: Controlling a motor with a wav file

text:
# Question
Title: Controlling a motor with a wav file
I've got an SD card and speaker hooked up to my nano and I can play mono audio files easily. My question is, is it possible to control the speed of a motor using the pwm output to the speaker? I tried just hooking the motor in where the speaker was, but that produced no noticeable variations in speed.

Alternatively, is it possible to analyse the wav file on the nano and control the motor that way? (i.e. motor speed is dependant on volume at a given time)

Thanks

# Answer
Regular sound files will have an even amount of time spend energizing the coil positive and negative, so the motor will not spin around in the normal sense. With a strong enough amplifier it will produce the sounds in the file like a speaker, but it will not noticeably turn.

Actual PWM varies the percentage of the time the signal is HIGH in a fixed frequency square wave, thus all the different values are the same "pitch". Audio varies amplitude and frequency, but the cumulative effect of audio waves is neutral, it spends half of the time below neutral and half above neutral voltage. The simplest analogy I can think of is audio being itself, even vibrations in air, and motor PWM being wind.

I am not sure if it possible to generate a sound file that would turn the motor, it probably depends on the file type. In any case, you would be better off with a far simpler amplifier like a transistor, MOSFET, or H-Bridge on one of your nano's actual PWM pins.

As to whether or not you could analyse the file on arduino, it also depends on file type. The code for the arduino WAV sheild I've seen does not have the arduino actually processing data, but It should be possible with a simple enough file type for arduino to decompress. WAV is not normally compressed, just raw data, so your limits are the RAM and if you can code something to glean volume from the raw data. I don't have much experience in that kind of file processing on AVR so I'm not going to call it either way.
> 2 votes

---
Tags: motor, pwm, audio
---


# Question
Title: Proxying streaming i2c data(int values) to serial
The following code works correctly in reading single int values. It also works correctly for 3-4 seconds if I 'stream' the values in constantly (Mouse move coordinates) before I get an IO error and the i2C bus connection is dropped. I assume this is some sort of buffer overrun...or? Can anyone get me on the right track here? What changes do I need to make so that I can constantly stream in serial data?

```
    #include <Wire.h>

#define SLAVE_ADDRESS 0x04
int zeroByte;
int state = 0;
int receivedValue = 0;

int numBytes = 0;

bool newData = false;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
    if(newData){

      Serial.println(receivedValue);
      newData=false;
    }
}

// callback for received data
void receiveData(int byteCount){

    while(Wire.available()) {
        newData = true;
        zeroByte = Wire.read();

         if(Wire.available() == 2)
  {
    receivedValue = Wire.read() | Wire.read() << 8;

  }

     }
}

// callback for sending data
void sendData(){

    Wire.write(receivedValue);
}

```

# Answer
> 0 votes
Your I2C bus is operating at 100 kHz. Your serial connection is set to 9600 baud. In case you are sending coordinates at a pace faster than the serial interface can keep up, the buffer will fill up. I assume you are using hardware serial (uno, mega, etc). Once the buffer is filled up Serial.write (which is called by Serial.println) will block until the buffer has free space. But the serial transmission depends on interrupts, and you are calling Serial.write inside an interrupt routine. By defult interrupt routines block other interrupts from happening. So your program gets stuck there and locks up both the serial transmission and the I2C interface.

It would be a good idea to put the serial write outside the interrupt routine, in the loop. Make a global variable `bool newData = false;` and set it true in the receiveData function. In your loop check the flag and transmit the data. Then set the flag to false.

You will still experience data loss if the serial interface can't keep up, but your application wont lock up. To solve the data loss simply use a higher baud rate, eg. 115200.

---
Tags: i2c
---