title: How do I make a atmega 32u4 mp3 player?

text:
# Question
Title: How do I make a atmega 32u4 mp3 player?
Is there a way to use the atmega 32u4 breakout board to make a mp3 player without the mp3 shield?

# Answer
You don't.

A basic ATmega lacks the computational (and perhaps memory also) resources for mp3 decoding. And even if you do decode to a linear PCM format, you do not have a good way to output it.

You can playback linear PCM data by pulse width modulating a pin, but the limited clock rate will result in limited resolution, and thus poor fidelity. You will also end up with a low sample rate, making it hard to avoid audible artifacts.

The situation can actually be somewhat better with an ATtiny85 - still no MP3 decoding of course, but you can clock the counter/time block at a higher rate and so playback PWM audio with higher fidelity, provided you are willing to tolerate the inaccuracy of the onboard clock oscillator that may shift your audio frequencies by a small amount.

If you want to do MP3, you will need either a more powerful processor (often no more expensive than the one you have, and typically cheaper as a module than anything "-duino"), or else a dedicated function chip to act as a coprocessor for that purpose.
> 1 votes

---
Tags: arduino-pro-mini
---


# Question
Title: What are the basic steps to make a printed circuit board?
I created a shield for Arduino on a soldering board. The next step shall be to implement the circuit on a PCB. I'm new to this, so I'd like to know what the basic steps in designing a PCB are.

More specifically,

1. What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?
2. Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Of course, any pointers to good tutorials on the Web will be appreciated, too!

# Answer
> 2 votes
Software packages are, amongst others

* Fritzing (more target at beginners)
* Eagle (free for board of size 100 x 80 mm (4 x 3.2 inches)).
* KiCad (open source)

Companies that make you pcb in small quantities are e.g.

I personally create my own double layer PCBs at home. I first started with the toner-transfer method, but now use photo lithography. I etch in Hydrochloric acid and hydrogen-peroxide. I can have a finished board in 1-2 hours, instead of having to wait a week or so. Great learning experience.

# Answer
> 1 votes
> What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?

There are plenty of good free ones, or free versions of commercial ones. Use the one that best suits your way of working - they are all different, try some out and find out which you like best. I use a free one for all my work (but then I am a FOSS junkie).

> Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Generally, no. It'd be just too costly. There are small quantity houses around though, and I often use iTead for my prototyping, since they will do batches of just 10 boards at a reasonable cost.

The basic steps in designing a PCB though are:

1. Design it as a schematic
2. Lay it out as a PCB design
3. Get a prototype made
4. Build it
5. Correct the mistakes
6. Go back to 3

If you only want one circuit and it is a pretty simple one you might want to give making the PCB yourself a go - it's quite rewarding and if nothing else gives you good insights into PCB design requirements and how best to lay out a PCB and the tracks for a good reliable etch. If you have a laser printer the Toner Transfer method of home PCB production is good.

---
Tags: shields, system-design
---


# Question
Title: Where are the digital and analog pins for the adafruit atmega 32u4 breakout board?
Which pins are the analog and digital pins? I've been searching the internet for an hour and I could get an answer.

# Answer
The information is right there on the product page for you. It took be a total of about 4 seconds to find it.

http://ladyada.net/products/atmega32u4breakout/
> 0 votes

---
Tags: arduino-leonardo
---


title: Program ATtiny13 - 20PU

text:
# Question
Title: Program ATtiny13 - 20PU
I'm trying to program my ATtiny 13 - 20PU. An it seems to work, but there is no action upon the "delay" command. If on the sketch below I comment out the "High" line, my led is off all the time and whenever I have a `Pin 4 High`, it's on all the time! Basically this seems to be a frequency/fuse/bootloader problem and made me think the upload was broken.

I added a led between the tiny's pin 3 (digital pin 4) and ground with a 1k current limiting resistor. This one is for testing with the attached sketch. I also tried this breadboard circuit, which gives exactly the same results.

Upon upload to the tiny I get this:

```
Sketch uses 380 bytes (37%) of program storage space. Maximum is 1,024 bytes.
Global variables use 8 bytes of dynamic memory.

```

(Everybody warns about 2 errors occuring upon a proper upload - I don't get those).

My boards.txt look like this:

```
menu.cpu=Processor
menu.clock=Clock

attiny.name=ATtiny
attiny.bootloader.tool=arduino:avrdude
attiny.bootloader.unlock_bits=0xff
attiny.bootloader.lock_bits=0xff
attiny.build.core=arduino:arduino
attiny.build.board=attiny
attiny.upload.tool=arduino:avrdude

attiny.menu.cpu.attiny45=ATtiny45
attiny.menu.cpu.attiny45.upload.maximum_size=4096
attiny.menu.cpu.attiny45.build.mcu=attiny45
attiny.menu.cpu.attiny45.build.variant=tiny8

attiny.menu.cpu.attiny85=ATtiny85
attiny.menu.cpu.attiny85.upload.maximum_size=8192
attiny.menu.cpu.attiny85.build.mcu=attiny85
attiny.menu.cpu.attiny85.build.variant=tiny8

attiny.menu.cpu.attiny44=ATtiny44
attiny.menu.cpu.attiny44.upload.maximum_size=4096
attiny.menu.cpu.attiny44.build.mcu=attiny44
attiny.menu.cpu.attiny44.build.variant=tiny14

attiny.menu.cpu.attiny84=ATtiny84
attiny.menu.cpu.attiny84.upload.maximum_size=8192
attiny.menu.cpu.attiny84.build.mcu=attiny84
attiny.menu.cpu.attiny84.build.variant=tiny14

attiny.menu.clock.internal1=1 MHz (internal)
attiny.menu.clock.internal1.bootloader.low_fuses=0x62
attiny.menu.clock.internal1.bootloader.high_fuses=0xdf
attiny.menu.clock.internal1.bootloader.extended_fuses=0xff
attiny.menu.clock.internal1.build.f_cpu=1000000L

attiny.menu.clock.internal8=8 MHz (internal)
attiny.menu.clock.internal8.bootloader.low_fuses=0xe2
attiny.menu.clock.internal8.bootloader.high_fuses=0xdf
attiny.menu.clock.internal8.bootloader.extended_fuses=0xff
attiny.menu.clock.internal8.build.f_cpu=8000000L

attiny.menu.clock.external8=8 MHz (external)
attiny.menu.clock.external8.bootloader.low_fuses=0xfe
attiny.menu.clock.external8.bootloader.high_fuses=0xdf
attiny.menu.clock.external8.bootloader.extended_fuses=0xff
attiny.menu.clock.external8.build.f_cpu=8000000L

attiny.menu.clock.external16=16 MHz (external)
attiny.menu.clock.external16.bootloader.low_fuses=0xfe
attiny.menu.clock.external16.bootloader.high_fuses=0xdf
attiny.menu.clock.external16.bootloader.extended_fuses=0xff
attiny.menu.clock.external16.build.f_cpu=16000000L

attiny.menu.clock.external20=20 MHz (external)
attiny.menu.clock.external20.bootloader.low_fuses=0xfe
attiny.menu.clock.external20.bootloader.high_fuses=0xdf
attiny.menu.clock.external20.bootloader.extended_fuses=0xff
attiny.menu.clock.external20.build.f_cpu=20000000L

#################################################
attiny.menu.cpu.attiny13=ATtiny13
attiny.menu.cpu.attiny13.upload.maximum_size=1024
attiny.menu.cpu.attiny13.build.mcu=attiny13
attiny.menu.cpu.attiny13.build.variant=core13

attiny.menu.clock.internal96=9.6MHz (internal)
attiny.menu.clock.internal96.bootloader.low_fuses=0x7A
attiny.menu.clock.internal96.bootloader.high_fuses=0xff
attiny.menu.clock.internal96.build.f_cpu=9600000L
################################################

attiny.menu.clock.internal48=4.8MHz (internal)
attiny.menu.clock.internal48.bootloader.low_fuses=0x79
attiny.menu.clock.internal48.bootloader.high_fuses=0xff
attiny.menu.clock.internal48.build.f_cpu=4800000L
################################################

```

And I choose the settings: Board ATtiny, Processor ATtiny13, Clock 9.6 MHz (internal), Port Arduino Uno (same as when I upload the ISP sketch), Programmer Arduino as ISP. I upload by clicking "Upload using Programmer".

Arduino Software is 1.6.4, the programmer Arduino is an Uno SMD edition. I used this programmer and this tutorial for smeezkitty core13.

I'm trying to upload this sketch:

```
// Blink sketch to test ATtiny Chips

//       ATMEL ATTINY13 / ARDUINO
//
//                 +-\/-+
// ADC0 (D 5) PB5 1|*   |8 Vcc
// ADC3 (D 3) PB3 2|    |7 PB2 (D 2) ADC1
// ADC2 (D 4) PB4 3|    |6 PB1 (D 1) PWM1
//            GND 4|    |5 PB0 (D 0) PWM0
//                 +----+

const int LED_PIN = 4; // digital pin
const int DELAY_TIME = 1000; // time between blinks [ms]

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

void loop() {
  digitalWrite(LED_PIN, LOW);
  delay(DELAY_TIME);
  digitalWrite(LED_PIN, HIGH);
  delay(DELAY_TIME);
}

```

Trying to burn a bootloader with the same settings as uploading to the tiny and then tools -\> burn bootloader, get's me the error:

```
"efuse" memory type not defined for part "ATtiny13"
Error while burning bootloader.

```

Skimming through the data sheet I noticed that the tiny13 - 20PU (the 20) stand for 20 MHz,... theoretically one should be able to downclock them to the ordinary 10 MHz, but maybe this is my problem?

# Answer
> 1 votes
There was some mistakes in the boards.txt it seems. After finding a very detailed and extensive boards file here, I modified it to have neat and tidy categories and is easier to use to become a working boards.txt. I had to burn the bootloader once to set the fuses right. After that everything works like a charm for 3 ATtiny13! No warnings or errors. This is used with Arduino 1.6.4. The folder tree is `~Arduino/hardware/attiny/avr/cores/core13` and `~Arduino/hardware/attiny/avr/boards.txt`

```
# boards.txt for Arduino 1.6.4

menu.flag=GCC Flags
menu.cpu=Processor
menu.clock=Clock

attiny13.name=ATtiny13
attiny13.upload.tool=arduino:avrdude
attiny13.upload.using=arduino:usbtiny

attiny13.bootloader.tool=arduino:avrdude

attiny13.menu.cpu.attiny13=ATtiny13
attiny13.menu.cpu.attiny13.upload.maximum_size=1024
attiny13.menu.cpu.attiny13.upload.maximum_data_size=64
attiny13.menu.cpu.attiny13.build.mcu=attiny13
attiny13.menu.cpu.attiny13.build.core=core13
# attiny13.menu.cpu.attiny13.build.variant=core13

#################################################
############## clock speeds #####################
#################################################

#### 9.6 MHz
############
attiny13.menu.clock.t13_9M6=9.6MHz (internal clock, Preserve EEPROM, BOD disable)
attiny13.menu.clock.t13_9M6.bootloader.low_fuses=0x3A
attiny13.menu.clock.t13_9M6.bootloader.high_fuses=0xFF
attiny13.menu.clock.t13_9M6.upload.speed=57600L
attiny13.menu.clock.t13_9M6.build.f_cpu=9600000L

#### 9.6 MHz - 2.7V
attiny13.menu.clock.t13_9M6_bod=9.6MHz (internal clock, Preserve EEPROM, BOD - 2.7V)
attiny13.menu.clock.t13_9M6_bod.bootloader.low_fuses=0x32
attiny13.menu.clock.t13_9M6_bod.bootloader.high_fuses=0xFB
attiny13.menu.clock.t13_9M6_bod.upload.speed=57600L
attiny13.menu.clock.t13_9M6_bod.build.f_cpu=9600000L

#### 4.8 MHz - 2.7V
attiny13.menu.clock.t13_4M8_bod=4.8 MHz (int 4.8 MHz clock, Preserve_EEPROM, BOD - 2.7V)
attiny13.menu.clock.t13_4M8_bod.bootloader.low_fuses=0x31
attiny13.menu.clock.t13_4M8_bod.bootloader.high_fuses=0xFB
attiny13.menu.clock.t13_4M8_bod.upload.speed=57600L
attiny13.menu.clock.t13_4M8_bod.build.f_cpu=4800000L

#### 1.2 MHz
attiny13.menu.clock.t13_1M2=1.2 MHz (int 9.6 MHz divided by 8,Preserve_EEPROM, BOD - 2.7V)
attiny13.menu.clock.t13_1M2.bootloader.low_fuses=0x2A
attiny13.menu.clock.t13_1M2.bootloader.high_fuses=0xFB
attiny13.menu.clock.t13_1M2.upload.speed=9600L
attiny13.menu.clock.t13_1M2.build.f_cpu=1200000L

#### 600 kHz
attiny13.menu.clock.t13_0M6=600 kHz (int 4.8 MHz divided by 8, Preserve_EEPROM, BOD disable)
attiny13.menu.clock.t13_0M6.bootloader.low_fuses=0x29
attiny13.menu.clock.t13_0M6.bootloader.high_fuses=0xFF
attiny13.menu.clock.t13_0M6.upload.speed=9600L
attiny13.menu.clock.t13_0M6.build.f_cpu=600000L

## 128 kHz
attiny13.menu.clock.t13_128k=128 KHz (internal watchdog oscillator)
attiny13.menu.clock.t13_128k.bootloader.low_fuses=0x7B
attiny13.menu.clock.t13_128k.bootloader.high_fuses=0xFF
attiny13.menu.clock.t13_128k.upload.speed=250
attiny13.menu.clock.t13_128k.build.f_cpu=128000L

## 16 kHz
attiny13.menu.clock.t13_16k=16 KHz (internal watchdog oscillator, Preserve_EEPROM, BOD disable)
attiny13.menu.clock.t13_16k.bootloader.low_fuses=0x2B
attiny13.menu.clock.t13_16k.bootloader.high_fuses=0xFF
attiny13.menu.clock.t13_16k.upload.speed=250
attiny13.menu.clock.t13_16k.build.f_cpu=16000L

##-----------------------------------
##--------- compiler flags ----------
##-----------------------------------

attiny13.menu.flag.Os=Default
attiny13.menu.flag.Os.compiler.c.extra_flags=
attiny13.menu.flag.Os.compiler.c.elf.extra_flags=
attiny13.menu.flag.Os.compiler.cpp.extra_flags=

attiny13.menu.flag.Os_flto=Default -flto
attiny13.menu.flag.Os_flto.compiler.c.extra_flags=-Wextra -flto
attiny13.menu.flag.Os_flto.compiler.c.elf.extra_flags=-w -flto
attiny13.menu.flag.Os_flto.compiler.cpp.extra_flags=-Wextra -flto

attiny13.menu.flag.O1=-O1
attiny13.menu.flag.O1.compiler.c.extra_flags=-O1
attiny13.menu.flag.O1.compiler.c.elf.extra_flags=-O1
attiny13.menu.flag.O1.compiler.cpp.extra_flags=-O1

attiny13.menu.flag.O1_flto=-O1 -flto
attiny13.menu.flag.O1_flto.compiler.c.extra_flags=-O1 -Wextra -flto
attiny13.menu.flag.O1_flto.compiler.c.elf.extra_flags=-O1 -w -flto
attiny13.menu.flag.O1_flto.compiler.cpp.extra_flags=-O1 -Wextra -flto

attiny13.menu.flag.O3=-O3
attiny13.menu.flag.O3.compiler.c.extra_flags=-O3
attiny13.menu.flag.O3.compiler.c.elf.extra_flags=-O3
attiny13.menu.flag.O3.compiler.cpp.extra_flags=-O3

attiny13.menu.flag.O3_flto=-O3 -flto
attiny13.menu.flag.O3_flto.compiler.c.extra_flags=-O3 -Wextra -flto
attiny13.menu.flag.O3_flto.compiler.c.elf.extra_flags=-O3 -w -flto
attiny13.menu.flag.O3_flto.compiler.cpp.extra_flags=-O3 -Wextra -flto

```

# Answer
> 0 votes
The "efuse error" on burning the bootloader is described in the article you refer to and a solution is given there as well. It occurs when the attiny13 is defined in the same group as the attiny25/45/85 as the former has no efuse and the latter do.

Giving the attiny13 its own menu entry in the IDE -as described in that article- should solve that.

---
Tags: attiny, frequency, fuses
---


# Question
Title: What is wrong with my 32u4 breakout board from adafruit?
I recently bought the atmega 32u4 breakout board from adafruit. I uploaded a sketch, then it says that there isn't a timer 2 on it and it won't do as I programmed my sketch. how can I fix this?

# Answer
You will need to port any libraries and code that depend on timer 2 to the '32U4 architecture. There is no way to add timer 2 to the chip, and it is likely that trying to force it to use a different timer won't help since it may configure things the other timer doesn't have.
> 0 votes

---
Tags: arduino-leonardo
---


title: Starting Off Low-Level Port Access

text:
# Question
Title: Starting Off Low-Level Port Access
I'm trying to teach myself some low\[er\] level code, but I just can't get it to work. I've tried OR-ing stuff in, AND-ing stuff in, and just straight up defining stuff, but it's not blinking! What am I doing wrong here?

I am using an Arduino UNO R3 DIP for this. I am just using the on-board LED, (on pin13/PORTB\_5)

Current code:

```
#define STATE B00001000
#define ZERO B00000000
void setup() {
    DDRB = STATE;
    }

void loop(){
    PORTB |= STATE;
    delay(500);
    PORTB &= ZERO;
    delay(500);
    }

```

# Answer
It would probably help if you were using the right pin. In the pins\_arduino.h file for the Uno is this diagram:

```
//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+

```

That shows that pin D 13 is PB5 which would be a binary value of `0b00100000` not `0b00001000` as you have, which would be PB3, or pin D11.

The only way I can come up with `0b00001000` is if I count from the left (wrong) and start at 1 (wrong) rather than count from the right (right) and start at 0 (right).
> 3 votes

---
Tags: arduino-uno, debugging, arduino-uno-smd
---


# Question
Title: SoftwareSerial.h alternative with AVR (Two Serial/UART ports in atmega328p)
`Arduino` pins can be used as `UART` using the `SoftwareSerial.h` library. Is there any alternative for `AVR`?

I need more than one serial port on a `ATmega328P`, but i don't use `Arduino`.

`SoftwareSerial.h` is tied to `Arduino.h` and `Arduino` pins. I do not use `Arduino`, i use `avr-gcc` with `atmega328p` and `atmega8`.

# Answer
> 2 votes
AVR274 describes a single-wire, half-duplex software UART.

AVR304 describes a half-duplex, interrupt-driven software UART, and AVR305 describes a polled alternative.

AVR307 describes implementing a half-duplex UART using a USI.

All code associated with each app note can be downloaded from Atmel's website.

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


# Question
Title: Capacitive sensor touch detection on wearable
I have a wearable wristband project where I'd like to detect a touch to the outside of the wristband, like a button. However, all my attempts to get this to work with capacitive sensing fail.

The problems accumulate from these aspects:

* Without grounding, the behaviour seems totally arbitrary at times
* I need high response times (12 fps so \< 100ms), so some resistor values keep hitting the timeout limit
* Testing is really hard, as behaviour changes after unplugging the USB connection to the computer. I have a bluetooth connection in the Arduino and debug via bluetooth connection to get a "actual scenario" type of reading
* I've also tried things like setting very short timeouts as well as low sample sizes as well as experimented with different resistors

However, I am not trying to really get any sort of gradual "capacitive sensing" here at all, I merely would need to detect a threshold for "is touching". In fact, the area that the user is touching could even be made out of metal (which it was in my tests so far) and touched directly (so nothing in between finger and metal).

This seems like such an obvious thing to try to achieve, I believe there must be some way to get this done. Any ideas?

# Answer
Expanding on my previous comment:

You can think of capacitive sensing as a form of impedance measurement, even though it's more a threshold detection than an actual measurement. In order to perform an impedance measurement, you have to build a circuit like this:

```
┌─────────┐           ┌───────────┐
│         ├───────────┤           │
│  meter  │           │ impedance │
│         ├───────────┤           │
└─────────┘           └───────────┘

```

The important thing in this figure is that you need **two** electrical contacts in order to close the circuit. The lower contact is often provided by a common ground, but since your wristband is not properly grounded, you will have to provide it by some other means.

My suggestion is to have two electrodes on the wristband: a lower electrode in permanent contact with the user, and an upper electrode that will be the touch button. If both electrodes are exposed metal, then you have a full DC path all around, and this is not “capacitive” sensing any more. Depending on how your sensing is done, this may not be a problem, and it may be detected just like an infinite capacity.

If you want to avoid a full DC path, you can have one of the electrodes covered by a thin layer of dielectric. Or even both, but then you have two capacitors in series and need twice the sensitivity.
> 0 votes

---
Tags: sensors
---


title: LED Cube lighting wrong LEDs randomly

text:
# Question
Title: LED Cube lighting wrong LEDs randomly
So I built my First LED Cube and the thing turns ON!!! Pretty happy about that but here is my problem.

When I try and get the Cube to display say a basic "outline" (a wire form of a cube only the outer most LEDs are on)

The shift registers, that I have daisy chained together, give the correct display 80% of the time, but the other 20% give completely wrong LEDs lighting up.

I have used 4 74HC595 shift registers linked together so I am only using 3 of my Arduino ports to control the 5\*5\*5 Cube. The basic shape is there but the ones that are not meant to be lighting up cause a lot of flickering (or *ghosting*?) in the center of the cube.

I have thought about using pull up or pull down resistors but I find that, when I run my program at a slower rate, the LEDs that are lighting wrongly are lighting up controlled so I think it has to be something with my code or setup.

Has anyone got any experience with LED cubes doing this?

Also I am only using the output enable and disable to make use the wrong this is not displayed when I am shifting the data out, should I be using the clear?

One last thing, does anyone have recommendations for the delay time to let each layer shine for?

My code is below

```
int clockPin = 8;
int dataPin = 7;
int set = 6;

void setup()
{
  //set pins to output so you can control the shift register
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(set,OUTPUT);
}

void loop()
{
      digitalWrite(set,HIGH); // DISABLES OUTPUT
  // level 1 ( top )
      shiftOut(dataPin, clockPin, MSBFIRST, B00000011);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
      digitalWrite(set,LOW);  // enables output
      delay(2);

       digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 2
      shiftOut(dataPin, clockPin, MSBFIRST, B00000101);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);  // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 3
      shiftOut(dataPin, clockPin, MSBFIRST, B00001001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 4
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 5 ( bottom )
      shiftOut(dataPin, clockPin, MSBFIRST, B00100001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);
}

```

Any help would be appreciated

Thanks

# Answer
> 2 votes
A simple way to test for short between LEDs is to write a loop that lights one of them at a time, one right after the other, for 50ms or so. It's relatively easy to notice two LEDs lighting together (a short) or a missing blink in the sequence (an open)~~, assuming you can see all the LEDs at once~~.

Update (6 years later, but hey - I since people still read this question):
I use a sketch that does exactly this to help find shorts and opens when I'm building up a new board. I'd previously implied that you need all of the LEDs attached, but you need at most 2.

On a newly soldered cpu with power & ground (and reset jumpered to ground), holding an LED on each of two adjacent pins will show a shorted pair, while a single LED on one pin will display an open or a short to ground (or to +5, if you orient your LED+resistor that way). I keep a few LEDs with a resistor soldered to the cathode, or ground, leg to use as digital probes.

# Answer
> 1 votes
I have had a similar issues when building this instructable, a 8x8x8 LED cube. Lighting up some of the LEDs caused wrong LEDs to light up simultaneously, even though according to the circuit diagram they where not suppose to. The wrong LEDs that lighted up seemed to be random, though it was reproducible.

The root cause was, after some debugging using a Multimeter's continuity test, that some of the LEDs legs where touching in places they shouldn't, and so the current was flowing where it was not supposed to flow. I strongly recommend to investigate that direction, verifying that Ground paths and Vcc paths are properly isolated from each other. This should be easier to do with a 5x5x5 cube.

About the delay - I suggest you'll take a look at the Arduino code in that instructable - it seems that between the different layers, the code does not use any delay, only between effects. The final result seems to works great.

# Answer
> 0 votes
I have a similar circuit (running a 7-segment display); I don't use reset, and for something like this (since the only state it keeps is reset on sending of new data, which is every frame).

For debugging, I would suggest seeing if there are any patterns. For example, if it doesn't happen on LEDs controlled by the first shift register, then it's likely to be due to the connection between them.

You might try seeing if a pulldown resister (try \>10kOhm) between the data pin and ground has an effect, too.

If you get really desperate, it might be worth getting an oscilloscope - see what is actually happening on the wire.

---
Tags: led
---


title: Arduino Yun doesn't link any library

text:
# Question
Title: Arduino Yun doesn't link any library
I'm writing code for a project with Arduino Yun. My project is quite simple: it takes a picture with a webcam and saves it in a PNG or JPEG file format. I've already installed the uvc driver for Arduino Yun and tested it with my webcam and the fswebcam application. The application saved pictures both in PNG and JPEG format successfully, so I went on and installed the C compiler, make and binutils for Arduino Yun and started to write my own application that would do the same thing (just taking a picture and saving it in PNG format). After writing the code to capture the pixels of the image, I decided to write them down in a PNG file format by using the libpng library available for Arduino Yun through luci web control panel. After installing the package, I included the png.h (using #include png.h) in my source code and wrote the code to write those pixels down in a simple PNG file (thanks to this tutorial: http://www.labbookpages.co.uk/software/imgProc/libPNG.html). What's the problem? It just won't compile! I tried everything and all I got were "undefined reference to 'function name here'" errors. I thought that, maybe, libpng was buggy so I moved to libjpeg. No luck! I get the same errors over and over again. I really don't know what else I can do, I tried everything, it just seems that the Arduino Yun C compiler can't handle "external" libraries. I thank you in advance for any help you'll give me...

Here are the errors I get when I try to compile it using the libjpeg library:

```
/tmp/ccdzMFgN.o: In function `salvaImmagineJPEG':
    ScattaFoto.c:(.text+0x1d9c): undefined reference to `jpeg_std_error'
    ScattaFoto.c:(.text+0x1da8): undefined reference to `jpeg_std_error'
    ScattaFoto.c:(.text+0x1dc8): undefined reference to `jpeg_CreateCompress'
    ScattaFoto.c:(.text+0x1dd4): undefined reference to `jpeg_CreateCompress'
    ScattaFoto.c:(.text+0x1dec): undefined reference to `jpeg_stdio_dest'
    ScattaFoto.c:(.text+0x1df8): undefined reference to `jpeg_stdio_dest'
    ScattaFoto.c:(.text+0x1e2c): undefined reference to `jpeg_set_defaults'
    ScattaFoto.c:(.text+0x1e38): undefined reference to `jpeg_set_defaults'
    ScattaFoto.c:(.text+0x1e54): undefined reference to `jpeg_set_quality'
    ScattaFoto.c:(.text+0x1e60): undefined reference to `jpeg_set_quality'
    ScattaFoto.c:(.text+0x1e78): undefined reference to `jpeg_start_compress'
    ScattaFoto.c:(.text+0x1e84): undefined reference to `jpeg_start_compress'
    ScattaFoto.c:(.text+0x1ed8): undefined reference to `jpeg_write_scanlines'
    ScattaFoto.c:(.text+0x1ee4): undefined reference to `jpeg_write_scanlines'
    ScattaFoto.c:(.text+0x1f10): undefined reference to `jpeg_finish_compress'
    ScattaFoto.c:(.text+0x1f1c): undefined reference to `jpeg_finish_compress'
    collect2: ld returned 1 exit status

```

# Answer
It's not the compiler, it's the libpng package (and other libraries too). It only contains the runtime shared library (`.so`) files. You can't use it for development.

I haven't yet found if it's possible to directly install a full development package or not - normally development for OpenWRT is done outside the low-powered chip using a cross-compiler environment on a PC.
> 1 votes

---
Tags: programming, c, compile
---


# Question
Title: Multiple nodes with the same receiving and transmitting address
I want to make a network with arduinos and nrf24l01 chips. The network will be like this:

* 1 master arduino
* multiple (no specific number) slave nodes

I want all nodes to have the same receiving and the same transmitting address and the master arduino to understand which one send the message from the message itself. For example:

**Master:** Receiving: 0xABCDABCD71 Transmitting: 0xABCDABCD01

**Slave 1** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71

**Slave 2** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71

**Slave 3** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71

**Slave 4** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71

When master send a message, all nodes will receive it. What I want to ask is :

* Is that possible?
* Will there be any problems?
* Is there any other way so I can add more nodes in the future without changing the code?

# Answer
as well as comment #1 the other thing will be the ack packets that the slaves will send back to the master to confirm message recieved. with all slaves sending back a ack at about the same time there will be no way for master to tell which ack is from which client, and thus who needs a retransmit. a way around this is to turn off ack for the clients and make the master transmit max times regardless. there is a rf24 fork that has broadcast mode, the makes it more easy to specify not to wait for ack before retransmitting
> 1 votes

---
Tags: nrf24l01+
---


# Question
Title: changing analog pins data logging using sdFat library
Background:

My goal is to use sdFat library, more precisely AnalogBinLogger example.

I want to log data from changing analog pins for example, I want to log from pin 0 to pin 3 for 5 minutes and then from pin 4 to pin 6 for another 5 mins and then from pin 7 to pin 9 for another 5 mins. that is going to be continuously which means I am going to get rid of the part where you have to enter "r" to start logging.

Regarding the time, I managed to figure it out, I am just using the value of the variable count, if my sampling rate is 1000 samples/sec for example then 5 minutes will be 1000\*60\*5 and the change will be done in this line:

```
if (Serial.available()) {
  // Stop ISR calls.
  adcStop();

```

to

```
if (count >1000*60*5) {
  // Stop ISR calls.
  adcStop();

```

and this worked fine.

My problem is with the changing pins:

```
const uint8_t PIN_LIST[] = {1};

```

I changed this line to

```
uint8_t PIN_LIST[3] = {};

```

First I removed the word `const`, because it's not going to be constant anymore, and I just declared an empty array, and second I am changing the pins in the loop.

Here is the loop after I got rid of doing the serial input:

```
void loop(void) {
int i;
for (i=0;i<=12;i+3)
{
  PIN_LIST[] = {i,i+1,i+2};
  logData();
  Serial.println("done");
 }}

```

The problem is I get this error :

1. AnalogBinLogger.ino: In function 'void loop()':
2. AnalogBinLogger:808: error: expected primary-expression before '\]' token
3. AnalogBinLogger:808: error: expected primary-expression before '{' token
4. AnalogBinLogger:808: error: expected \`;' before '{' token

The line 808 is:

```
PIN_LIST[] = {i,i+1,i+2};

```

So this is the only error, any help please?

The code is so long (800+ lines) if this information is not enough and you need me to explain a part then just tell me.

# Answer
in case someone has the same problem it seems like after you initialize an array this way

uint8\_t PIN\_LIST\[3\] = {};

you won't be able to assign all the values at once:

PIN\_LIST\[\] = {i,i+1,i+2};
instead you assign each individual value

* PIN\_LIST\[0\] = i;
* PIN\_LIST\[1\] = i+1;
* PIN\_LIST\[2\] = i+2;

and now it worked : )
> 1 votes

---
Tags: analogread, data-type, datalogging
---


# Question
Title: Will the arduino power autoselection logic short the regulated 5V and the USB 5V?
From the reference design of the Arduino UNO r3, I find that USBVCC will be connected to +5V via mosfet T1 if Vin is below 6.6V. Doesn't this short the two sources if Vin is just below 6.6V? The datasheet for regulator U1 (NCP1117) mentions input range as low as 6.5V for the 5V version.

This question came to mind when researching if I can simultaneously power the arduino with USB and the 5V-pin. There are many warnings not to do so, and some say its ok anyway. I realise that this will short the USB 5V with my external 5V if Vin/PWRIN is not connected or less than 6.6V/~7.3V, but how bad is that considering that this may happen anyway by design (if the theory above is correct)?

# Answer
> 1 votes
If you connect a power supply directly to 5V pin on gpio it bypasses voltage regulator hence your board may be damaged if the power supply generates spikes. But you can power it using 5V supply directly to 5V pin provided you are using a good quality power supply. If you are supplying the power via Vin or power jack there is additional voltage regulator in path giving extra security. Thus you need more 6.5v so as the output of the regulator is 5v. If you supply 5v to Vin the output is nearly 4v thus the board doesn't get enough power.

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


# Question
Title: Bluetooth Master and Slave to track device's locations
I'm trying to create an app for my science fair that uses bluetooth to track people in a determined place. I was thinking about one Arduino system to receive all the information and transmit through a network and some Arduino slaves to duplicate the signal and cover the hole place.

**Resuming...**

I'll have:

1. Arduino slaves placed all over the place to track people
2. One Arduino connected to the network to receive all the information from the slaves and pass it through the network.
3. Some kind of web app inside the main Arduino with an API to manage the data and make it friendly for third-party apps

I was wondering of what kind of equipment should I buy to make this happen. Thanks!

---

Each cellphone with it's bluetooth enabled will work as a person (sending signal) - my Arduino slaves will receive the signal (find bluetooth around it) and send the device name and signal strength to the arduino master - The arduino master (connected to the network) will interpenetrate the responses and send the results to the built-in web server - Apps will make requests to the web app to get this data and show in a plant where're these people.

Basically it will work like these bluetooth stickers that you can plug in to your keys, phone e etc... and with the app you can search for them in your house via bluetooth from your cellphone.

Here's a better explanation: Link

# Answer
> 2 votes
Bluetooth generally support only one to one connection. Atmost 6 bluetooth can be connected to single module in latest bluetooth version(the basic model probably used by you connects only 1 device). Hence it is not a good idea to use bluetooth. Also if you need a web based platform you should switch to some more powerful platform like raspberry pi, beagle bone etc.

---
Tags: programming, wifi, web-server, bluetooth, networking
---


# Question
Title: How to tell Arduino Uno that I pressed or released a key on PC keyboard over serial?
I want to implement a simple musical keyboard with Arduino using `tone()` and `noTone()` functions, etc.

The desired behavior is:

* While PC and Arduino are connected via USB/Serial...
* ...when I press a key, a corresponding note starts playing...
* ...and if I release that key that note stops playing...
* ...or if I press *another* key, another note replaces the former one.

So, basically, instead of "while key is pressed" logic, I would like to just write a byte to serial when a key is pressed, write nothing while the key is held pressed, and write another byte when that key is released.

I will be using a Python script in the PC, but examples in other languages, or just using a plain serial monitor, are fine.

# Answer
> 0 votes
UPDATE: When I posted this answer I had not yet any knowledge of the Processing Language. If you came to this answer with the same intention I had (the question title), I strongly suggest you to use Processing instead, which has much more straightforward keyboard event capturing and serial communication working out of the box with minimal code.

A question showing this in action is here: https://stackoverflow.com/questions/18366482/processing-to-arduino-with-keyboard

---

After realizing that what I actually wanted was to "capture keyboard events", I ended up using PyGame due to its minimalistic setup. Now I can send whatever I want to the Arduino using PySerial.

PS.: Don't be fooled by the lame aesthetics of PyGame website, it is a very mature gaming platform.

Full code here: https://github.com/heltonbiker/Experiments/tree/master/SerialMusicKeyboard

```
#/usr/bin/env python

import pygame
import serial
import glob
import time

def pygameSetup():
    pygame.init()
    screen = pygame.display.set_mode((468, 60))

    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((250, 250, 250))

    if pygame.font:
        font = pygame.font.Font(None, 36)
        text = font.render("Shut up 'n play yer keyboard!", 1, (10, 10, 10))
        textpos = text.get_rect(centerx=background.get_width()/2)
        background.blit(text, textpos)

    screen.blit(background, (0, 0))
    pygame.display.flip()

def main():

    pygameSetup()

    initialized = False

    while not initialized:
        try:
            serialpath = glob.glob('/dev/ttyACM*')[0]
            ser = serial.Serial(serialpath, 9600)
            initialized = True
            print "serial up"
        except:
            time.sleep(500)
            print "waiting for serial"

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                print event
                ser.write(chr(event.key))
            elif event.type == pygame.KEYUP:
                ser.write(chr(0))

if __name__ == '__main__':
    main()

```

# Answer
> 1 votes
As mentioned by Spiked3 there are a few ways to hit the ground running with C#.

Firstly, as detailed by Majenko, you will need an application running on your PC and some code on the Arduino to interact with this. For the desktop application, the two easiest ways to get started with C# are with WinForms, or XNA/MonoGame. WinForms is targeted at Desktop application development; think legacy desktop apps. Although it is not the current defacto standard (replaced largely by WPF) it is very simple and akin to Swing in Java to use. MonoGame and XNA are targeted at video game development. The latter would be my preference as it lends itself more towards real time applications, and has a game loop much like the Arduino so it is very easy to start using. The caveat is that there is more setup involved, but you will probably find this the friendliest and best supported.

Firstly, The Code! So for the Winforms Route, We have something like this:

```
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            Debug.WriteLine(" Key Up! ({0})", e.KeyCode);

            // TODO: Talk with Arduino
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            Debug.WriteLine(" Key Press! ({0})", e.KeyChar);

            // TODO: Talk With Arduino
        }
    }
}

```

To get to this point, fire up a new winforms project, and open up the 'Form1' code (the default window which is added to the project) add the methods as outlined above. You will need to go to the designer afterwards and add events for on KeyPressand on KeyUp to tie these functions to the Window. You can do this by clicking the Window, then opening the Properties Panel, and then clicking the lightening bolt. You will see a list of event names; find the corresponding events (Key Press and Key Up) and associate them with these methods.

From here, you can perform some logic when a button is either pressed or released.

The monogame or XNA approach is a bit simpler to follow as there is no hidden magic; but may be more intimidating if you're not familiar with C# and the project type.

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;

namespace GameName1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;

        KeyboardState currentState;
        KeyboardState previousState;

        public Game1() : base()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            // Get state management started
            currentState = Keyboard.GetState();

            base.Initialize();
        }

        protected override void Update(GameTime gameTime)
        {
            // Listen for exit command
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // Update the state of your keyboard object
            previousState = currentState;
            currentState = Keyboard.GetState();

            // Detect Keypress of key 'F'
            if (currentState.IsKeyDown(Keys.F) && previousState.IsKeyUp(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Pressed! ({0})", 'F');
                //TODO Talk to Arduino
            }

            // Detect Keyrelease of key 'F'
            if (currentState.IsKeyUp(Keys.F) && previousState.IsKeyDown(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Released! ({0})", 'F');
                //TODO Talk to Arduino
            }

            base.Update(gameTime);
        }
    }
}

```

In either case, you will need to get yourself set up first. Get a compy of Visual Studio Community from the link below, and install MonoGame if desired. Then do some C# tutorials to get comfortable in your new environment.

Lastly, you will want to talk with your Arduino. This can be done by implementing a compatible Serial interface between your desktop application and your Arduino. See the tutorial below to get started!

I hope this information is useful. There is a very broad range of topics mentioned here, and it may seem overwhelming at first - but C# is a very idiosyncratic language in that it permits rapid development in many different scenarios, and I think that you will find it rewarding to conquer the learning curve.

# Answer
> 0 votes
You need to come up with a protocol. Then you need to write the PC software. The PC software will monitor the keyboard, and when you press a key it will send a certain signal through the serial port. When you release the key it will send a different signal.

How you arrange that is entirely up to you.

You might implement a protocol that sends something like:

```
b4
c4
d3
off
c3
f3
off
g4
off

```

Where the first letter is the note, the second letter is the octave to play that note in, and the word "off" is to stop playing.

I don't have a clue (and probably few people here do) how you'd program the PC end in Python. It most likely depends on what platform you're working on as to what kind of interface you can build.

# Answer
> 0 votes
It sounds really simple, but as I think about it, the python twist makes it near impossible.

First the simple part. What you are describing is very close to the MIDI spec. It define a sequence of character for note on/note off events over serial. I'm rusty but it something like this x'90' + chan1..16, note, velocity (3 bytes for note on) and x'80' + chan1..16, note, velocity (3 bytes for note off). (spec)

Firmata took that idea, and turned it into a remote arduino protocol, where instead of a note, a pin number is used (eg pin on/pin off) and you could dig into the firmata that is included with Arduino for some ideas.

The hard part is the keyboard. I use a function getch, that I define myself based on whether the script is running on a POSIX host or not (although that is technically inaccurate). It is described at https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user but unfortunately it only waits for a keystroke and provide no information about a key release. You are going to have to dig deep and probably write some platform specific code, maybe even a C .DLL, to get that kind of interaction in python. Handling key down/up is trivial in any language but python (for windows anyhow, dont know about \*nix)

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


title: Function generator with Arduino Nano

text:
# Question
Title: Function generator with Arduino Nano
I'm trying to convert the project here to an Arduino Nano.

I scaled the waveforms from 12 bit to 8 bit values. I replaced the `analogReadResolution` and `analogWriteResolution` calls with `pinMode(10, OUTPUT)` and `pinMode(11, OUTPUT)` and changed the two `analogWrite` calls to write to pins 10 and 11. Otherwise the program is unchanged.

My thinking (and this is where my poor electronics skills come into play) is that I just need a simple low pass filter to convert the PWM into the appropriate waveform (which, at startup, ought to be a sine wave on both pins). According to the article, the frequency generator tops out at 170Hz. I figure the PWM signal is going to be significantly higher than that, so I use R=3.3K and C = .1uF for my RC filter which ought to give me a -3dB at about 480Hz, but what I'm seeing on my scope is a mess. Not a stable signal at all.

This is the waveform I'm seeing on my scope:

Can someone educate me?

Update: BTW, this is the initial waveform which ought to be a sine wave.

# Answer
What you're proposing can work, but the PWM frequency needs to be *much* higher than the frequency you're trying to generate. If you look at the PCMAudio sample you'll see that it tunes the PCM frequency almost as high as it will go.
> 2 votes

# Answer
The PWMs on pins 10 and 11 of the Arduino Nano run at 488 Hz. That's what you are seeing on the scope. The code you are using was meant for an Arduino Due, which has real digital-to-analog converters.

**Edit**: You can tune the PWM to run as high as `F_CPU/256` by reconfiguring the timers 1 and 2 to “fast PWM” mode, instead of phase correct PWM, and setting their prescalers to 1 instead of 64. This should raise the PWM frequency to 62.5 kHz, given that the Nano has a 16 MHz clock.

The following code should do exactly this. You can put it somewhere inside your `setup()`. **Warning**: I have not tested this code. This will change the PWM frequency on pins 10 and 11, but also on pins 3 and 9, which share the same timers. It will probably break the `tone()` Arduino function.

```
// Set PWM frequency to 62.5 kHz on pins 3, 9, 10 and 11.
TCCR1A = 1<<WGM10;
TCCR1B = 1<<WGM12 | 1<<CS10;
TCCR2A = 1<<WGM21 | 1<<WGM20;
TCCR2B = 1<<CS20;

```
> 2 votes

---
Tags: arduino-nano
---


# Question
Title: How do I use the prototyping area on a SparkFun MicroSD Card shield?
I'm having trouble figuring this out. I'm using this popular shield: https://www.sparkfun.com/products/12761

There is a breadboard area in the middle of the shield. But what confuses me is the lack of lines (order). On normal breadboards you can tell which row would be at the same voltage. If I wanted to put something on this prototyping area, how would I connect it? For example an LED, which would have a resistor attached to the positive side going to 5V and the negative side going to ground?

# Answer
> 2 votes
This type of board, "pad per hole", has no pre-made interconnects. If you use thin enough wire sometimes you can push two pieces of wire into the same hole before you solder, say a resistor lead and another wire to connect to the next component. You can also solder an interconnect wire to the protruding leg of a DIP chip. You can make a buss for ground or 5v by assigning a whole row for that purpose, on the top side wire everything that needs to connect to that buss, and on the bottom side solder a straight piece of bare wire to all those wire ends in that row.

---
Tags: arduino-uno, shields, sd-card
---


# Question
Title: How can I run two Arduinos in sync for video generation?
I was thinking about building a video circuit that uses two Arduinos (maybe more) to generate video using `NTSC` and the `AD725`. Although, VGA might be nice if possible.

Anyway, the idea is to use one Arduino as the background layer and the other one as the sprite layer (overlay).

Then, instead of masking the sprite data and having more cpu time, I was thinking of running the signals through a mux. So that when drawing background data and no sprites (per scanline) then pipe the signal to the AD725. But when there is a sprite mid-line, then the \>0v signal of the sprite Arduino would cause the mux to pipe its contents through to the AD725.

Or, something similar.

I believe many arcade boards from the 80's did this. Many of them had entire "sprite boards" attached and the signals would mix. Each layer would have it's own RAM and not be aware of the other layer.

But to do this, I would have to keep the Arduinos sync'd perfectly.

So that's my question. How I can do this?

Oh, my Arduino of choice in the beginning would be the UNO but I have others (DUE, Teensy3.1, etc.) if that would be a better fit.

Thanks.

# Answer
> 1 votes
Arduinos are great for many things, and I think the idea of synchronizing two or more Arduinos might have several applications. However, if I wanted to generated VGA or NTSC video, I would look at the Parallax Propeller as another option.

Many people use the Parallax Propeller to produce VGA video, keeping its 8 processors working in parallel.

# Answer
> 1 votes
I would take a look at MREtv which seems to promise all that you want to do, with just one arduino. This might not be the answer you're looking for, but getting threads to sync is a pain in the rear end, see this for explanation of why threads are a pain.

Now back on topic, it seems like MRETV might off what you want to do, and it can do some pretty impressive things from what I read in the arduino. You might need to modify the library a bit, but it offers already implemented encoding, so that is a plus.

http://www.instructables.com/id/MRETV-Video-Stereo-Sound-and-much-more-from-a-s/

# Answer
> 0 votes
You would need to use interrupts on the "sprite arduinos" to get the timing very exact - the "background" arduino would need to send signals sync signals (horizontal and vertical) to the sprite arduinos. The sprite arduinos would then need to keep track of which line it is on, and time exactly how far along the line it is. You will need a circuit to either allow the incoming signal through (I believe the arduino will be too slow to pass it read it, then write it);

alternatively, have multiple (still synchronized) sources, each indicating if they want to be on the screen; then one that takes the "I want to be on the screen" signals, make a decision, and connect the appropriate one (via a transistor).

A basic tutorial on TV out is found at: http://playground.arduino.cc/Main/TVout

# Answer
> 0 votes
Just a thought, you could try synchronizing micros() / millis() between Arduinos... \[ https://aaka.sh/patel/2013/12/23/synchronizing-micros-millis-arduino/ \]

Over time you could set instructions/commands to execute at certain time intervals on target arduinos using something as simple as a 2 wire serial setup \[ http://arduino.cc/en/Tutorial/MasterReader \]

---
Tags: arduino-uno, timing
---


# Question
Title: Reusing LED from RC helicopter controller
I have an old RC helicopter controller, but not the helicopter. I recently purchased an Arduino Uno and would like to do something with LEDs(beside the on-board one built-in). Can I use an LED from the controller, that is already soldered in, cut it free and plug into my breadboard.

*Side Note*

I have no experience in soldering and don't own a soldering iron.

# Answer
Yes, you can. For convenience, cut a bit shorter the lead on the side of the package where the flat part is so that you can identify the leads easier.
> 1 votes

# Answer
Yes you can. Make sure you have a resistor in series with your led. It is much, much better to guess and use the wrong resistor, than not to put a resistor in at all. I use http://led.linear1.org/1led.wiz to calculate my resistor. Your source voltage will be 5v. Each thing you have to fill has help on what value you're likely to want to put here.

It doesn't matter which side of the led you put the resistor.

If you can cut the led out, it should be fine, so long as you have long enough legs to go into the breadboard.
> 0 votes

# Answer
Ignacio's drawing shows you how to connect a LED. If you don't have any soldering tools you can use a **solderless breadboard**. This small one from Adafruit is ideal for small circuits:

(They exist in all sizes from very small to very large). The holes in each 5-hole row are all internally connected.

The problem with cutting the LED from the board may be that the remaining wire length is too short to fit in the breadboard. (You'll need at least something like 6 mm.) LEDs are a nice way to start with electronics, since you need minimal part count to make something visible. If you can't cannibalize the LED from the controller, just buy one from your local electronics shop. They're dirt cheap.
> 0 votes

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


# Question
Title: Using Browser window to display sensor values in realtime
The title pretty much says it all:

What would be the most obvious way to setup the Arduino (shields?), the Sketch (libraries?) and PC (webserver, ajax, plain html?) so that I get the following system working:

1. I open some page in a browser. The page has some labels/fields/values;
2. I power up Arduino, which is connected to some sensors (or even potentiometers);
3. The sensor values display keep being constantly updated in the page, with a sensible refresh rate (the fastest as possible, as to control some browser-based game for example);

The fundamental idea here is to use the Browser, and not some other GUI toolkit, or Processing, or the command line.

# Answer
> 2 votes
The most obvious way? Not what is the best way? It is a subjective question. The most obvious way would be to do it in a way you know how to. I am sure there are at least 20 ways to do this.

The way I know, and that I would do it is write a PC service that establishes serial communications with the Arduino, transfers data using JSON, and presents a web server I could connect TCP to. Knowing C# and using existing code I have, it would take less than 15 minutes.

# Answer
> 1 votes
I guess there are a number of ways to tackle the problem. Using the Ethernet shield is probably the most intuitive option, but this isn't something I have explored in too much detail - I would usually opt for other micros at this stage and I am confident you will get an answer from someone else detailing this.

To get the most out of the Arduino and leverage what the Arduino is good at, I would probably make a C# console application or Windows service which communicates with the Arduino over serial, and use the 'System.Web.Http.SelfHost' assembly to make the data available through a RESTful web service which a html page could use JQuery to poll for information. It would be pretty easy to extend this to push the data to the page using SignalR.

The fundamental drawback of this architecture is that your device isn't serving the website, so these must be hosted somewhere else, or run from flat files. Also a PC must be attached to facilitate the data transfer over serial and provide the web service.

To get started you will want to familiarise yourself with c# and the SelfHost module, and WebApi 2.0 if you aren't already, this is all covered here, and of course you will need Visual Studio Community edition or greater to start creating projects.

Next, write a Windows Service or Console Application which implements an object model holding your data, and updates this periodically with the Arduino via serial.

The Self Host module is pretty incredible in that it allows you to add a web interface to any .Net application very easily, and directly manipulate your model. The tutorial linked above is very easy to follow, and can easily be adapted.

For testing and development purposes, I would highly recommend Postman, which can be used to test and trigger your API endpoints. It's a comprehensive and well polished tool specifically for this job.

In terms of the network logistics, I would then use JQuery to make periodic posts to the self-host service in the same fashion that Postman would. You can use the function call backs to trigger successive queries on completion to maximise the data refresh rate without causing excessive consumption. A time interval would be another option you could consider between requests, and is discussed in this article on polling.

The typical Ajax request structure would look something like this:

```
$.ajax({
    url: 'yourApiMethodAddress',
    type: 'get',
    error: function (jqXHR, status, ex) {
        /* Something went wrong. Maybe you could stop
           the update process and show a message and
           a retry button. */
        console.log("Error: " + status);
        console.log(ex);
    },
}).done(function (data) {
    // Update page with information stored in 'data'. View console for hints
    console.log(data);
});

```

I would recommend using Twitter Bootstrap in your webpage file to pretty things up and maintain readability. Don't forget to include the javascript and css files for both Bootstrap and JQuery in your html document (if used).

In summary, I would recommend implementing an application which runs on a computer attached via USB/Serial to the Arduino, with the .Net Self Host module utilised to provide a RESTful API. This API can then be polled from a html page using javascript and JQuery to obtain the information and update the page.

I hope this information helps, and as there a lot of moving parts I didn't provide many code examples for simplicity sake. If you find this useful and would like more information adding, mention it in the comments and I will update my answer.

# Answer
> 0 votes
Your question actually exists out of multiple questions...

**1. How to connect arduino to network/internet.**

I would suggest using a cheap WIFI module or Ethernet module

**2. How to send values from arduino over ethernet.**

The fastest would be using a direct connection (TCP/IP or UDP?)

**3. How to receive values from arduino over ethernet on a PC.**

The problem with this would (I think) be that a webserver usually does not enable a direct TCP/IP connection, but instead would use HTML to transfer data/webpages. But I'm not a web-developer at all. I would create a dedicated program in processing/c++/python or something similiar.

---
Tags: ethernet
---


# Question
Title: Issues with PIR Sensor triggering by itself
I am currently working on my first Arduino project and I am having some issues that I am seeking help with. The robot I am building must have human following capabilities and to do so I am using 3 PIR sensors (One on the front, one on the left and one on the right) and an Ultrasonic Sensor so the robot won't run into a wall or a person it is following. To handle the motors I am using the Adafruit Motor Shield (V.1)

The way I am trying to make this work is as follows.

The robot's main PIR sensor is the one attached to the front. If this sensor reads HIGH then the robot will move forward while checking its distance from any objects in front of it in which case it stops and reverses until there is at least 30cm of space between itself and the object in front. The radius of this sensor had to be reduced so that it only reads HIGH if the person is exactly in front of the robot. This was done using carton paper and black duct tape. Two images of this have been provided below in case this has something to do with my issue.

The other 2 PIR sensors attached to the sides will tell the robot if it should turn left or right. If the left PIR is triggered then the robot will start turning left and keep doing so until the front PIR finally reads HIGH, and then it moves forward. The same thing is done with the right PIR except that it moves right. These PIR sensors are handled using interrupts on the Arduino Mega 2560 board as can be seen in the provided code.

The code I am using can be found below:

```
#include <AFMotor.h>
#include <NewPing.h>

#define trigPin 34
#define echoPin 32

NewPing sonar(trigPin, echoPin);
int minimumDistance = 30;
int currentDistance = 0;

int calibrationTime = 60;
int redLED = 22;
int greenLED = 24;

int PIR = 26;
volatile int PIR_val = 0;
int PIR_left = 19; // (interrupt 4)
int PIR_right = 18; // (interrupt 5)

AF_DCMotor motorL(1, MOTOR12_64KHZ);
AF_DCMotor motorR(2, MOTOR12_64KHZ);

void setup()
{
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);

  pinMode(PIR, INPUT);
  pinMode(PIR_left, INPUT);
  pinMode(PIR_right, INPUT);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  digitalWrite(redLED, HIGH);
  // Calibration for PIR sensors
  for (int i = 0; i < calibrationTime; i++)
  {
    delay(1000);
  }
  digitalWrite(redLED, LOW);
  digitalWrite(greenLED, HIGH);

  attachInterrupt(4, turnLeft, RISING);
  attachInterrupt(5, turnRight, RISING);
}

void loop()
{
  delay(50);
  currentDistance = sonar.ping_cm();

  if (currentDistance < minimumDistance && currentDistance > 0)
  {
    moveBackward();
  }
  else
  {
    PIR_val = digitalRead(PIR);

    if (PIR_val == HIGH)
    {
      moveForward();
    }
  }
}

void moveForward()
{
  motorL.run(FORWARD);
  motorL.setSpeed(180);
  motorR.run(FORWARD);
  motorR.setSpeed(200);
}

void moveBackward()
{
  motorL.run(RELEASE);
  motorR.run(RELEASE);
  motorL.run(BACKWARD);
  motorL.setSpeed(190);
  motorR.run(BACKWARD);
  motorR.setSpeed(225);

  while (currentDistance < 30 && currentDistance > 0)
  {
    currentDistance = sonar.ping_cm();
  }

  motorL.run(RELEASE);
  motorR.run(RELEASE);
}

void turnLeft()
{
  motorL.run(BACKWARD);
  motorL.setSpeed(150);
  motorR.run(FORWARD);
  motorR.setSpeed(150);

  // While front PIR is reading LOW
  while (PIR_val == LOW)
  {
    PIR_val = digitalRead(PIR);
  }
  // After front PIR reads HIGH
  moveForward();
}

void turnRight()
{
  motorR.run(BACKWARD);
  motorR.setSpeed(150);
  motorL.run(FORWARD);
  motorL.setSpeed(150);

  // While front PIR is reading low
  while (PIR_val == LOW)
  {
    PIR_val = digitalRead(PIR);
  }
  // After front PIR reads HIGH
  moveForward();
}

```

The first issue I am having is that as soon as the PIR sensors are done calibrating, the robot starts moving forward by itself. Even if I leave the robot alone inside a room with the door closed, after the calibration time passes the robot automatically moves forward on its own.

The other issue I am having is also with the front PIR sensor. While the robot is turning and looking for a human as seen in the 'turnLeft()' and 'turnRight()' methods, the robot will sometimes move forward toward a random direction instead of towards me.

I have already tried replacing the front PIR sensor twice and the sensor itself does not seem to be the issue.

The PIR sensors I am using are the 'HC-SR501' model. For all PIR sensors, the delay time is set to the lowest possible time (5 seconds) and the sensitivity is set to full.

I welcome any input or suggestions whatsoever. If you would like me to provide any additional information about this project please ask and I will do so.

# Answer
> 0 votes
Try:

* turn sensor OFF when robot is moving
* turn sensor ON while robot is standing still
* look for some prey
* repeat from 1 one

Same schema goes with rotating :

* rotate to some angle,
* stop rotation
* detect

xD I was wondering bout it too, but only thinking, not implemented yet!

I think that simple is best, but something advanced with faster reaction would be better!

---
Tags: programming, arduino-mega, sensors
---


# Question
Title: Running a servo and tone() won't compile? "multiple definition of `__vector_32'"?
Im using Spark fun pro micro:https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

I am controlling a servo motor which reads its data from a pot connected to A0, and then writes to the servo on D9.

A speaker is connected to A5. Im using tone()

If I comment out the servo part of it, the tone() works out just fine and vise versa.. The error message I get is "multiple definition of \`\__vector\_32'"

Got a clue??! Thanks!

# Answer
> 1 votes
The link you provided shows a board built around the ATmega32U4. On this chip, “\__vector\_32” is the low-level name of an ISR (Interrupt Service Routine) named “TIMER3\_COMPA\_vect”. Your problem comes from having two libraries trying to define an ISR for the same interrupt, which is generated by the timer 3 of the chip. Merging the ISRs is actually unlikely to work, because since each library configures the timer in its own way, the timing of the interrupts will be wrong for at least one of the libraries. You really have to use different timers.

On my copy of Tone.cpp I can read:

```
#elif defined(__AVR_ATmega32U4__)

#define AVAILABLE_TONE_PINS 1
#define USE_TIMER3

const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 3 /*, 1 */ };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ };

```

which shows that the code is configured to use timer 3 on this particular chip. In Servo.h I have:

```
#elif defined(__AVR_ATmega32U4__)
#define _useTimer1
typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ;

```

which shows it should use timer 1, and not conflict with Tone.cpp.

It seems we have different versions of Servo.h. Mine is from Arduino 1.0.5. You may try to fix the problem by modifying the relevant section of either file (just after `#elif defined(__AVR_ATmega32U4__)`) and have them use different timers.

**Edit**: It appears this issue has already been fixed... on June 2012! See this diff: Avoid TIMER3 conflict with Servo and tone() on the Arduino GitHub repository. The simplest fix in your case may be to just upgrade your Arduino software. You could also manually apply that (really small) diff to your current copy.

# Answer
> 2 votes
The problem you're seeing arises when two codes (e.g. libraries) try to use the same interrupt.

If you look at the source code of the two libraries, you'll find that they both make use of a number of ISRs (interrupt service routines): `Tone.cpp` uses

```
ISR(TIMERn_COMPA_vect) {...}

```

for n = 0..5, while `Servo.cpp` uses

```
ISR(TIMERn_COMPA_vect) {...}

```

for n = 1, 3, 4, 5.

Now what happens when you compile this code is that they both libraries generate identical symbols (the `__vector_32` part) which then clash when the compiled code is linked to give the final binary you'd upload to your Arduino.

There is no simple way around this because the interrupt handlers need to be registered at certain fixed positions in flash memory and there can only be exactly one interrupt handler for each of these slots (these slots are simply entries in a look-up table with the addresses of the interrupt handlers in flash, cf. Table 9-1 in the datasheet).

Now to solve this problem you would need to find a way to either merge the interrupt handlers of the two libraries (not so easy I guess), or make them use different interrupts (without looking further into what options the pro micro offers, the code suggests that there are several TIMER interrupts which could be assigned one to the Servo, one to the Tone, *if* that is supported by the hardware).

In any case you'll not get around modifying the libraries (or writing your own code for one functionality or the other).

# Answer
> 1 votes
The libraries are not compatible with each other, welcome to Arduino.

I dont use either library, and usually avoid libraries altogether because of things like this. I will assume you want a solution, not a clue.

The quickest route is to pick one of the libraries, and globally modify \__vector\_32 to something like \__vector\_32x.

That probably is not the best solution but the quickest. The best solution would be to understand how it is used in both libraries, and modify them to work together. In the end it might be as simple as wrapping it with some #ifdef, but that requires understanding it enough to get to that conclusion, and it will take some time. Maybe someone else already has.

---
Tags: servo, arduino-pro-micro
---


title: How can I play audio from an SD card?

text:
# Question
Title: How can I play audio from an SD card?
**What is the best / simplest way to play audio files from an SD card?**

I'm currently working on a sound board, where each button plays a different sound. But I have yet to find the right combination of shields / hardware to do this efficiently.

Is there a shield that supports this directly (SD card -\> speaker)? Note that I also need additional pinheads for my buttons to connect to. I think I will be using the Arduino Mega for that purpose.

# Answer
There are several audio products/shields. Because you mention "speakers", the first one listed can come with an on-board amplifier to drive speakers directly. Most shields just give line-out to drive a pre-amp.
> 2 votes

# Answer
```
#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
#include <TMRpcm.h>           //  also need to include this library...

TMRpcm tmrpcm;   // create an object for use in this sketch
char mychar;

void setup(){

  tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can      be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
     }
  tmrpcm.play("beware.wav"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){

  if(Serial.available()){
    mychar = Serial.read();

    if(mychar == 'o'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("helpyou.wav");
} else if(mychar == 'r'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("chortle.wav");
} else if(mychar == 'q'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("helpyou.wav");
} else if(mychar == 'p'){
  tmrpcm.play("beware.wav");
}
else if(mychar == 'w'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("impresiv.wav");
}
else if(mychar == 't'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("seekyoda.wav");
}
else if(mychar == 'y'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("sensefear.wav");
}
else if(mychar == 'u'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("strongami.wav");
}
else if(mychar == 'i'){ //send the letter p over the serial monitor to start playback
  tmrpcm.play("whyhere.wav");
}
  }

}

```

This code should be helpful. Make sure you have a SD card reader. You must also hookup the card reader:

3.3v goes to 3.3v on the Arduino UNO (for power)

GND goes to Ground on Arduino UNO

D0 goes to pin 12 on Arduino UNO

D1 goes to pin 11 on Arduino UNO

CLK goes to pin 13 on Arduino UNO

D3 goes to pin 10 on Arduino UNO

Lastly, download an arduino library so it can play audio files.

https://github.com/TMRh20/TMRpcm
> 0 votes

---
Tags: arduino-mega, sd-card, audio
---


title: Verify a code for Traffic Signal

text:
# Question
Title: Verify a code for Traffic Signal
```
void setup() {
  pinMode(13, OUTPUT);  // Red
  pinMode(14, OUTPUT);  // Yellow
  pinMode(15, OUTPUT);  // Green
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(14, LOW);
  digitalWrite(15, LOW);  // Stop
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, HIGH);
  digitalWrite(14, HIGH);
  digitalWrite(15, LOW);  // Listen
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, LOW);
  digitalWrite(14, LOW);
  digitalWrite(15, HIGH);  // Go
  delay(20000);            // Wait 20 seconds
}

```

How good is this code and is there any error ?

# Answer
> 1 votes
There is nothing wrong with your code. But it could use some cleaning to make it efficient.

The code at the moment will be 'deaf' to any user inputs for twenty seconds between light changes.

This can be fixed by using a timer interrupt and changing the lights every 20 seconds and listen for other inputs or do other things. You can use the arduino timer library, this is well documented and you should be able to find examples of its use. Basically you would monitor a variable until it reaches a point and then trigger the lights.

The other option would be to use the `millis()` and every 20 seconds change a light, but do stuff between those 20s. This can be done like this:

```
unsigned long previousMillis;  //hold the previous time
unsigned long currentMillis;   // hold the current time

long threshold = 20000;
int count = 0;

int pins[] = {13, 14, 15};

//setup code stuff

//put the following at the top of loop()

currentMillis = millis();

if(currentMillis - previousMillis > threshold){

    previousMillis = currentMillis;

    for(int i = 0; i < 3; i++){
    digitalWrite(pins[i], LOW);  //turn off all

    }

    if(count > 2) count = 0;

    digitalWrite(pins[count], HIGH);

    count++;
}

```

# Answer
> 0 votes
I have a similar requirement, this gives you a little more flexibility , My traffic light code is controlled by a PIR outside my door , if the PIR detects an individual the lights turn to stop when the PIR clears the lights turn to green.

the code and hardware are still in the test phase.

```
#include <**EasyTransfer**.h>

int D_Status_Word = 0;
int Status_Word = 0; //sets all bits to  zero
int Light_Threshold = 150; //the light level that constitutes an unusual entry
int Active = 0;
int Passive = 100;
int Counter = 100;
int Green_Pin = 7;
int Amber_Pin = 8;
int Red_Pin = 9;
int Photocell_Pin = 1;     // the cell and 10K pulldown are connected to a0
int Photocell_Reading;
int Sensor_Frequency = 0;

struct SEND_DATA_STRUCTURE {
  //put your variable definitions here for the data you want to receive
  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
  int Out_Word;
  int LDR_Level;
};

SEND_DATA_STRUCTURE My_Tx_Data;

//create an object for themessage
**EasyTransfer** ETout;
int D_Sensor_Pin [] = {
  2, 3, 5, 6
};
// pin hallwaypir, 3 doorpir, 5 door sensor, 6 hallpir

void setup() {
  **Serial**.begin (9600);
  // put your setup code here, to run once:
  ETout.begin(details(My_Tx_Data), &**Serial**);
  for (int i = 0; i <= 3; i++)// read the two state sensors
  {
    pinMode(D_Sensor_Pin [i], INPUT);
  }
  pinMode(A1, INPUT);//set the analoge u ldr pin ot input mode
  pinMode (Green_Pin, OUTPUT);
  pinMode (Amber_Pin , OUTPUT);
  pinMode (Red_Pin , OUTPUT);
}

void loop() {
  Scan_Sensors();
  if (D_Status_Word != Status_Word)
  {
    Sensor_Frequency = Active; // high frequency sampling because a sensor has activated
    //send a data packet to the mega with mem card via serial.
    Send_Data_Packet();
  }
  if (bitRead (Status_Word, 1) != bitRead (D_Status_Word, 1))
  {
    if ((D_Status_Word, 1) == 1)
    {
      Traffic_Light_Stop();
    }
    else
    {
      Traffic_Light_Go();
    }
  }
  Status_Word = D_Status_Word;

  delay(Sensor_Frequency);// 1000= waits for a second
}

void Scan_Sensors()
{
  byte readings = 0;
  Photocell_Reading  = 0;
  for (int i = 0; i <= 3; i++)// read the two state sensors
  {
    bitWrite(readings, i, digitalRead(D_Sensor_Pin [i] ));
  }
  //test to see if any sensors have trivggered (readings>0)
  if (readings > 0)
  { // a 2 state sensor has triggered, reset the Counter to 100
    Counter = 100;
  }

  //read threshold sensors
  Photocell_Reading  = analogRead(Photocell_Pin);
  {
    bitSet(readings, 4); // 4 becaus there are 4 2 state sensors (0 to 3)
    //we write 1 because thelight is below the threshold
    **Serial**.print ("photocell Reading = ");
    **Serial**.println(Photocell_Reading);
  }
  D_Status_Word = readings;
  Counter -= 1; //decrement the Counter
  if (Counter <= 0)
  { //the Counter has counted 100 scans since a 2state has triggered
    //rest freqenvcy to Passive
    Sensor_Frequency = Passive;

  }
}
void Send_Data_Packet()
{
  My_Tx_Data.Out_Word = D_Status_Word;
  My_Tx_Data.LDR_Level = Photocell_Reading;
  **Serial**.print ("photocell Reading = ");
  **Serial**.println(Photocell_Reading);
  **Serial**.print ("status word = ");
  **Serial**.println(D_Status_Word);
  ETout.sendData();
}

void Traffic_Light_Stop()
{
  //lights turn from green to yellow to red
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, HIGH);
  digitalWrite (Red_Pin, LOW);
  delay(750);
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, LOW);
  digitalWrite (Red_Pin, HIGH);
}

void Traffic_Light_Go()
{
  //lights turn red to red and yellow to green
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, HIGH);
  digitalWrite (Red_Pin, HIGH);
  delay(750);
  digitalWrite (Green_Pin, HIGH);
  digitalWrite (Amber_Pin, LOW);
  digitalWrite (Red_Pin, LOW);

}

```

# Answer
> 0 votes
There is nothing wrong with the code that I can see although you do have some redundant statements: When you go to "Listen" you set the red and green pins high and low respectively, but they are already high and low from the previous state. Not a big issue, being verbose adds clarity so there is some argument for leaving it as is.

I would consider using #define macros to number the ports and set the delay times. This adds readability and also means you can make changes easily without having to search through the code and match up appropriate instances of the port number that you want to change, for example:

```
#define RED_PIN 13
#define DELAY_BETWEEN_CHANGES 20000
...
digitalWrite(RED_PIN, HIGH);
delay(DELAY_BETWEEN_CHANGES);

```

This also means that you can get rid of comments in your code as it becomes pretty self explanatory. I personally believe that comments are bad. If you write code and put a comment explaining what it does, when you have to modify the code you also have to modify the comment. Make the code understandable in the first place, no need for comments.

Final point (not related to code): What happens after "Go"? I'm from the UK so we have another phase after Go. It reminds me of an old driving test joke: Instructor: What is the sequence of traffic lights? Student: Red, red and amber, green. Instructor: What comes after green? Student: How would I know? I've always gone by then!

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


title: Arduino Uno questions

text:
# Question
Title: Arduino Uno questions
Anyways cutting to the chase I am pretty good at C++ as I have been doing it for over 6 months pretty much 1-2 hours each day and I am looking for cool things to use my knowledge on ,I have heard of the Arduino's but the problem is I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions. 1. Do I need to have a background in engineering to use an Arduino. 2. Is there any cheap alternatives to the quite costly starter kit.

# Answer
> I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions. 1. Do I need to have a background in engineering to use an Arduino.

The answer to your first question: it depends on what you want to achieve, and how much time you are willing to spend stuck.

A bit of electrical/electronic background can help you a lot. Basics such as Ohm's, Kirchhoff's. Semiconductor devices (diodes, transistors, OpAmps). It's very useful to understand what kinds of test&measurement equipment exists and how it can be used.

You can pursue C++ for 6 months 1-2 hours a day. You can pursue electrical knowledge in the same way as well. A solid book like "The Art of Electronics" will help you a lot (doesn't have to be the latest edition).

Then you can pursue more exciting things: sensors (for example).
> 2 votes

# Answer
If you are the "hacker" type (i.e. you are good at self-learning and you like to explore things) even if you are an absolute newbie I advice *against* those starter kits. They usually contain lots of overpriced parts, which you can get much more cheaply ordering directly to digikey, mouser or the like for your country (or maybe at your local shop).

On the other hand I strongly recommend buying an original Arduino board (for beginners an Arduino UNO is optimal, IMO, and comes at a reasonable price around 20-25EUR). This because the quality is guaranteed and you risk less problems. There are really good clones out there, but also tons of crappy ones, so I'll leave them to when you get more experience. Nothing is more frustrating while learning that wasting hours to debug a supposedly idiotproof project only to discover that *it was not your fault*, but the board's!!!

Note: if you go for an Arduino UNO choose the version with a socketed plastic DIP package MCU (that big, long chip with two parallel rows of pins), instead of the SMT version, using an MCU packaged as a tiny plastic square. The version with the socket may come handy if you accidentally fry the MCU: a new one will cost you less than 4EUR and it's easily replaceable (it is not soldered on the board). The SMT, on the other hand, is a PITA to replace and you'd need special hardware to do that. Moreover, the socketed version can be used as a "poor man's" programmer for ATMega328 MCUs. You program it on the board and then place it on an external circuit.

If you are an absolute beginner at EE, you can find lots of beginner tutorials on the Internet. Concentrate on key basic aspects. Most electronic projects can be handled with less math than you expect. You absolutely need to know Kirchhoff's laws and Ohm's law and a couple of related formulas if you want to begin *learning* electronics, but nothing more fancy. The rest can be learned on the way. Keep in mind that there are people out there that know much less than that and that are able to put together an electronics project successfully only by following "instructables" found on the Internet (really hardcore tinkerers! :-)

BTW, one thing you may find interesting, given your C++ background, is that what they call the "Arduino language" is really true C++! The Arduino environment "enhances" the source program (the "sketch", as they call it) and inserts all the boilerplate code needed to configure the MCU and other low-level stuff a beginner would have hard time digesting. Then the source program so enhanced is fed to AVR-GCC, in its G++ incarnation, which is nothing more that GNU GCC configured as cross-compiler for AVR MCUs. You can even use templates and derived classes, if you dare :-) Of course they don't tell you, otherwise the poor Arduino beginner would be scared away :-D

Very advanced Arduino users can bypass the Arduino environment completely and write directly C++ code and use the board as a simple prototyping board for the MCU it is based upon (ATMega328P for the Arduino UNO), exploiting all the features of the MCU without all the abstraction layers which comprises the Arduino environment.

A note of caution: when I talk about C++ I mean what is technically known as a ***freestanding C++ implementation***, as opposed to a ***hosted implementation*** like on PC's. This means that the implementation doesn't need an OS to work, but also that it doesn't have all the standard libraries that you expect to find on a hosted implementation (sorry, no std::vector or std::cout !!!). A freestanding implementation must only provide a very limited subset of the usual standard libraries (those that handle lower level stuff, like memory allocation), and normally relies on implementation-specific libraries to do other stuff. In particular with the Arduino environment and the underlying AVR-GCC comes the AVR-LIBC library. But this is needed only when you do advanced stuff. The basic Arduino library will keep you busy for a nice amount of time until you reach such a level of expertise.
> 1 votes

# Answer
1) You do not have to have engineering background. You only need to know basics such as what a resistor is, what a transistor is, how an led works etc. (Of course the answer depends on what you want to do. For instance, if you want to work on a robotic project then yes, you need a little knowledge.)

2) Shopping questions are not answered here, but since you are asking something about "cost" then I have two answers. You can find cheaper solutions, but I, personally, always support original products for two reasons. First, you need to support the people who serves your work. Second is that original products are generally more reliable.
> 0 votes

# Answer
First question, no. Tons of tutorials for a from scratch beginner online. Second question, Google Arduino clones.
> 0 votes

# Answer
I am having loads of fun with Arduino from a background of programming with no electronics experience. From simple "flash some LEDs" in the early days (back in Feb) through to making my own "games console" using a 32x32 LED matrix, FRAM memory chip, piezo buzzer and a home made controller for input. I found that once I got started and browed various relevant sites, ideas started to flow.

I would suggest using straight C rather than C++, especially if you are working on one of the particularly low memory devices (such as the Uno). I ran out of working RAM more times than I care to remember.

As for starter kits, if you search, you should be able to find cheap kits. I got a pretty decent starter kit for around £20 but there were cheaper ones with a few less components. Mine included (amongst other things) 30 LEDs, various IR and flame sensors, photo resistors, a 7 segment LED, a 4 digit 7 segment LED, an 8x8 LED matrix, a servo, a stepper motor, a stepper motor control board, a couple of breadboards and an Arduino Uno.
> 0 votes

---
Tags: arduino-uno, c++, hardware, clones
---


# Question
Title: Cannot receive and transmit at the same time
I have 2 arduinos I made some code and I managed to send from the first to the second and from the second to the first with two different pairs of code. What I want to do is to send from the first to the second and from the second to the first with no code change. I added in my current code some monitoring commands but what I can see in my Serial monitor is that not all characters are passed thru. I attach something like my code below only more simplified because it is a big project.

1st arduino:

```
radio.stopListening();
  for(int i=0; i<lnth; i++){
      chartosend=data.charAt(i);
      radio.write( &chartosend, sizeof(chartosend) );
  }
  radio.write(&endchar,1);
radio.startListening();
  if(radio.available()){
    radio.read( &inchar, sizeof(inchar) );
    inradio+=inchar;
    //Serial.println(inchar);
  }

```

2nd Arduino:

```
radio.startListening();
  if(radio.available()){
    radio.read( &data, sizeof(data) );
    inradio+=data;
  }
radio.stopListening();
  if(analogRead(0)>20){
     for(int i=0; i<6; i++){
      chartosend=pir1.charAt(i);
      radio.write( &chartosend, sizeof(chartosend) );
    }
    radio.write( &endchar, sizeof(endchar) );
  }

```

Where is the problem and how I could solve this?

# Answer
> 1 votes
I dunno know about the radio interface you are using. But I can see something which will break your code for sure.

The sections, where you read data from the interface on both Arduinos are passed without a delay, interrupt, polling loop or something else.

Which means: your "read" code section is in no way synchronised with the write code section on the other arduino and vice versa. At the point when you call the function "radio.available()" (which probably tests if there's any data available at the receiver fifo) there is possibly one or any number of bytes available, but not necessary the whole transmission from the other arduino. You have to make sure — somehow — that the transmission is finished, before you can call it a day and go on with processing the received data.

To do this you have to

1. synchronise the beginning and the end of your transmissions on both Arduinos
2. poll the data on the respective receiver side, until you are satisfied
3. or run into a timeout you have to apply in case there's a byte or more lost by chance.

I hope this gives you a little bit of orientation where to start.

---
Tags: nrf24l01+
---


# Question
Title: Cannot print the first number of the date with RTC module
I am using this real-time-clock module to keep track of the time for a project: http://www.dfrobot.com/wiki/index.php/Real\_Time\_Clock\_Module\_(DS1307)*V1.1*(SKU:DFR0151)

I have hooked up the respective pins correctly to the Arduino.

Below is the code I'm using. This first one is the code used to set the time on the module. It writes the initial time you specify to the RTC module.

```
#include "Wire.h"
#define DS1307_ADDRESS 0x68
byte zero = 0x00;         //workaround for issue #527

void setup(){
  Wire.begin();
  Serial.begin(9600);
  setDateTime();         //MUST CONFIGURE IN FUNCTION
}

void loop(){
  printDate();
  delay(1000);
}

void setDateTime(){          //Set the time to a minute or two ahead. After upload has completed, simply press the reset button to start the time while watching another clock.
  byte second = 0;     //0-59
  byte minute = 56;     //0-59
  byte hour = 13;     //0-23
  byte monthDay = 26;     //1-31
  byte month = 5;     //1-12
  byte year = 15;     //0-99
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.write(zero);     //stop Oscillator
  Wire.write(decToBcd(second));
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));
  Wire.write(decToBcd(monthDay));
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.write(zero);       //start
  Wire.endTransmission();
}

byte decToBcd(byte val){
return ((val/10*16)+(val%10));        //Convert normal decimal numbers to binary coded decimal
}

byte bcdToDec(byte val)  {
  return ((val/16*10)+(val%16));        //Convert binary coded decimal to normal decimal numbers
}

void printDate(){
  Wire.beginTransmission(DS1307_ADDRESS);        // Reset the register pointer
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111);     //24 hour time
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  Serial.print(month);        //print the date, EG: 3/1/11 23:59:59
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

//http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

```

And this next block reads the time from the RTC module. It has an onboard battery, so it keeps time even when disconnected from the Arduino.

```
#include "Wire.h"
#define DS1307_ADDRESS 0x68

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

void loop(){
  printDate();
  delay(1000);
}

byte bcdToDec(byte val){
  return ((val/16*10)+(val%16));          //Convert binary coded decimal to normal decimal numbers
}

void printDate(){
  Wire.beginTransmission(DS1307_ADDRESS);          // Reset the register pointer
  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111);     //24 hour time
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  Serial.print(month);          //print the date, EG: 3/1/11 23:59:59
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print("20");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

//http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

```

The weird thing is, when I open the serial monitor after I upload the getTime sketch (the second one), every thing works except that the dayOfMonth only shows the last digit. For example, if the day was the 23rd, it would only print 3. Or if it was 31, it prints 1. I've gone through the code, but can't find anything that I think would cause this. Any tips?

To get started, I followed this tutorial: http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

# Answer
You forgot

```
int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday

```

just before reading `monthDay`. Even though you may not be interested in this piece of data, the RTC chip has no way of knowing that, and it will always send the date and time in the same format. You can replace that line by

```
Wire.read(); // discard day of week

```

if you want to make clear that you are discarding this information.

Ah, BTW, `decToBcd()` and `bcdToDec()` are ill-named: they convert between BCD and *binary*, not *decimal*.
> 3 votes

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


title: Is crystal mandatory on attiny84?

text:
# Question
Title: Is crystal mandatory on attiny84?
I am trying to make a mini project with attiny84 and I searched the web so I can make an arduino on breadboard. What I saw on the internet is that they didnt use crystal. Is it mandatory if I want to use 1 pwm pin and the SPI interface on the attiny84?

# Answer
Only if you need crystal accuracy. If the internal RC oscillator is accurate enough then feel free to use it instead.
> 2 votes

---
Tags: pwm, attiny, spi
---


title: ATTiny to drive LEDs

text:
# Question
Title: ATTiny to drive LEDs
I'm installing some daylight running lights in my car and I have purchased 2 LED bars, each with 8 white LEDs. They use 12V and I need to make some effect when they turn on. Like in some modern cars, when I turn on the key, LEDs should blink(shake like when old fluorescent tubes turns on) and then turn on slowly(brightness from 0-100).

I can do this with Arduino-Uno and I need to put this in a smaller chip. What would be the best suitable ATTiny chip for this project? Because using an ATmega328 is not worth for a small project like this.

# Answer
The ATtiny85 is an 8-pin AVR device with 3 PWM channels available in DIL and SO packages. The Arduino core can be downloaded from arduino-tiny. It can be programmed via ISP using either ArduinoISP or a dedicated programmer.
> 2 votes

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