# Question
Title: Serial Communication over Desktop to Arduino
I have a USB 2 Serial adapter and the device is working fine. I see the device perfectly configured in my System.

I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter. Below is my Arduino code:

```
int i = 0;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  for(i=0;i<6;i++)
  {
  Serial.write('H');
  delay(100);
  }
}

```

But when I try to read thru terminal software of data received at my COM port I see some junk character incoming. I am pretty sure that I am using same baud rate / flow setting both side. Why am I facing this issue - do I need to connect any other pins also as I just need to receive data at system side?

# Answer
> I have a USB 2 Serial adapter...I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter.

You **must not** connect Arduino pins directly to a D-SUB connector of a USB-Serial adapter, as those connectors traditionally carry higher voltage, opposite sense RS232 signals.

* The voltage is too high, and likely to cause damage to your Arduino's processor
* The signal is inverted in sense from the logic-level signaling used by your Arduino's processor.

If you actually needed to make this connection, you would need to either use a "logic level" USB serial adapter (sometimes informally called a USB-TTL adapter). These terminate in various types of connections such as bare wires or header pins/sockets - but basically *never* in an D-SUB connector. Or you can use an inverting line driver and receiver such as the MAX2232 type devices, or even an old 1488/1489 pair.

But it's not clear that you should be doing this at all - **an Arduino Mega already has a USB-serial converter onboard** \- that is the interface you use to program it, and it would ordinarily be simplest to use that for runtime communication as well.
> 1 votes

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


# Question
Title: Solar Tracker Code - how to limit steppers to max & min angle?
a couple of friends and i are working on a double axis solar tracker with a Adafruit Motor-shield V2 and 2x Adafruit bipolar stepper motors (200/rev). We got the following code so far but are stuck with getting the steppers to stop at a certain angle (90° for vertical and 180° for horizontal) so that we dont tangle up the wires and avoid unnecessary movement. Any help and sugestions would be much appreciated.

Cheers

```
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *stepperh = AFMS.getStepper(200, 1);  // declaring horizontal stepper
Adafruit_StepperMotor *stepperv = AFMS.getStepper(200, 2);  // declaring vertical stepper

int ldr1 = A0;  // right ldr
int ldr2 = A1;  // centre ldr
int ldr3 = A2;  // left ldr
int ldr4 = A3;  // top ldr
int ldr5 = A4;  // bottom ldr

const int threshold = 550;  // limit to stop tracker from moving at night

const int tol = 50;  // tolerance for ldrs // maybe vertical AND horizontal depending on difference?

//int = countv
//int = counth

//const int maxh = ?    // to prevent overturning horizontal (50 steps = 90°)
//const int minh = ?    // combine with count int's // i.e. if counth > 90 - stop
//const int maxv = ?    // to prevent overturning vertical
//const int minv = ?

void setup()
{
  AFMS.begin();
  stepperv->setSpeed(10);
  stepperh->setSpeed(10);
}

void loop()
{
  int right = analogRead(ldr1);
  int centre = analogRead(ldr2);
  int left = analogRead(ldr3);
  int up = analogRead(ldr4);
  int down = analogRead(ldr5);

  //STOP MOVEMENT//
  if ((left < threshold) && (right < threshold) && (up < threshold) && (down < threshold)) {}  // stop any movement if sensor values below threshold
                                                                                // at begining to check after every sensor reading

  //HORIZONTAL MOVEMENT//
  if((right > centre + tol) && (left + tol < centre))   // && (right - ? > tol)
  {
    stepperh->onestep(BACKWARD,DOUBLE);  // add +1 to int counth // if (minh < counth < maxh) - move // else - stop // counth=counth++ , counth=counth--
  }
  else if((left > centre + tol) && (right + tol < centre))  // && (left - ? > tol)
  {
    stepperh->onestep(FORWARD,DOUBLE);
  }
  else {}  // do nothing

  //VERTICAL MOVEMENT//
  if((up > centre + tol) && (down + tol < centre))  // && (up - ? > tol)
  {
    stepperv->onestep(BACKWARD,DOUBLE);
  }
  else if((down + tol > centre) && (up + tol < centre))  // && (down - ? > tol)
  {
    stepperv->onestep(FORWARD,DOUBLE);
  }
  else{}  // do nothing
}

```

# Answer
The only sure way is to use one or more position or limit switches. Steps can be lost (motor didn't move as commanded due to, f/ex, overload), the motor could be back-driven while powered down or if over-powered by the mechanical system, or your step counting could be faulty due to a bug or a power glitch.

At power-up or at any time your software thinks it might have got out of sync with the mechanicals, back into the limit switch at low speed (so you don't hard-crash), and reset your software counters, and reposition from there.
> 4 votes

# Answer
When working with steppers you have to realise that you are not dealing with absolute coordinates. Unlike with, for example servos, which you command to go to particular angle, you command steppers to rotate a particular amount of steps in a particular direction. This creates in your case the problem that you cannot actively check the positions of the steppers without some sensing element.

As a solution I would suggest that you would store the steps the steppers take in some variables, and then with the code limiting, that these variables don't go over a surtain number. With this method, you need to have a way of setting the zero point of the steppers, meaning from where to start the counting. This could for example be done by driving the system against some switch, and then setting the step variable to zero here. This is usually done once in the bootup, meaning that it is excecuted in the setup function.
> 1 votes

# Answer
Stepper motors are nice and all but they actually make less than adequate servos for this purpose. the best way that I can see is with linear actuators that have position sensors in them and feed the Voltage divider outputs from those sensors to the Atmega chip. If you write the code to compare the signals from the light detectors with the voltage from the pos sensors it should be a lot better. Also, limit switches should be used in this arrangement too. They would be as a fail safe. The other benefit is that linear actuators usually hold a lot better without loosing their position due to outside stresses. Steppers can be used for prototyping, but it would still be better to start with small servos with sensors and get the system working first. I myself am trying to get a working system and I am having troubles with the coding also, but I am not good at coding. One other thing, I have looked at a lot of different codes to find something that might help me with my project and I have seen this. Stepper motor systems are written with minimal code which as I see it leaves room for much error. Atmega has plenty of room for code storage and plenty of ports for sensors in this use. Everyone knows that old phrase keep it simple but some times that is not always the best advice. You are working with something that needs to be somewhat complicated, to be less likely to fail. The more engineering you put into something the more likely something is to go wrong but less engineering gives you the same results. So consider all the posibilities and address them. Adding components and sub systems will in the end make your work better.
> 1 votes

---
Tags: arduino-uno
---


title: Arduino Uno PWM

text:
# Question
Title: Arduino Uno PWM
My scheme is very basic: I use RGB LED with Arduino Uno. 5v is connected to anode, and pins 9-11 are connected to cathodes.

When using following sketch, my LED is producing white colour, which red, green and blue components are on:

```
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setup(){}

void loop(){
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}

```

But when I refer to docs for PWM:

```
A call to analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on)

```

When I write `0` to all pins, I expect led to be off. What am I missing?

# Answer
> 7 votes
With your LEDs connected to +5V (AKA "Common Anode"), the PWM signal is reversed.

* When the output is "on", the voltage on the pin is 5v.
* When the output is "off", the voltage on the pin is 0V.

The difference in voltage between +5V and the pin for those two different states is:

* "On" = 5V - 5V = 0V
* "Off" = 5V - 0V = 5V

So you can see than when the output is off the LED will on because it causes a difference in voltage from one side of the LED to the other, so current can flow. When the output is on the voltages either side of the LED are the same, so no current will flow.

# Answer
> 4 votes
Since you've connected to the cathodes the pins are *sinking* current. As such the LEDS are active *low* with 0 being almost fully on and 255 being fully off.

# Answer
> 1 votes
Your LEDs are connected to the supply voltage. The output must be low to allow the LED to shine.

`Output 0 ==> LED on`

# Answer
> 0 votes
When you set the pin value to 0 you are making that pin act as ground. Since the LED had a single anode that receives 5V. When the difference between the anode and cathode is high (Anode - 5V & Cathode - 0V) the LED turns on. When the difference between the anode and cathode is low (Anode - 5V & Cathode - 5V) the LED is off. The larger the difference between the two the brighter the LED. In your code use `analogWrite(redPin, ~0);` then everything should work. Change 0 above to whatever value you want, less than 255, and it should work. Also do the same for the green and plus pins too.

---
Tags: led
---


title: Simple IR sensor

text:
# Question
Title: Simple IR sensor
I had an infrared 38khz sensor that I used to read my TV remote control commands. It worked fine but I burned it. I had not another 38khz IR sensor so I tried to use my infrared reflective optic sensor like the one below:

I press my TV remote control button and when I try to read the HIGHs and LOWs it does not work. The sensor shows in my Serial that it received the infrared light but it does not sense the lows/high.

As far as I know, this sensor is not 38khz, it listens in all frequencies that are infrared. So why it does not work? It should work cause it listens in all frequencies. Why it can detect the HIGHs/LOWs that the remote control sends?

# Answer
> 3 votes
You didn't post the code that used to work with the standard 38Khz IR sensor, but I believe you used **digitalRead** to determine a HIGH or LOW value, by thus determine if there is an IR emitting in place.

The reflective optic sensor works differently, the output is analog, and changes according to the amount of IR light it sens. In addition, it has a built-in IR led next to the IR sensor, so if you want to use this as the IR detection sensor you had, first you need to disable the IR led to prevent interference.

The second step would be to use **analogRead**, and compare the result to a pre-defined threshold. For example, since analogRead returns result in the range of 0...1023, you can treat everything from, say, 512 and above as logic 'HIGH'. If you are working with libraries that detects the IR signal, you will need to alter them accordingly.

---
Tags: arduino-uno
---


# Question
Title: Multiple timers with different frequencies
I have to use multiple timers (for example, to blink different LEDs) with different frequency (for example, 7.3 Hz). Cannot you tell me, what is the preferred way to implement it?

Just now I use one simple TimerOne timer and just check what LEDs should be inverted and what are not, but I don't think it's a good idea.

```
#include <TimerOne.h>

#define PIN_RED 52
#define PIN_GREEN 50
#define PIN_BLUE 48
#define PIN_YELLOW 46

#define N_LEDS 4

float freqs[N_LEDS] = {1, 2, 3, 4};
int pins[N_LEDS] = {PIN_RED, PIN_GREEN, PIN_BLUE, PIN_YELLOW};

long int usec_to_invert[N_LEDS];
long int full_usec_to_invert[N_LEDS];

boolean led_states[N_LEDS];

int who_is_next()
{
  int next_to_invert = 0;
  for(int i = 0; i < N_LEDS; i++)
  {
    if(usec_to_invert[i] < usec_to_invert[next_to_invert])
    {
      next_to_invert = i;
    }
  }
  return next_to_invert;
}

void process_timer()
{
  int to_invert_now = who_is_next(); // Смотрим, кого надо инвертировать на этот раз
  long int time_past = usec_to_invert[to_invert_now];

  for(int i = 0; i < N_LEDS; i++)
  {
    usec_to_invert[i] -= time_past;
  }
  led_states[to_invert_now] = !led_states[to_invert_now];
  digitalWrite(pins[to_invert_now], led_states[to_invert_now]);
  usec_to_invert[to_invert_now] = full_usec_to_invert[to_invert_now];

  int next_to_invert = who_is_next();
  long int time_to_pass = usec_to_invert[next_to_invert];
  if(time_to_pass <= 200)
  {  // The interrupt processor should finish work
    Timer1.setPeriod(200);
  }
  else
  {
    Timer1.setPeriod(time_to_pass);
  }
}

void setup()
{
  Serial.begin(115200);
  for(int i = 0; i < N_LEDS; i++)
  {
    pinMode(pins[i], OUTPUT);
    led_states[i] = false;
    full_usec_to_invert[i] = (long int)(1000000. / freqs[i] / 2.);
    usec_to_invert[i] = full_usec_to_invert[i];
  }

  int next_to_invert = who_is_next();
  Timer1.initialize(usec_to_invert[next_to_invert]);
  Timer1.attachInterrupt(process_timer);
}

void loop()
{
   delay(1000);
}

```

# Answer
My suggestions would be:

* Implement a class that handles the queue and timer settings and uses callbacks.
* If you do not need perfect accuracy, remove the loop making the program wait and do that part just setting the timer.
* digitalRead() on an output pin returns the value it was last set to, therefore you do not need to waste that extra RAM.
* DO NOT wait in the ISR "process\_timer()", since you might lose other interrupts! (for the Serial communication, for example)
* is it neccessary to have only values above 200? if not, then don't prevent them from going below that.

--or

use a total overkill system for this situation, such as my multitasking-library arduOS that also covers a some other things.
> 1 votes

---
Tags: programming, timers
---


# Question
Title: Using the ATMega328, from an Arduino UNO in a Standalone configuration, and bootloader - I am really lost
I am ***really*** despaired. I have spent a full day to understand this, and it seems that I still don't.

I have an Arduino UNO, with an ATMega328, for which I wrote a great piece of code.

Later, I have built a circuit on a bread board, where I want to use that same ATMega328, in a 3.3V configuration, and hence 8MHz oscillator .

So, I understood that I have to write a new boot loader to it (is that correct?)

So I follow many guides available, including the Arduino Standalone, and then I understood that I don't have another chip (ATMega328), in order to use the UNO as a boot loader.

So, I was trying to connect the ATMega328 directly from the bread board to the UNO's serial data, change the `boards.txt` file to add `"ATMega on bread board 8MHz"`, and tried to boot-loading it, without success. I get the error that it `can't connect with the board`.

Now I have been told that **I can't** connect the ATMega328 directly to the UNO serial to boot load it, so my questions are:

1. Do I really need to go over this hell in order to work with the same chip that worked with 16MHz, but now on 8MHz at 3.3V? (why in `microchip` I could just switch xtal? )
2. If I do have to boot loading it, and I have **one** chip, and an UNO, how can I do that?
3. How you do that in mass production?

# Answer
> 2 votes
So do I understand you correctly that you want to lift the ATmega328 IC from the Uno board and use it on a breadboard? That strikes me as an unnecessarily risky proposition just to save a dollar or two for a separate ATmega328p.

Second, you technically might not have to write a new boot loader to the chip, if you don’t intend to reprogram it while it’s on the breadboard, but you definitely need different fuse settings, and the two changes are closely related in the Arduino IDE.

Third, bootloaders on ATmega are incapable of modifying themselves, so if you want to write a new bootloader, you always need a programmer (which can e.g. be your Arduino UNO running the ArduinoISP sketch or ScratchMonkey); I don’t think your single-microcontroller idea would work.

For mass production, you’d just use a programmer. Bootloaders tend not to be used for this, which can lead to situations like this year’s mishap at SparkFun

# Answer
> 1 votes
There is a very nice tutorial by Adafruit, which explains how to get the Arduino Uno run at 3.3v, with minimum hussle and while keeping it's speed at 16Mhz, despite it's a bit out of specs (they claim it shouldn't pose a problem).

The main idea is to replace the voltage regulator and the fuse on the Uno board. This involves some soldering, but will probably give you the fastest results for *prototyping*.

I would not choose the Arduino Uno for mass production anyway, since there are plenty of Arduino compatible boards that runs at 3.3v (like Arduino Due, Lilypad, and Arduino Pro Mini to name a few. Full list can be found on Wikipedia). As a side note, for mass production, I would probably go with a custom made PCB, and not an off-the-shelf product, considering its high cost.

The link you provided explains how to recreate the Arduino around the Atmega328p on a breadboard. For that, you will need a USB to serial converter such as the suggested FT232, but please note that this tutorial **does not** address the issue on stake, which is running the chip at 3.3v (note the specs of the voltage regulator they offer, which is a 5v regulator).

---
Tags: arduino-uno, bootloader, arduino-ide, atmega328
---


# Question
Title: Unable to load sketch: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41
I've stumbled upon what I've later found it's quite common error, but there seems not to be simple troubleshooting way and solution (people often try various things, sometimes they succeed, sometimes not).

I am using DAGU mini driver, I was able to load sketch as described here \- chose Arduino NG ATMega8 as board, connect to my PC via USB (with the driver listed on the product page).

Later on I've plugged RedBot wheel encoders sensor and write some simplistic program to check whether it works at all. I've summarized the steps in a github issue, so that it's easy to reference it.

When I tried to upload the sketch I've receiced `stk500_initialize(): (a) protocol error, expect=0x14, resp=0x42`, `stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41`. The full log is included in comment on that github issue.

The D13 diode is making series of 3-blink bursts - 8 bursts after start. More diagnostic I did in the github issue as well.

My question (apart from obvious 'how to fix it!?!' ;) ) is whether there is some kind of documentation for this protocol? On the various topics I've found people seem to have somewhat different problems (the numbers and messages were different). I just want to know why the first few messages are exchanged OK (avrdude receives some basic info from the chip), but later ones (namely `Send: A [41] . [81] [20]`) are producing protocol errors.

# Answer
> 0 votes
AVR programmer helped.

Meaning the bootloader somewhat got corrupted and I had to burn new one.

---
Tags: uploading, bootloader, sketch
---


title: What is this PIND command

text:
# Question
Title: What is this PIND command
I have a code that reads the value of a sensor and because it needs to be very fast it does not use digitalRead but a strange form of reading. In the top of the code it shows:

```
#define IRSENSOR PIND
int irpin = 2;

```

I have no idea why this PIND referes to my arduino pin 2, but it only work if my sensor is in pin 2. If I want to change to pin 9 and only change the irpin varialbe it does not work. Why?

To read the sensor I use this code:

```
while (IRSENSOR & (1 << irpin )) {

```

Have no idea why this work. Does anyone know this kind of programming with arduino?

# Answer
> 6 votes
PIND refers to the arduino's IO register for input in port D

Without arduino, one has to refer to pins by specific bits in 3 different sets of registers for each port (PIN\*, DDR\*, and PORT\*; B,C, and D).

The arduino code makes it simpler to pick out a single pin by hiding all of this, but it does make reading a pin take much longer.

In the code, the specific pin is being selected by masking off all but the "irpin" bit in PIND, so changing irpin will pick a different bit and thus a different pin.

Pin 9 is actually bit 1 of port B, not D, so see if this works:

```
#define IRSENSOR PINB
int irpin = 1;

```

alternatly, using a reference instead of define,

```
volatile uint8_t& IRSENSOR = PINB;
int irpin = 1;

```

# Answer
> 1 votes
Reason explained by @BrettM. To be more perfect use macros everywhere, e.g.:

```
#define IRSENSOR PIND
#define IRSENSOR_PIN PD2

while (IRSENSOR & _BV(IRSENSOR_PIN)) {

```

Arduino's *digitalWrite(),digitalRead(),pinMode()* functions are useless for more serious coding because they are 1) slow 2) you cannot address pins not connected to headers (e.g. at *Arduino2560*).

---
Tags: arduino-uno
---


title: Port register not working

text:
# Question
Title: Port register not working
I am trying to read my ultrasonic sensor. It sends a pulse in the trigger pin and the echo pin receives the pulse. Using pulseIn I can know exactly the time it took to the pulse go and back. But I need to use port register which is much faster and I need it to be fast in this specific case.

My code is very simple:

```
void setup() {

    Serial.begin(9600);
    //pin 12 as output
    DDRB = B00010000;
    //pin 12 as low
    PORTB = B00000000;

}

void loop() {

    //pin 12 as high
    PORTB = B00010000;
    delayMicroseconds(10);
    //pin 12 as low
    PORTB = B00000000;

    long start_time = micros();

    //While reading high in pin 13 keep running the loop
    while (PINB & B00100000)) {

    }

    Serial.println(micros() - start_time);

    delay(1000);

}

```

The problem is that it does not work, I mean, the while loop is not being processed so the serial is always printing a very small number. It doesnt matter if I move the ultrasonic sensor to distant walls the while loop still does not work. What am I doing wrong?

# Answer
> 2 votes
According to anything I could find, the Echo output is normally *low* and then goes *high* for a duration equal to the range. Your initial while condition is inverted, and you need to check for *both* edges.

```
unsigned long up, down;

// trigger pulse
while (!(PINB & _BV(PB5)))
  ; // wait for leading edge
up = millis();
while (PINB & _BV(PB5))
  ; // wait for trailing edge
down = millis();
Serial.println(down - up);

```

---
Tags: arduino-uno
---


# Question
Title: Arduino Mega: which Digital pins are already used for something?
I got an Ethermega, and learned that Pin 13 already has a LED.

Are there other digital pins with special circuitry or already allocated to a specific function? (like usb,serial,ethernet,sd, etc)

I need about 30 inputs so I can skip some if that would avoid headaches.

# Answer
> 1 votes
D4: ChipSelect for the SD card reader (can be used if no SD is present)

D0 and D1 are Serial RX and TX (just like any other arduino)

D10: Ethernet enable line

D13: led. Led is connected via a mosfet, so it doesn't interfer (like on the uno)

D50, D51, D52: SPI for the ethernet chip and SD card

All this was found in the schematic

# Answer
> 2 votes
Don't worry about the led on pin 13, it just sits there but doesn't block anything.

You can still use the pin as a normal IO pin.

You didn't mention whether your 30 inputs are digital or analog, so let's have a look at digital input first.

I have never used the **MCP23017** mentioned by *Martynas*, but the linked article looks very interesting and I'll definitely order one of these amazing chips!

Another option might be using 8 bit PISO (*parallel in - serial out* shift registers, such as the **74HC165**. Consider this as the complement to the 75HC595 for output. These shift registers are dirt cheap (around 0.3 €), are available as DIP (important for breadboarding) and can be run via SPI.

Advantages:

* it's fast to read in 8 digital lines into a byte (why would one want to use more than a bit for the state of a digital input?)
* the shift registers can be *daisychained*, subsequent calls of ShiftIn allows to read all (digital) input states into a corresponding data structure (array of bytes, etc.) using just **three pins** on your Arduino.

---
Tags: arduino-mega, pins, digital
---


title: Interrupts for analog inputs

text:
# Question
Title: Interrupts for analog inputs
I have an Arduino Uno. I've been reading about pin change interrupts, and one vector covers the analog pins. However, is it possible to trigger interrupts using analog pins as analog inputs (not digital)?

I actually want to analogRead() a potentiometer inside the ISR.

This is my code so far, http://pastebin.com/ykpp78GB

And my circuit is just two potentiometers connected to pin A0 and A1.

# Answer
> 5 votes
It is not possible to trigger an interrupt when an analog input has reached a threshold on any tinyAVR or megaAVR. It is possible to trigger an interrupt when an analog input of an AVR XMEGA with the event system.

It is possible to use the built-in analog comparator on the ATmegaXX8 and ATmegaXXU4 in the Uno, Leonardo, and comparable boards to trigger an interrupt when an internal or external threshold has been met. It is only possible to compare to an internal threshold on the Mega, Mega 2560, or comparable boards since the pin for the external threshold is not broken out, although actual breakout boards for the ATmegaXXX0/1 will have the pin broken out.

In all cases, examine the appropriate datasheet (in particular the "Analog Comparator" section) as well as the pin mappings on the Arduino website for full details.

---
Tags: interrupt
---


title: ATtiny85 minimum setup to blink led

text:
# Question
Title: ATtiny85 minimum setup to blink led
What would be the (very) minimum *schematic* to make a ATtiny85 blink a led?

Restrictions are:

* There must be a C program compiled and uploaded to it, just like an Arduino board would have. The code would use a simple "delay" to wait a little bit before changing the LED state.
* The LED must be controlled by a "digital output port" just like an Arduino board would be.

This is the main question. Although I thought to ask a similar question with the restriction of "blinking exactly once per second", that would change completely the schema (not being a MINIMAL after all). So lets restrain to the main question. Maybe some day we can discuss the version 2.0!

# Answer
> 9 votes
This schematic shows a complete connection of a blinking led.

* Red cable = +5V (pin 8)
* White cable = Ground (pin 4)
* Resistor = 1 end at pin 5 (IO 0) and the other in the LED anode (+)
* Led anode (+) in the resistor, cathode (-) (small leg) in the ground
* Resistor = 330 Ohms

The arduino in the picture is not necessary, just used to give power. But in the video linked below its used to burn the ATtiny85. The resistor can be a 330 ohms for a simple project like this.

Youtube Video with a simple explanation

I hope this explanation will enlighten who wants to start on it.

--

Edited:

If you want to record your ATtiny85 using Arduino UNO as ISP, then you will also need:

* 10 uF electrolytic capacitor

Here a picture of the pins:

# Answer
> 6 votes
Ignacio Vazquez-Abrams has already outlined the schematics.

> There must be a C program compiled and uploaded to it, just like an Arduino board would have.

There are however some differences between a fully equipped Arduino board with an ATMega328P and a bare ATtiny85 you would have to care for in your code:

1. A bare ATtiny85 runs at 1 MHz (8 MHz internal oscillator, *CKDIV8*). Define **F\_CPU** accordingly.
2. The ATtiny85 only has one hardware port, **PB**. There's a reason Ignacio used **PBx** in his scheme ;)

On the plus side, the ATtiny85 allows to toggle a pin by setting the corresponding bit in **PINB**.

```
PINB |= (1 << PB0);

```

# Answer
> 5 votes
Here is the absolute minimal schematic required to blink a LED beyond power and decoupling:

Refer to "Which resistor to use for this LED" to calculate the appropriate value for R1.

# Answer
> 3 votes
My setup would be:

* a 10k resistor between Vcc and reset pin (pull-up)
* a 330k put in serial with a led, connected between, e. g. PB0 and gnd.

That's all.

For programming, I use an ISP programmer. I use a cheap Arduino Nano clone board for that.

I can run my ATtiny85 at 16Mhz internal oscillator, but important: I remarked that I had better results after having burnt the bootloader onto the ATtiny85, even if it is not needed because there is no USB serial chip besides the MCU.

But perhaps using avrdude to program the ATtiny85 fuses bits could avoid to burn this useless bootloader (taking 1/4 of flash memory). If someone has a solution, he is welcome.

---
Tags: sketch, c, attiny, prototype
---


# Question
Title: Using Arduino audio to control an LED light
I am looking for a way to control an LED on a circuit board using audio input for learning purposes.

I have written my own speech recognition system using dynamic time warping in Python, but I would like to know if (and maybe what models if not all can do) Arduino can possibly handle the processing of a 70 by 70 O(n^2) matrix traversal with **fft** or **dct** operations on audio input divided into 10ms frames.

Any advice will be appreciated.

# Answer
The Due or Tre may have enough power for this. The Yún may be able to offload it to the more powerful CPU. Every other Arduino will struggle with it.
> 0 votes

---
Tags: led, remote-control, audio, signal-processing
---


# Question
Title: Shift register on Attiny85 programmed by Arduino
Shift registers need 3 digital pins in order to work (data, clock and latch), but Attiny45/85 chips provides 2 digital and 2 analog pins.

Would I use 1 analog pin as digital pin? How?

# Answer
The ATtinyX5 does not have *any* analog-only pins; all 5 pins are usable as digital I/O (all 6 if you know what you're doing, but if you need to ask how then you're not ready to do so).
> 1 votes

# Answer
As *Ingnacio has already pointed out*, **PB0** to **PB4** can be used as digital IO ports **without problems**. It night be a good idea though not to touch **PB6**, the `RESET` pin.

Btw, this isn't different from an Arduino, where all so-called *analog pins* can be used for digital output as well.

If you want to drive shift registers from an ATtiny85 using SPI, you might want to have a look at the tinySPI library written by **Jack Christensen**. *Please note that I haven't used this library personally!*
> 0 votes

---
Tags: arduino-uno, attiny
---


# Question
Title: Wrong Mouse.move() output in Arduino Leonardo
I'm using my Arduino Leonardo as a Mouse but I'm experimenting a strange behaviour. I put my mouse at (-1, -1) (absolute) coordinates and then I execute this code:

```
Move.move(com[curr_cmd_id].x, com[curr_cmd_id].y, 0);

```

where that point is (334, 180) (relative coords) (and I checked it through Serial console)

Now, the pointer is actually moving to the right but then it stops. Let's say it reaches the point (334, 0).

Then I tried:

```
Mouse.move(com[curr_cmd_id].x, 0, 0);
delay(500);
Mouse.move(0, com[curr_cmd_id].y, 0);

```

but still the same behaviour.

Then finally I tried this one (which it actually solves my problem but it's a dirty solution):

```
int i;
for(i=0; i<com[curr_cmd_id].x; i++){
  Mouse.move(1,0,0);
  delay(1);
}
for(i=0; i<com[curr_cmd_id].y; i++){
  Mouse.move(0,1,0);
  delay(1);
}

```

Could anybody help me in understanding what's going on here? How can I achieve a simple and direct relative movement for my pointer? Thanks you in advance!!

# Answer
I struggled with this too until I realized this

> Parameters
>
> xVal: amount to move along the x-axis - signed char
>
> yVal: amount to move along the y-axis - signed char
>
> wheel: amount to move scroll wheel - signed char

Note it says signed char.

That means the value you pass to the Mouse.move is a signed 8-bit. (-128 to 127)

My work around is this below:

```
void moveMouse(int x, int y, int w){
  x = (int)x / 1.59; //Adjust these two values accordingly. I found out that 100, 100 does
  y = (int)y / 1.58; //not move 100, 100. It moves 159, 158 for me.

  while(x!=0 || y!=0 || w!=0){
    int moveX, moveY, moveW;
    if(x > 0){
      if(x >= 100){
        moveX = 100;
      }else{
        moveX = x;
      }
    }else if (x < 0){
      if(x <= -100){
        moveX = -100;
      }else{
        moveX = x;
      }
    }else{
      moveX = 0;
    }

    if(y > 0){
      if(y >= 100){
        moveY = 100;
      }else{
        moveY = y;
      }
    }else if (y < 0){
      if(y <= -100){
        moveY = -100;
      }else{
        moveY = y;
      }
    }else{
      moveY = 0;
    }

    if(w > 0){
      if(w >= 127){
        moveW = 127;
      }else{
        moveW = w;
      }
    }else if (w < 0){
      if(w <= -128){
        moveW = -128;
      }else{
        moveW = w;
      }
    }else{
      moveW = 0;
    }

    x = x - moveX;
    y = y - moveY;
    w = w - moveW;

    Mouse.move(moveX, moveY, moveW);
  }

```
> 1 votes

---
Tags: programming, arduino-leonardo, sketch, pointer
---


title: Blend with SD Shield

text:
# Question
Title: Blend with SD Shield
Building a data logging and transmission system here. I've a RedBearLab Blend with built-in BLE capabilities and a (cheap) SD / Data logging shield that looks very suspiciously like it's copied from the Adafruit one.

Using a Stock Arduino Uno board, the Data logging shield works out of the box - both RTC TimeSet and cardinfo come back successfully.

Stacking the shield on the Blend, both examples lead nowhere. The TimeSet states that no connection could be made, and the cardinfo says it can't find the card.

I assume it's a pin conflict of some sort, but I'm really unsure what I should do to debug/fix it.

\[edit\] As I found out below, the SD Module works now - but I still face the problem of not getting the RTC to work. Neither on the shield nor a Tiny RTC module. Again, both work fine on the Arduino Uno.

\[edit2\] I had basically the same problem for the RTC module as well - see the answer below.

# Answer
> 0 votes
Sometimes it helps just adding the tags.....

The Blend is a Arduino Leonardo Chip - and as Lady Ada helpfully points out, you need a special SD Library to use this. The advice on https://learn.adafruit.com/adafruit-data-logger-shield/for-the-mega-and-leonardo is everything I needed to get the cardinfo working, especially the `while (!card.init(SPI_HALF_SPEED, 10, 11, 12, 13)) {` part.

Also, the I2C Pins for the RTC Clock are not the "standard" Analog Pins 4 and 5, but D2 and D3 (see http://arduino.cc/en/Reference/Wire)

---
Tags: pins, bluetooth, arduino-leonardo, sd-card
---


title: Delay() function and I2C interrupt

text:
# Question
Title: Delay() function and I2C interrupt
In my design, one arduino pulls a line high on other arduino, the other arduino polls this pin and if that is high sends the data on I2C bus.

The first arduino holds the line high for 100ms using the delay() method, the other arduino is sending the data during this time, but the I2C receive interrupt is not being triggered.

I have attached a sequence diagram for a better explanation for what is happening.

I suspect that the delay() method somehow is disabling the I2C ISR from triggering.

# Answer
> 2 votes
Sorry guys, I made a very silly mistake here, i was using Serial.print here in ISR, following the Slave\_Receiver example in the Arduino examples. I got a bit carried away with the use of those Serial debug messages and added lots of them,

I got this info from https://stackoverflow.com/questions/17985830/arduino-using-interrupts-freezes-processing-and-serial-output

checkout answer by **elias**

The code does not freeze now. Sorry for the troubles, i hope this helps someone else in return.

---
Tags: i2c, arduino-pro-mini
---


# Question
Title: NRF24L01+ scanning and connecting to wifi hotspots or creating one
I've seen this video so I think I can connect it through my wifi router to any device. How can I scan for and discover wifi hotspots and then connect to it? Or is there a way to create wifi hotspot of it's own?

# Answer
> 5 votes
It does seem possible, check out this thread on Arduino forums, where cpixip worked directly with the NRF24 SPI interface to accomplish that.

Here is the code he published, in case the link won't be available:

```
#include <SPI.h>

// Poor Man's Wireless 2.4GHz Scanner
//
// uses an nRF24L01p connected to an Arduino
//
// Cables are:
//     SS       -> 10
//     MOSI     -> 11
//     MISO     -> 12
//     SCK      -> 13
//
// and CE       ->  9
//
// created March 2011 by Rolf Henkel
//

#define CE  9

// Array to hold Channel data
#define CHANNELS  64
int channel[CHANNELS];

// greyscale mapping
int  line;
char grey[] = " .:-=+*aRW";

// nRF24L01P registers we need
#define _NRF24_CONFIG      0x00
#define _NRF24_EN_AA       0x01
#define _NRF24_RF_CH       0x05
#define _NRF24_RF_SETUP    0x06
#define _NRF24_RPD         0x09

// get the value of a nRF24L01p register
byte getRegister(byte r)
{
 byte c;

 PORTB &=~_BV(2);
 c = SPI.transfer(r&0x1F);
 c = SPI.transfer(0);
 PORTB |= _BV(2);

 return(c);
}

// set the value of a nRF24L01p register
void setRegister(byte r, byte v)
{
 PORTB &=~_BV(2);
 SPI.transfer((r&0x1F)|0x20);
 SPI.transfer(v);
 PORTB |= _BV(2);
}

// power up the nRF24L01p chip
void powerUp(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x02);
 delayMicroseconds(130);
}

// switch nRF24L01p off
void powerDown(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)&~0x02);
}

// enable RX
void enable(void)
{
   PORTB |= _BV(1);
}

// disable RX
void disable(void)
{
   PORTB &=~_BV(1);
}

// setup RX-Mode of nRF24L01p
void setRX(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x01);
 enable();
 // this is slightly shorter than
 // the recommended delay of 130 usec
 // - but it works for me and speeds things up a little...
 delayMicroseconds(100);
}

// scanning all channels in the 2.4GHz band
void scanChannels(void)
{
 disable();
 for( int j=0 ; j<200  ; j++)
 {
   for( int i=0 ; i<CHANNELS ; i++)
   {
     // select a new channel
     setRegister(_NRF24_RF_CH,(128*i)/CHANNELS);

     // switch on RX
     setRX();

     // wait enough for RX-things to settle
     delayMicroseconds(40);

     // this is actually the point where the RPD-flag
     // is set, when CE goes low
     disable();

     // read out RPD flag; set to 1 if
     // received power > -64dBm
     if( getRegister(_NRF24_RPD)>0 )   channel[i]++;
   }
 }
}

// outputs channel data as a simple grey map
void outputChannels(void)
{
 int norm = 0;

 // find the maximal count in channel array
 for( int i=0 ; i<CHANNELS ; i++)
   if( channel[i]>norm ) norm = channel[i];

 // now output the data
 Serial.print('|');
 for( int i=0 ; i<CHANNELS ; i++)
 {
   int pos;

   // calculate grey value position
   if( norm!=0 ) pos = (channel[i]*10)/norm;
   else          pos = 0;

   // boost low values
   if( pos==0 && channel[i]>0 ) pos++;

   // clamp large values
   if( pos>9 ) pos = 9;

   // print it out
   Serial.print(grey[pos]);
   channel[i] = 0;
 }

 // indicate overall power
 Serial.print("| ");
 Serial.println(norm);
}

// give a visual reference between WLAN-channels and displayed data
void printChannels(void)
{
 // output approximate positions of WLAN-channels
 Serial.println(">      1 2  3 4  5  6 7 8  9 10 11 12 13  14                     <");
}

void setup()
{
 Serial.begin(57600);

 Serial.println("Starting Poor Man's Wireless 2.4GHz Scanner ...");
 Serial.println();

 // Channel Layout
 // 0         1         2         3         4         5         6
 // 0123456789012345678901234567890123456789012345678901234567890123
 //       1 2  3 4  5  6 7 8  9 10 11 12 13  14                     |
 //
 Serial.println("Channel Layout");
 printChannels();

 // Setup SPI
 SPI.begin();
 SPI.setDataMode(SPI_MODE0);
 SPI.setClockDivider(SPI_CLOCK_DIV2);
 SPI.setBitOrder(MSBFIRST);

 // Activate Chip Enable
 pinMode(CE,OUTPUT);
 disable();

 // now start receiver
 powerUp();

 // switch off Shockburst
 setRegister(_NRF24_EN_AA,0x0);

 // make sure RF-section is set properly
 // - just write default value...
 setRegister(_NRF24_RF_SETUP,0x0F);

 // reset line counter
 line = 0;
}

void loop()
{
 // do the scan
 scanChannels();

 // output the result
 outputChannels();

 // output WLAN-channel reference every 12th line
 if( line++>12 )
 {
   printChannels();
   line = 0;
 }
}

```

The pinout seems to match the NRF24 library pinout. Please note that it seems this project does not implement the WiFi stack, but only check a high enough signal ( \> -64dBm) for a given channel.

In order to create a WiFi hotspot, implementing the 802.11 stack is inevitable, and it seems like the Arduino core chip (atmega328) is not suitable for implementing it using software and bit-banging, so a dedicated hardware will be necessary.

# Answer
> 2 votes
I believe nRF2401 is low level tx/rx chip working in 2.4GHz band. But it's not WiFi module. To use it as WiFi you probably need implement WiFi stack. I think guy in video set up channel and counting receved data only.

---
Tags: arduino-mega, wifi, nrf24l01+
---


# Question
Title: Which reflectance sensor array for a line following robot?
I'm working on a line-following robot with my son. We've found a sensor array on Robot Shop that will help us but .. there's two and I'm not sure which will be the best for us.

The difference between them, as described in this PDF is "The QTR-8A uses a voltage divider for each sensor’s output while the QTR-8RC uses an RC circuit."

What I want to do is detect which sensor the followed line is triggering. All I need is a yes/no. But I'm too new to this to decide which of these two sensors would be best for me.

# Answer
The main difference between the two models, as stated in the PDF you provided, is the output they provide to the MCU.

The QTR-8A will provide an **Analog** output, requiring a corresponding analog pin on the microcontroller. The QTR-8RC will provide a **Digital** output, but will allow the same accuracy of the QTA-8A by measuring the discharge time of the capacitor (HIGH to LOW time), with the advantage of higher accuracy due to the use of RC circuit instead of a voltage divider.

Both seems pretty straight forward, but for your needs, the QTR-8RC might seem more compatible, considering the Arduino Uno has 6 analog I/O pins (you didn't mention which Arduino is going to be used, the Arduino Nano has 8 and the Arduino Mega has 16), and that the QTR sensor provides 8 outputs. The way you could accomplish that with QTR-8RC and 8 **digital** I/O pins is described in the PDF:

> 1. Turn on IR LEDs (optional)
> 2. Set the I/O line to an output and drive it high
> 3. Allow at least 10 us for the 10 nF capacitor to charge
> 4. Make the I/O line an input (high impedance)
> 5. Measure the time for the capacitor to discharge by waiting for the I/O line to go low
> 6. Turn off IR LEDs (optional)
> 3 votes

---
Tags: sensors, robotics
---


title: C# and Arduino problem with serial port

text:
# Question
Title: C# and Arduino problem with serial port
I would like to establish a communication between my C# program and my Arduino Duemilanove. I tried lot of different tutorials, but none of them were the same, and I'm a little bit confused.

Actually my code is:

C#

```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InterfaceArduinoWindowsFOrm {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      serialPort1.PortName = "COM3";
      serialPort1.BaudRate = 9600;
      serialPort1.Open();
    }

    private void pictureBox1_Click(object sender, EventArgs e) {
    }

    private void tabPage2_Click(object sender, EventArgs e) {
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
    }

    private void toolTip1_Popup(object sender, PopupEventArgs e) {
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {
      Console.WriteLine("test");
    }

    private void button1_Click_1(object sender, EventArgs e) {
      serialPort1.Write("5");
      Console.WriteLine(serialPort1.IsOpen);
    }
  }
}

```

Arduino:

```
/* Sweep
  by BARRAGAN <http://barraganstudio.com>
  This example code is in the public domain.
  modified 8 Nov 2013
  by Scott Fitzgerald
  http://arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // Create servo object to control a servo.
// Twelve servo objects can be created on most boards.
int pos = 0;
int message = 0; // This will hold one byte of the serial message
                 // variable to store the servo position.

void setup() {
  Serial.begin(9600);
  myservo.attach(9);  // Attaches the servo on pin 9 to the servo object
}

void loop() {
  if (Serial.available()) {

    // Check to see if there is a new message
    message = Serial.read();

    // Put the serial input into the message
    Serial.print(message);

    if (message == '5') {
      Serial.print("test");
      for(pos = 0; pos <= 180; pos += 1) {
        // Goes from 0 degrees to 180 degrees
        // in steps of 1 degree

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }

      for(pos = 180; pos>=0; pos-=1) {
        // Goes from 180 degrees to 0 degrees

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }
    }
  }
}

```

The problem is, when I click my button, nothing happens, but obviously if I remove the `if` statement, the servo motor code works.

# Answer
> 1 votes
Since you are sending from the Arduino the received serial data back to the C# application (`Serial.print(message);`), I would advise to check what you receive on the C# side. Register to the DataReceived event of the SerialPort as so:

```
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

```

And add an event handler:

```
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    string data= port.ReadExisting();
    // check here what data you received, if any
}

```

This way you could confirm that the Arduino gets the data properly from the C# side to begin with. Next step would be to understand if this **if** statement treats the data properly:

```
if (message == '5')

```

But starting from examination of what you get from the C# side will help you decide where exactly is the problem.

---
Tags: serial
---


# Question
Title: How to use bitset/read on 16bit numbers (Arduino)
I'm working on an Arduino powered Tetris game. To keep track of the pieces that have fallen and become fixed I have an array of bytes

```
byte theGrid[] = {
B00000000,
B00000000,
B00000000,
B00000000,
B00000000,
...

```

This works great when the well is only 8 LEDs wide, but I need it to be 16 wide. Is there a way to perform bitwise operations on a 16 bit number, like a short? I tried just declaring theGrid as a short, but I'm getting this error no matter what I do.

```
tetris:62: error: 'B0000000000000000' was not declared in this scope

```

The reason I was using byte is so I could use bitread and bitset. So if an L piece comes down and lands, I can bitset the appropriate bits like this

```
bitSet(theGrid[pixelY], 15-pixelX);

```

and end up with

```
B1000000000000000, B1110000000000000

```

# Answer
> 3 votes
The main problem that you're having is that *binary literals don't exist in C*; the Arduino libraries get around this by having **every single binary value** from 1'b0 to 8'b1111\_1111 defined as a macro in `cores/arduino/binary.h`. The obvious workaround is to use octal, decimal, or hexadecimal literals instead.

```
unsigned short theGrid[] = {
00,
0,
0x0,
 ...
};

```

Bitwise operations work as normal.

```
theGrid[pixelY] |= _BV(15 - pixelX);

```

---
Tags: programming, sketch
---


# Question
Title: Which IDE should I use to write Pythonic-programs for Arduino
I'm doing my first baby-steps to build tools using Arduino. I'd like to know if there is a way to write python scripts to build programs for Arduino. Most of IDEs I found are non-supported IDEs. Is there any "recommended" IDEs that I should use.

# Answer
The recommended IDE for writing **C/C++** for Arduino for beginners is the formal Arduino IDE, of which you can read more on the arduino.cc website.

**Python** is an interpreter language, and as such, require an interpreter running on the target machine. Unfortunately, the Arduino does not natively support running an Python interpreter, although some efforts has been made in that direction, for example the Python on a chip project, or the Python Arduino Proto API v2. See this SO question for more details. If you go with any of these options, the IDE you would use would be your favorite Python IDE.

Note that both projects have their downsides, and actually there is no real alternative equivalent to running compiled C/C++ code on the Arduino. If you have strong Python programming abilities, this shouldn't be too hard for you as well :)
> 1 votes

---
Tags: arduino-uno, python
---


# Question
Title: analogWrite causes value from IR receiver to change
I'm playing around with an IR receiver and an RGB led.

I had it up and running, until I changed around some code. The remote seeming stopped working, but after looking at the values in the Serial Monitor it appeared that the values that were being printed out weren't the same.

After playing around a bit I found that if analogWrite is run on pin 11, the value changes. Why is this so?

Code is as follows:

```
#include <IRremote.h>

int ir_recv_pin = 2;

IRrecv irrecv(ir_recv_pin);

decode_results results;

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

void loop()
{
    if (irrecv.decode(&results))
    {
        //Serial.println(results.value);
        Serial.println(results.value == CH_MINUS);
        Serial.println(results.value);
        Serial.println(CH_MINUS);

        analogWrite(11, 125);
        irrecv.resume();
    }
}

```

Output is as such when pressing the button twice in a row (without holding the button down):

```
1
16753245
16753245
0
3810010651
16753245

```

Initially the values come out as expected (16753245), but after the analogWrite, the value changes (3810010651).

Looking at the documentation it says that pin 11 runs at 980Hz. Is this why the value changes? If so, why?

# Answer
Because IRremote uses timer 2 by default, and the PWM output on pin 11 is generated via OC2A. Either edit `IRremoteInt.h` to use timer 1, use a pin on timer 1 for PWM, or frob OCR2A directly instead.
> 3 votes

---
Tags: analogwrite
---


# Question
Title: Record video with CMOS camera using Arduino
Is it possible to use this with Arduino to record and store videos on memory card?

Additionally, if someone has already done it, a tutorial link would be appreciated.

# Answer
> 3 votes
Arduinos have two major drawbacks:

1. Not enough memory.
2. Way too slow.

There's a shield to help you do that:

http://nootropicdesign.com/ve/ http://blog.arduino.cc/2011/03/24/arduino-computer-vision-with-video-experimenter-shield/

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


title: Using a relay to control a lamp

text:
# Question
Title: Using a relay to control a lamp
Okay, so I'm using an Arduino Uno R3 and I wanted to start of my own home automation project. I have a 4 channel 12V relay board and I normally connect it to a 12V 500mA adapter. What is the maximum wattage bulb (or CFL) that I can power with this configuration?

# Answer
Unless you feel like starting a fire, none. Find a 220V 2A relay with a 5V coil and use that instead, switching the hot wire and not the neutral.
> 1 votes

---
Tags: arduino-uno, relay, automatization
---


title: Arduino to Home Speakers

text:
# Question
Title: Arduino to Home Speakers
I know little about electronics in general. I wanted to connect Arduino, and play a tone using tone() through my home speakers.

I've used a 1/8'' audio jack and connect ground to ground and left/right to pin 2. Run it and it was too loud.

Then I read the specification and it says,

Input impedance = 20 kOhm

Input sensibility = 400mV +/- 50mV

Arduino sends 5V so that should be a lot. Did I damage my speaker? They still work.

# Answer
> 2 votes
It's probably not damaged, but you shouldn't do it again.

To get the 5V signal down to 400mV you need to create a voltage divider. As such you will need a:

5V / (400mV / 20kohm) − 20kohm = 230kohm

resistor between the pin and the input. 220kohm should be close enough.

---
Tags: audio
---


title: 16 bit PWM on a mega

text:
# Question
Title: 16 bit PWM on a mega
I have two Arduinos, a nano and a mega. I want to output 16 bit PWM, but can seem to only get it working on the nano. I'm adapting the code from this website: http://www.ofrecordings.com/2014/03/16/how-to-set-up-16-bit-pwm-with-an-arduino-uno-atmega328/

```
void setup() {
  // Set PB1/2 as outputs.
  DDRB |= (1 << DDB1) | (1 << DDB2);

  TCCR1A =
      (1 << COM1A1) | (1 << COM1B1) |
      // Fast PWM mode.
      (1 << WGM11);
  TCCR1B =
      // Fast PWM mode.
      (1 << WGM12) | (1 << WGM13) |
      // No clock prescaling (fastest possible
      // freq).
      (1 << CS10);
  OCR1A = 0;
  // Set the counter value that corresponds to
  // full duty cycle. For 15-bit PWM use
  // 0x7fff, etc. A lower value for ICR1 will
  // allow a faster PWM frequency.
  ICR1 = 0xffff;
}

void loop() {
  // Use OCR1A and OCR1B to control the PWM
  // duty cycle. Duty cycle = OCR1A / ICR1.
  // OCR1A controls PWM on pin 9 (PORTB1).
  // OCR1B controls PWM on pin 10 (PORTB2).
  OCR1A = 0x0000;
  delay(500);
  OCR1A = 0x8000;
  delay(500);
  OCR1A = 0xffff;
  delay(500);
}

```

That code works on the nano, but not on the mega. I expect that it output PWM on pins 11 and 12, but no luck. Care to explain how I can get it working? It's an entirely different microprocessor, and I'm not sure which parts of the code to change.

# Answer
Change first line:

```
    // Set PB1/2 as outputs.
    DDRB |= (1 << DDB1) | (1 << DDB2);`

```

to the

```
     // Set PB5/6 as outputs. [**Digital pin 11,12 on Arduino Mega!**]
    DDRB |= (1 << DDB5) | (1 << DDB6);

```

Now your PWM should work, but on digital pins 11 & 12 \[Arduino Mega\].
> 2 votes

# Answer
According to this chart: http://arduino.cc/en/Hacking/PinMapping2560

The mega does not support PWM on those digital pins. It looks like 14 of the 54 pins do, use the chart to find which pins to use.
> 0 votes

---
Tags: pwm
---


title: Calculating Angles from MPU6050

text:
# Question
Title: Calculating Angles from MPU6050
I've been playing with a GY521 breakout recently with the MPU6050 chip on it, though i've hit a bit of a problem that I can't quite work out

I know when I rotated the board I rotated ~90 degrees about the Y axis, and using the sensitivity numbers from the datasheet (131) and integrating i've managed to get something that looks believable from the gyroscope, but am having problems with the accelerometer.

From a number of sources, this being one of them, I've managed to get the three equations seen on here, however when I apply them to either the raw or scaled data (as they're scalers is shouldn't make a difference?) I get a set of data that varies from 0 to 90, but only on the X and Z axes, while nothing happens to the Y.

Updated to include code:

```
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"

MPU6050 accelgyro;

int16_t ax, ay, az, gx, gy, gz;

double timeStep, time, timePrev;
double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

int i;
double gyroScale = 131;

void setup() {

  Wire.begin();
  Serial.begin(9600);
  accelgyro.initialize();

  time = millis();

  i = 1;

}

void loop() {

  // set up time for integration
  timePrev = time;
  time = millis();
  timeStep = (time - timePrev) / 1000; // time-step in s

  // collect readings
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  // apply gyro scale from datasheet
  gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;

  // calculate accelerometer angles
  arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
  arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);

  // set initial values equal to accel values
  if (i == 1) {
    grx = arx;
    gry = ary;
    grz = arz;
  }
  // integrate to find the gyro angle
  else{
    grx = grx + (timeStep * gsx);
    gry = gry + (timeStep * gsy);
    grz = grz + (timeStep * gsz);
  }

  // apply filter
  rx = (0.1 * arx) + (0.9 * grx);
  ry = (0.1 * ary) + (0.9 * gry);
  rz = (0.1 * arz) + (0.9 * grz);

  // print result
  Serial.print(i);   Serial.print("\t");
  Serial.print(timePrev);   Serial.print("\t");
  Serial.print(time);   Serial.print("\t");
  Serial.print(timeStep, 5);   Serial.print("\t\t");
  Serial.print(ax);   Serial.print("\t");
  Serial.print(ay);   Serial.print("\t");
  Serial.print(az);   Serial.print("\t\t");
  Serial.print(gx);   Serial.print("\t");
  Serial.print(gy);   Serial.print("\t");
  Serial.print(gz);   Serial.print("\t\t");
  Serial.print(arx);   Serial.print("\t");
  Serial.print(ary);   Serial.print("\t");
  Serial.print(arz);   Serial.print("\t\t");
  Serial.print(grx);   Serial.print("\t");
  Serial.print(gry);   Serial.print("\t");
  Serial.print(grz);   Serial.print("\t\t");
  Serial.print(rx);   Serial.print("\t");
  Serial.print(ry);   Serial.print("\t");
  Serial.println(rz);

  i = i + 1;
  delay(50);

}

```

Results:

Strikes me as a little odd, as I was expecting only a rotational change in Y. Any suggestions?

# Answer
If I understand your question, the main issues are that the axis don't match up, and z from the accel is not accurate?

with respect to the axis: just swap the values. Rotation math is self-consistent and "correct" in many different permutations. What makes it correct is the set of equations, not any single equation; So, copying equations from one reference frame to another will yield incorrect results even if they were correct originally.

your link addresses this difference:

> "Interpreting the diagram at left is a little tricky, since the tilt of the X-axis actually shows rotation around the Y-axis, and the angling of the Y-axis shows (negative) rotation around the X-axis."

```
  ary = -(180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  arx =  (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));

```

should work better for you

On the second point: accelerometers can't measure yaw, the "z" equation can safely be ignored. that isn't yaw it calculates. Calculating z from the gyro alone should fix your second issue.

Other considerations:

* The gyroscope tracking can be made more accurate by using the midpoint rule in your integration
* Your code is not integrating the gyroscope's signal with the best estimate of its last position (rx, ry, rz), instead it integrates the gyro with separate numbers (grx, gry, grz). In effect information from the accelerometer is discarded each loop and gyro drift is not corrected for.
* Thanks for including those graphs with your code samples =\] rotation math is extremely tricky, and graphs help a lot
> 2 votes

---
Tags: arduino-uno, accelerometer, gyroscope
---


# Question
Title: Assigning values to char array causes program to not run
I have the following code:

```
#include "LCD12864RSPI.h"
#include "DFrobot_bmp.h"
#include "DFrobot_char.h"

#define AR_SIZE( a ) sizeof( a ) / sizeof( a[0] )
unsigned char wangzhi[]=" www.DFRobot.com ";
unsigned char fused[1024];

void setup()
{
  pinMode(11, OUTPUT);
  for(int i=0;i<4;i++){
  digitalWrite(11,HIGH);
  delay(1000);
  digitalWrite(11,LOW);
  delay(1000);
  }
  LCDA.initDriverPin(2,7,10);
  LCDA.Initialise(); // INIT SCREEN
}
unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){

  int i=0;
  int ac=0;//a counter
  int bc=0; //b counter
  int cc=0;//c counter

  for(int n=0;n<64;n++){
    for(int k=0;k<5;k++){
      fused[i]=a[ac];
       ac++;
       i++;
    }
       for(int k=0;k<5;k++){
        fused[i]=b[bc];
       bc++;
        i++;
    }
        for(int k=0;k<5;k++){
            fused[i]=c[cc];
            cc++;
             i++;
    }
    fused[i]=0x00;
    i++;
  }

  return fused;
}
unsigned char* getMatch(int input){
  input = input & 0x000f;
  switch (input){
   case 0: return g0;
   case 1: return g1;
   case 2: return g2;
   case 3: return g3;
   case 4: return g4;
   case 5: return g5;
   case 6: return g6;
   case 7: return g7;
   case 8: return g8;
   case 9: return g9;
   case 10: return plus;
   case 11: return minus;
   case 12: return times;
   case 13: return g1;
   case 14: return g1;
   case 15: return g1;
   default: return g1;
  }

}
void displayfuse(int number){
// LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));
}
void loop(){
  displayfuse(0x1234);

}

```

This code is a stripped version of the code I need to run to get a bigger project working. But if it somewhat works than the setup should begin by flashing a LED 4 times before continuing. Currently this works. However as you can see I have commented out the line `LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));`. uncommenting this line causes the LED's to flash continuously rather then just 4 times. The library I'm using can be found here. Does anybody know what is going on? To me the first few lines of a program can be affected by a change somewhere this deep inside the code is a form of dark magic.

Weirdly when I change the setup to the following: void setup()

```
{
  pinMode(11, OUTPUT);
  for(int i=0;i<15;i++){
  digitalWrite(11,HIGH);
  delay(100);
  digitalWrite(11,LOW);
  delay(100);
  }
  for(int i=0;i<4;i++){
  digitalWrite(11,HIGH);
  delay(1000);
  digitalWrite(11,LOW);
  delay(1000);
  }
  LCDA.initDriverPin(2,7,10);
  LCDA.Initialise(); // INIT SCREEN
}

```

it stops flashing completely.

Edit having just reuploaded the code again this time the led just remains on all the time.

edit edit Now with the following code:

```
#include "LCD12864RSPI.h"
#include "DFrobot_bmp.h"
#include "DFrobot_char.h"

unsigned char fuse[1024];
void setup()
{

  LCDA.initDriverPin(2,7,10);

  LCDA.Initialise(); // INIT SCREEN
  pinMode(11, OUTPUT);
  digitalWrite(11,HIGH);

}
unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){
 unsigned char* fused =(unsigned char*)malloc(sizeof(char)*1024);

  int i=0;
  int ac=0;//a counter
  int bc=0; //b counter
  int cc=0;//c counter

  for(int n=0;n<64;n++){
    for(int k=0;k<5;k++){
      fused[i]=a[ac];
      ac++;
       i++;
    }
        for(int k=0;k<5;k++){
      fused[i]=b[bc];
      bc++;
       i++;
    }
        for(int k=0;k<5;k++){
      fused[i]=c[cc];
      cc++;
       i++;
    }
    fused[i]=0x00;
    i++;
  }
  return fused;
}
unsigned char* getMatch(int input){

  input = input & 0x000f;

  switch (input){
   case 0: return g0;
   case 1: return g1;
   case 2: return g2;
   case 3: return g3;
   case 4: return g4;
   case 5: return g5;
   case 6: return g6;
   case 7: return g7;
   case 8: return g8;
   case 9: return g9;
   case 10: return plus;
   case 11: return minus;
   case 12: return times;
   case 13: return g1;
   case 14: return g1;
   case 15: return g1;
   default: return g1;
  }
}
void displayfuse(int number){
 LCDA.CLEAR();
   delay(100);

 int mask1 = 0xF000;
 int mask2 = 0x0F00;
 int mask3 = 0x00F0;

 int firstnumber = number&mask1>>12;
 int operation = number&mask2>>8;
 int secondnumber= number&mask3>>4;

  LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber)));
  delay(5000);
}
void loop(){
  displayfuse(0x1234);
  delay(1000)
}

```

This causes the led to not turn on but moving the lines where I make pin 11 output and high one up (beyond the `LCDA.Initialise(); // INIT SCREEN` ) then the led will turn on. It can also be turned on by commenting out the `LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber)));` line. Magic is happening...

# Answer
The 'dark magic' is going to be your program rebooting every time it gets to that line. I would imagine (this isn't a library I know) that you're exceeding an array bound & generating a 'segfault', although it could be that you light up your LCD array & the power draw causes a reboot.. Because the LED flash is at the start of setup, it executes quickly, so generating the appearance of continual flashing when it re-enters repeatedly. Your code is going to assign g1\[0\] when the line in question executes - is g1\[\] defined to point somewhere valid?
> 1 votes

---
Tags: programming, led, c++
---


title: Problem with fading LEDs

text:
# Question
Title: Problem with fading LEDs
I got a breadboard with 10 LEDs, 4 of them fade, to be specific: 3, 5, 6 and 9 are working. 0, 1, 2, 4, 7, 8 are not working.

I'm using LEDs and resistors on all spots, they're all the same. Tried changing things around but the problem doesn't seem to be the resistors or the LEDs.

I'm using the following code (I'll highlight the parts for the fading, by marking it between `//**` comments).

Does anyone know a way to fix this? Or see any problem?

```
const int inButton = 13;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
int delayTime = 100;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  //**
  pinMode(inButton, INPUT);
  for (int out = 0; out < 10; out++){
    pinMode(out, OUTPUT);
  }
  //**

  pinMode(testLed, OUTPUT);
}

void loop() {
  buttonState = digitalRead(inButton);
  if (buttonState != lastButtonState){
    if (buttonState == 1){
      buttonPushCounter++;
    }
  }

  lastButtonState = buttonState;

  if (buttonPushCounter % 5 == 0){
    for (int i = 0; i < 10; i++){
      digitalWrite(i, 1);
      delay(delayTime / 2);
      digitalWrite(i, 0);
    }
  }
  else if (buttonPushCounter % 5 == 1){
    for (int i = 0, j = 9; i < 10, j >= 0; i++, j--){
      digitalWrite (i, 1);
      digitalWrite (j, 1);
      delay(delayTime / 2);
      digitalWrite (i, 0);
      digitalWrite (j, 0);
    }
  }
  else if (buttonPushCounter % 5 == 2){
    for (int i = 0; i < 10; i+=2){
      digitalWrite(i, 1);
    }
    delay(delayTime);
    for (int i = 0; i < 10; i+=2){
      digitalWrite(i, 0);
    }
    delay(delayTime);
    for (int i = 1; i < 10; i+=2){
      digitalWrite(i, 1);
    }
    delay(delayTime);
    for (int i = 1; i < 10; i+=2){
      digitalWrite(i, 0);
    }
  }
  else if (buttonPushCounter % 5 == 3){
    for (int i = 0 ; i < 10 ; i++){
      analogWrite(i, brightness);
    }
    brightness = brightness + fadeAmount;
    if (brightness == 0 || brightness == 255){
      fadeAmount = -fadeAmount;
    }
    delay(25);
  }
  else {
    int R1 = random(10);
    int R2 = random(10);
    int R3 = random(10);
    int R4 = random(10);
    digitalWrite(R1, 1);
    digitalWrite(R2, 1);
    digitalWrite(R3, 1);
    digitalWrite(R4, 1);
    delay(delayTime);
    digitalWrite(R1, 0);
    digitalWrite(R2, 0);
    digitalWrite(R3, 0);
    digitalWrite(R4, 0);
  }
}

```

# Answer
> 4 votes
Only pins that support PWM support `analogWrite()` fully. 3, 5, 6, 9, 10, and 11 do. The rest do not.

# Answer
> 2 votes
To add to @ignacio-vazquez-abrams answer, the pins that support `analogWrite()` have `~` sign next to their number (on my Uno board they are `9~`, `10~`, `11~` e.g.);

---
Tags: led
---


# Question
Title: Arduino: The program exited the loop early and execute setup() repeatedly
I'm working with Arduino Uno, Adafruit PN532 NFC/RFID Shield and along with other modules. I'm posting this test program because I found there's conflict with the serial output while writing code to integrate all the modules together. I tried troubleshooting by running this code. The result wasn't what I'd expected.

In Arduino, as far as I know, setup() only runs once after starting the program and then loop() will be executed repeatedly. I ran the example sketch called *readMiFare* provided by Adafruit alone and it was fine. This code can be found at https://github.com/adafruit/Adafruit\_NFCShield\_I2C/blob/master/examples/readMifare/readMifare.pde. However, when I did the following in main,

```
void setup()
{
  Serial.begin(115200);
  nfctestsetup();
}

void loop(void)
{
  nfctestloop();
}

```

the following conflict showed up. When happened was that whenever I scanned a card to the reader it executed the loop() partially and exited the loop. Even worse, it executed the setup() again and again whenever I scanned a card.

In nfctestsetup(), I just commented out `Serial.begin(115200);` from readMiFare.

My hardware setup was a no brainer since I'm using I2C.

Appreciate the help.

After spending a good amount of hours on troubleshooting, I found something interesting. When I commented out all other files except NFC and main, it worked like a charm. So I suspect there could be redefinitions on the pins that the NFC shield uses on other files. I suspect the following code in the other file gave me the problem because I commented out the rest of the code in this file and ran this block of code together with NFC and main. In fact, it's the last line of code in this block that gave me the problem.

Also, I probed on the RESET pin (see the readMiFare link above). It generated a high-low-high pulse whenever I scanned a card. Is this related to the problem?

```
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 3     // This should be an interrupt pin, on Uno thats #2 or #3
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

```

Any thought is appreciated.

# Answer
> 1 votes
This can happen when your sketch uses too much memory - the board can no longer assign addresses so it resets leading to an endless loop. Try reducing the amount of memory you are allocating.

---
Tags: bluetooth, rfid, adafruit
---


# Question
Title: Mac won't detect Serial Port for Leonardo
***EDIT:*** *The problem was the cable I was using (see answer below).*

---

I have a MacBook Pro running OS X Yosemite (10.10.1). I connected my Arduino Leonardo to my computer for the first time today (using a Micro USB to USB cable), but my computer isn't detecting it.

When I opened the Arduino IDE I selected Tools \> Board \> "Arduino Leonardo", but when I try to choose a Serial Port the only options are:

* /dev/tty.Bluetooth-Incoming-Port
* /dev/cu.Bluetooth-Incoming-Port
* /dev/tty.Bluetooth-Modem
* /dev/cu.Bluetooth-Modem

I have tried closing and relaunching the Arduino IDE, disconnecting and reconnecting my Arduino Leonardo, and restarting my computer, but I still only see the four Bluetooth ports.

System Information (aka System Profiler) doesn't show anything connected to any of my USB ports.

Thanks in advance!

# Answer
> 1 votes
@IgnacioVazquez-Abrams's comment made me realize that the problem was the Micro USB cable I was using. It gave the Arduino 5V power from my computer, but didn't support any data connection. I'm buying a new cable.

---
Tags: serial, arduino-leonardo, usb, mac-os
---


title: Convert Arduino Pro Mini 5v to use 3.3v

text:
# Question
Title: Convert Arduino Pro Mini 5v to use 3.3v
Id like to make my 5v pro mini use 3.3 v instead of 5 because i want to use it in an existing piece of electronics that uses 3v throughout.

Looking at the specs for the pro mini it says the 3.3v version can accept higher voltages.

So is there a regulator i can bypass/bridge that will convert my 5v version to a 3.3v version? or am i wasting my time?

# Answer
I have good news, and I have bad news.

The good news is that only **two changes** to the board are required to change it from a 5V board to a 3.3V (or any voltage within spec) board.

The bad news is that there's *no way in hell* you'll be able to do them.

So, we work around them and get the board up and running.

The first is obvious: a 3.3V board should be running off of 3.3V. Since we can't replace the SOT23-5 regulator on the board (the little 5-pin device towards the end) we need a voltage regulator to supply this, directly to the VCC pin. Find yourself a linear or switching regulator that provides this voltage.

The second is that the microcontroller, an Atmel ATmega168/P, is not specced to run at 16MHz when the supply voltage is only 3.3V; the maximum speed is 12MHz. Since we can't replace the crystal on the board (the little silver package next to the MCU itself) we need to perform some trickery to tell the MCU divide the frequency down to something way below safe, and then boost it up after. Use a programmer (see some of my other answers for more info about this) to set the CKDIV8 fuse and then use the routines in `avr/power.h` in your code to "reduce" the divisor to 2, bringing the clock speed back up to 8MHz. While you're at it, check the BOD fuses to make sure they're not set to something useless like 0b100.

As always, see the datasheet.
> 10 votes

# Answer
See this nice article by Adafruit, which explains how to run an Arduino **Uno** at 16Mhz with 3.3v. Both the Arduino Pro Mini and the Uno use the same ATmega328p chip, and they claim that even though running at 16Mhz is out of specs, it *should* work.

As **Ignacio** mentioned in his answer, there will be no alternative to downclocking the Mini Pro if you want to play it safe and stay **within the specs**. If you are willing to take the chance, remove the 5v regulator as suggested, and connect a regulated 3.3v to Vin. Consider the hazards; they might include device resets, misbehaving code or malfunctioning I/O pins. If you are using an unregulated 3v voltage source, you will need to step up the voltage - using DC DC step up converter such as this one. (By the way - you could also find a step up converter to 5v \- hence problem solved...)

In addition, see this SO answer for more details. The *safe* clock speed for the ATmega328p operating at 3.3v would be **13.33Mhz**. For reference, here is the Safe Operating Area graph from the datasheet supplied in the answer:
> 4 votes

---
Tags: voltage-level, arduino-pro-mini
---


title: Convert long to char array and back

text:
# Question
Title: Convert long to char array and back
I'm trying to store a state in my data logger. I can read/write fine to SD, but I can't wrap my head around reading/writing a `long` value correctly - I've build it down to converting it to char array and back.

My best try so far has been

```
long temp = 1418172669L;
unsigned char buf[4];
buf[0] = temp         & 0xFF;
buf[1] = (temp >>  8) & 0xFF;
buf[2] = (temp >> 16) & 0xFF;
buf[3] = (temp >> 24) & 0xFF;

long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

```

But `l` is very different from `temp` \- currently the output is `-26371`. Am I making an obvious mistake?

# Answer
I suggest using a union:

```
union {
    char myByte[4];
    long mylong;
} foo;

```

**Char to Long:**

Then you can just add the bytes:

```
foo myUnion;
myUnion.myByte[0] = buf[0];
myUnion.myByte[1] = buf[1];
myUnion.myByte[2] = buf[2];
myUnion.myByte[3] = buf[3];

```

Then you can access the long as:

```
myUnion.myLong;

```

**Long to Char:**

The same if you want to go the other way from long to char array:

```
foo myUnion
myUnion.myLong = 1234L;

```

To access bytes:

```
myUnion.myByte[0];
myUnion.myByte[1];
myUnion.myByte[2];
myUnion.myByte[3];

```
> 9 votes

# Answer
I think the last expression is performed exclusively as an `int` expression and converted to `long` only at the end, i.e. before assignment to `l`.

```
long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

```

Here the compiler calculates `buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24)` as an `int` only.

If you give a hint to the compiler by telling it you want `long` expressions used, then it should work. The easiest way to do so is to replace the number of bits to be shifted as **long literals**:

```
long  l = buf[0] | (buf[1] << 8L) | (buf[2] << 16L) | (buf[3] << 24L);

```

That should be enough for the compiler to perform the whole operation as `long` and not loose precision.
> 1 votes

# Answer
Just for completeness, after posting this, I've found another way around it, but @Phataas solution is much more elegant. Using the `ltoa` and `atol` functions, long to char array and vice-verse can be done like this:

```
char temp[10];
ltoa(669L,temp,10);
long result = atol(temp);

```
> 0 votes

---
Tags: programming, variables
---


# Question
Title: Bipolar LEDs flicker when sensors are polled
Or at least that's what I believe is the problem.

I had to add a bipolar LED library to my sketch to get them to work.

As it is now I only have it activated by a specified bit so it can properly drive yellow. Green and Red were working fine (the flickering problem not withstanding) without the bipolar library.

If I have no sensors enabled in the software (java model railroad interface) I'm using with the sketch, then the bipolar LEDs work fine.

The second I add a sensor, then the arduino starts polling the inputs, at which time the bipolar LEDs (all colors) go all wonky. Their flickering coincides with the flickering of the tx/rx lights on the board, so I'm assuming that the polling of the sensors is what is causing it.

Note that the bipolars are the only LEDs attached to another output pin instead of the ground. It's almost like it's polling any pin that's low at the time, which we obviously don't need/want with the pins for the LEDs.

I even changed the order of the sketch which seemed to slightly effect the flickering, but not enough not to be annoying. Keep in mind my level of understanding programming this is at the level of being able to combine sketches...which conflict led us here.

```
#include <CMRI.h>
#include <CrossingFlasher.h>
#include <BiColorLED.h>

CMRI cmri; // defaults to a SMINI with address 0. SMINI = 24 inputs, 48 outputs
CrossingFlasher crossing(10, 11); // crossbucks
BiColorLED led=BiColorLED(46,47); // (pin 1, pin 2)
BiColorLED led2=BiColorLED(48,49); // (pin 1, pin 2)
BiColorLED led3=BiColorLED(50,51); // (pin 1, pin 2)
BiColorLED led4=BiColorLED(52,53); // (pin 1, pin 2)

void setup() {
  Serial.begin(9600); // make sure this matches your speed set in JMRI
  for (int i=34; i<=53; i++) { pinMode(i, OUTPUT); }
  for (int i=22; i<=33; i++) { pinMode(i, INPUT); digitalWrite(i, HIGH); }
  for (int i=10; i<=11; i++) { pinMode(i, OUTPUT); }
}

void loop() {
  // 1: build up a packet
  cmri.process();

  // 4: update crossing lights. Reads bit 0
  if (cmri.get_bit(0) == true)
    crossing.on();
  else
    crossing.off();

  // 5: update crossing lights
  crossing.update();

  // 6: update Yellow lights. Reads bit 1
  if (cmri.get_bit(1) == true)
    led.setColor(3);
  else
    led.setColor(0);

  led.drive();

  // 7: update Yellow lights. Reads bit 2
  if (cmri.get_bit(2) == true)
    led2.setColor(3);
  else
    led2.setColor(0);

  led.drive();

  // 8: update Yellow lights.
  if (cmri.get_bit(3) == true)
    led3.setColor(3);
  else
    led3.setColor(0);

  led.drive();

  // 9: update Yellow lights.
  if (cmri.get_bit(4) == true)
    led4.setColor(3);
  else
    led4.setColor(0);

  led.drive();

  // 2: update outputs
  digitalWrite(34, cmri.get_bit(5));
  digitalWrite(35, cmri.get_bit(6));
  digitalWrite(36, cmri.get_bit(7));
  digitalWrite(37, cmri.get_bit(8));
  digitalWrite(38, cmri.get_bit(9));
  digitalWrite(39, cmri.get_bit(10));
  digitalWrite(40, cmri.get_bit(11));
  digitalWrite(41, cmri.get_bit(12));
  digitalWrite(42, cmri.get_bit(13));
  digitalWrite(43, cmri.get_bit(14));
  digitalWrite(44, cmri.get_bit(15));
  digitalWrite(45, cmri.get_bit(16));
  digitalWrite(46, cmri.get_bit(17));
  digitalWrite(47, cmri.get_bit(18));
  digitalWrite(48, cmri.get_bit(19));
  digitalWrite(49, cmri.get_bit(20));
  digitalWrite(50, cmri.get_bit(21));
  digitalWrite(51, cmri.get_bit(22));
  digitalWrite(52, cmri.get_bit(23));
  digitalWrite(53, cmri.get_bit(24));

  // 3: update inputs (invert digitalRead due to the pullups)
  cmri.set_bit(0, !digitalRead(22));
  cmri.set_bit(1, !digitalRead(23));
  cmri.set_bit(2, !digitalRead(24));
  cmri.set_bit(3, !digitalRead(25));
  cmri.set_bit(4, !digitalRead(26));
  cmri.set_bit(5, !digitalRead(27));
  cmri.set_bit(6, !digitalRead(28));
  cmri.set_bit(7, !digitalRead(29));
  cmri.set_bit(8, !digitalRead(30));
  cmri.set_bit(9, !digitalRead(31));
  cmri.set_bit(10, !digitalRead(32));
  cmri.set_bit(11, !digitalRead(33));
}

```

I tried all the suggestions and more, same results.

My uneducated guess is the problem is probably with the CMRI.h library. Because I FINALLY managed to actually get the native support for yellow in the software I was using (JMRI) working without any extra bipolar libraries, and guess what? STILL flickers, though this native JMRI support tends to make it more orange/red in color than the bipolar library did (I prefer the later).

The cmri library is actually attempting to make the arduino emulate another piece of hardware, so for all I know it might not even be possible to get it to act right.

I've included both cpp and h scripts. If no one actually figures this out, thanks anyway.

The CMRI.cpp file:

```
/*
CMRI - a small library for Arduino to interface with the C/MRI
computer control system for model railroads
Copyright (C) 2012 Michael Adams (www.michael.net.nz)
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "CMRI.h"
#include <Arduino.h>

CMRI::CMRI(unsigned int address, unsigned int input_bits, unsigned int output_bits, Stream &serial_class)
    // store details
: _address(address)
, _rx_length((output_bits + 7) / 8)
, _tx_length((input_bits + 7) / 8)
, _serial(serial_class)

    // set state
, _rx_buffer((char *) malloc(_rx_length))
, _tx_buffer((char *) malloc(_tx_length))

    // parsing state
, _mode(PREAMBLE_1)
, _rx_index(0)

{
    // clear to zero
    for(int i=0; i<_rx_length; i++)
        _rx_buffer[i] = 0;
    for(int i=0; i<_tx_length; i++)
        _tx_buffer[i] = 0;
}

void CMRI::set_address(unsigned int address)
{
    _address = address;
}

// reads in serial data, decodes packets
// automatically responds to POLL requests
// returns packet type so if we got a SET request you know to update your outputs
bool CMRI::process()
{
    while (_serial.available() > 0)
    {
        if (process_char(_serial.read()))
        {
            return true;
        }
    }
    return false;
}

bool CMRI::process_char(char c)
{
    // if it's a SET that's fine do nothing
    // if it's an INIT that's also fine, we don't really care
    // if it's a GET, well, do nothing since it must be someone else replying
    // if it's a POLL then reply straight away with our data
    switch (_decode(c))
    {
        case POLL:
            transmit();
            return true;

        case SET:
            return true;

        default:
            return false;
    }
}

// public methods

bool CMRI::get_bit(int pos)
{
    // 1: divide index by 8 to get byte offset
    char c = get_byte(pos / 8);
    // 2: return bit at that location
    return (bool) ((c >> (pos % 8)) & 0x01);
}

char CMRI::get_byte(int pos)
{
    if (pos > _rx_length)
        return 0; // out of bounds
    else
        return _rx_buffer[pos];
}

bool CMRI::set_bit(int pos, bool bit)
{
    if ((pos + 7) / 8 > _tx_length)
        return false; // out of bounds
    else
    {
        int index = pos / 8;
        _tx_buffer[index] = bit
            ? _tx_buffer[index] | 1 << pos % 8      // if bit=1, then OR it
            : _tx_buffer[index] & ~(1 << pos % 8) // if bit=0, then NAND it
        ;
        return true;
    }
}

bool CMRI::set_byte(int pos, char b)
{
    if (pos > _tx_length)
        return false; // out of bounds
    else
    {
        _tx_buffer[pos] = b;
        return true;
    }
}

void CMRI::transmit()
{
    delay(50); // tiny delay to let things recover
    _serial.write(255);
    _serial.write(255);
    _serial.write(STX);
    _serial.write(65 + _address);
    _serial.write(GET);
    for (int i=0; i<_tx_length; i++)
    {
        if (_tx_buffer[i] == ETX)
            _serial.write(ESC); // escape because this looks like an STX bit (very basic protocol)
        if (_tx_buffer[i] == ESC)
            _serial.write(ESC); // escape because this looks like an escape bit (very basic protocol)
        _serial.write(_tx_buffer[i]);
    }
    _serial.write(ETX);
    _serial.flush();
}

// Private methods
uint8_t CMRI::_decode(uint8_t c)
{
    switch(_mode)
    {
        case PREAMBLE_1:
            _rx_index = 0;
            if (c == 0xFF)
                _mode = PREAMBLE_2;
            break;

        case PREAMBLE_2:
            if (c == 0xFF)
                _mode = PREAMBLE_3;
            else
                _mode = PREAMBLE_1;
            break;

        case PREAMBLE_3:
            if (c == STX)
                _mode = DECODE_ADDR;
            else
                _mode = PREAMBLE_1;
            break;

        case DECODE_ADDR:
            if (c == 'A' + _address)
                _mode = DECODE_CMD;
            else if (c >= 'A')
                _mode = IGNORE_CMD;
            else
                _mode = PREAMBLE_1;
            break;

        case DECODE_CMD:
            if (c == SET)
                _mode = DECODE_DATA;
            else if (c == POLL)
                goto POSTAMBLE_POLL;
            else
                _mode = POSTAMBLE_OTHER;
            break;

        case IGNORE_CMD:
            _mode = IGNORE_DATA;
            break;

        case DECODE_DATA:
            if (c == ESC)
                _mode = DECODE_ESC_DATA;
            else if (c == ETX)
                goto POSTAMBLE_SET;
            else if (_rx_index >= _rx_length)
                { }
            else
                _rx_buffer[_rx_index++] = c;
            break;

        case DECODE_ESC_DATA:
            if (_rx_index >= _rx_length)
                { }
            else
                _rx_buffer[_rx_index++] = c;
            _mode = DECODE_DATA;
            break;

        case IGNORE_DATA:
            if (c == ESC)
                _mode = IGNORE_ESC_DATA;
            else if (c == ETX)
                goto POSTAMBLE_IGNORE;
            break;

        case IGNORE_ESC_DATA:
            _mode = IGNORE_DATA;
            break;

        case POSTAMBLE_OTHER:
            _mode = PREAMBLE_1;
            break;
    }
    return NULL;

POSTAMBLE_SET:
        _mode = PREAMBLE_1;
        return SET;

POSTAMBLE_POLL:
        _mode = PREAMBLE_1;
        return POLL;

POSTAMBLE_IGNORE:
        _mode = PREAMBLE_1;
        return NULL;
}

```

The CMRI.h file:

```
    /*
    CMRI - a small library for Arduino to interface with the C/MRI
    computer control system for model railroads
    Copyright (C) 2012 Michael Adams (www.michael.net.nz)
    All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
*/

#ifndef CMRI_h
#define CMRI_h

#define _CMRI_VERSION 1.5 // version of this library
#include <Arduino.h>

class CMRI
{
    public:
        CMRI(unsigned int address = 0, unsigned int input_bits = 24, unsigned int output_bits = 48, Stream& serial_class = Serial);
        void set_address(unsigned int address);

        bool process();
        bool process_char(char c);
        void transmit();

        bool get_bit(int n);
        char get_byte(int n);

        bool set_bit(int n, bool b);
        bool set_byte(int n, char b);

        enum {
            MAX  = 258, // max packet length in bytes (64 i/o cards @ 32 bits each + packet type and address bytes)
            INIT = 'I', // PC is telling us stuff we don't really care about
            SET  = 'T', // as in TX from the PC => Arduino, PC is SETing our status
            GET  = 'R', // as in TX from Arduino => PC, PC is GETing our status
            POLL = 'P', // PC wants to know our status
            STX  = 0x02, // start byte
            ETX  = 0x03, // end byte
            ESC  = 0x10, // escape byte
        };

private:
        enum {PREAMBLE_1,PREAMBLE_2,PREAMBLE_3,DECODE_ADDR,DECODE_CMD,DECODE_DATA,DECODE_ESC_DATA,IGNORE_CMD,IGNORE_DATA,IGNORE_ESC_DATA,POSTAMBLE_SET,POSTAMBLE_POLL,POSTAMBLE_OTHER};

        int   _address;
        int   _rx_length;
        int   _tx_length;
        char    _rx_packet_type;
        char* _tx_buffer;
        char* _rx_buffer;

        Stream& _serial;

        // parsing state variables
        int     _mode;
        int     _rx_index;

        uint8_t    _decode(uint8_t c); // process one character received from serial port
};

#endif

```

# Answer
The yellow color is make by very quickly alternating between red and green. If you do this fast enough your eyes won't notice. This alternating is done inside `led.drive();`. If you are polling the sensors, `led.drive();` isn't called and the leds aren't alternating for a moment.

Best way would be to use a timer to call `led.drive();` every 9ms or less. You could use the timerOne library. I've never used that library, but I think you should use the following code.

```
#include "TimerOne.h"

...

void setup {
    Timer1.initialize(9000);// call every 9ms
    Timer1.attachInterrupt(callback);

...

void callback()
{
    led.drive();
}

```

remove all other led.drive calls
> 3 votes

# Answer
You have your LED's across one of the serial I/O lines (Pin 1). Use different pins.
> 1 votes

---
Tags: led
---


# Question
Title: Setting timer3 in CTC mode - conflict with servo library
I would like to set up a timer in order to call a function 800 times per second. I'm using the Arduino Mega and Timer3 with a prescaler of 1024. To choose the prescaler factor I've considered the following steps:

* CPU freq: 16MHz
* Timer resolution: 65536 (16 bits)
* Divide CPU freq by the chosen prescaler: 16x10^6/**1024**=15625
* Divide the rest through the desired freq 62500/800=**19**.
* Put the result + 1 in OCR3 register.

I've used the following table to set registers of TCCR3B:

**The error**

It is impossible to compile the code. This is the error returned by the compiler:

> Servo\Servo.cpp.o: In function '\__vector\_32': C:\Program Files (x86)\Arduino\libraries\Servo/Servo.cpp:110: multiple definition of '\__vector\_32' AccelPart1\_35.cpp.o:C:\Program Files (x86)\Arduino/AccelPart1\_35.ino:457: first defined here c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

**The code**

```
volatile int cont = 0;
unsigned long aCont = 0;
void setup()
{
 [...]
  // initialize Timer3
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3A);
  // enable global interrupts:
  sei();
}

void loop()
{
 // Print every second the number of ISR invoked -> should be 100
 if ( millis() % 1000 == 0)
 {
   Serial.println();
   Serial.print(" tick: ");
   Serial.println(contatore);
   contatore = 0;
 }
}

[...]

// This is the 457-th line
ISR(TIMER3_COMPA_vect)
{
    accRoutine();
    contatore++;
}

void accRoutine()
{
  // reads analog values
}

```

How to solve the conflict with the servo library?

**SOLUTION**

Conflict solved using the following code. It compiles but the counter associated with the 800Hz timer doesn't increment its value.

```
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

```

Since the main problem has been solved, I've created another question here related to the problem of the counter incrementation.

# Answer
Unfortunately, The Servo library reserves output compare A (OCR\*A) on timers 1,3,4, and 5 when loaded on an arduino mega. Each can only have one ISR, so you will not be able to define your own TIMER\*\_COMPA\_vect while you use Servo without modifying the library.

However, each hardware timer is equipped with 2 output compare registers. Servo does not claim any TIMER\*\_COMPB\_vect interrupts, so those are free to use, and work exactly the same.

You should watch out for the Servo libraries activities, it could change the configuration of your timer. The default order is on megas is 5,1,3,4 and to give each 12 servos. It only configures the timer once it needs it, so you should be fine using timer 3 until you add that 25th servo.

To change your code, use OCR3B instead of OCR3A (the Output Compare Registers) and set bit OCIE3B instead of OCIE3A in TIMSK3 (the Output Compare Interrupt Enable bits). Then you to change your ISR function to `ISR(TIMER3_COMPB_vect){}`

CTC mode only works with OCR3A, but if you set TCNT3 to 0 in your interrupt function you can get similar behavior. Remember to remove the line that turns CTC mode on using WGM12.
> 3 votes

---
Tags: arduino-mega, timers, compile, avr-gcc
---


title: Source Code for strcpy and strcat

text:
# Question
Title: Source Code for strcpy and strcat
Does anyone know the location of the assembler file for strcpy and strcat for the Arduino? I wish to modify it.

# Answer
The Arduino IDE doesn't ship with the source/assembly for a lot of the core functionality. It comes pre-compiled in object/library files.

However, you could download the source code for AVR Libc from this site:

Obviously there's no guarantee that the files you download will exactly match what comes with the Arduino IDE, but it's useful if you're interested in how they're implemented.

When you've downloaded and extracted the source code, look in the `libc/string` folder. you should find assembly files called `strcat.S` and `strcpy.S`.

As jfpoilpret says in the comments, attempting to modify core library functions is generally not a good idea. They may be getting called by other parts of the core, so any changes you make could break something else.
> 5 votes

---
Tags: core-libraries
---


# Question
Title: Why can this color sensor not recognize green?
I got this color sensor last week, I've been able to get the sensor to recognize blue and red, but not green. still working on this. I use the code in the product page.

so anybody have any idea about this issue? Pretty thanks.

# Answer
> 4 votes
Check that you've connected all the Arduino pins correctly to the sensor. In particular, make sure pin 4 on the Arduino is connected to S2 on the sensor.

It's the combination of signals on S2 and S3 which determines which colour is being detected:

```
S2    S3    Colour
----  ----  ------
Low   Low   Red
Low   High  Blue
High  Low   Clear
High  High  Green

```

If S2 is always low then you can only detect red and blue.

If the connections are definitely correct, then ensure you haven't made any code modifications which could interfere with it. You may also want to test pin 4 on your Arduino (e.g. using a multimeter) to make sure it's working properly. If necessary, you could use a different pin instead. However, you'll need to modify the `#define S2` line in the code to match.

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