# Question
Title: Using union to return a range of bits from a data frame: wrong approach?
I'm working on an adaptation of Jason Leyrer's Guitar Hero Library for Arduino. My version is for a DJ Hero controller, and I've also borrowed some code from this Arduino forum thread: topic=120527 (sorry can't post links yet).

The protocol is i2c and I am successfully reading data from it, however I'm not 100% sure what to do with the data.

The buttons are fine, as they are mapped to just one bit in a given byte. However the other controls are a combination of 4, 5 and 6 bit longs.

The format according to Wiibrew is like so:

* `BE` is for Euphoria button
* `CS` : Crossfade Slider, lower is left and upper is right
* `SX` and `SY` are the black analog stick.
* `ED` is the Effect Dial
* `RTT` is the turntable on the right as a 6-bit signed integer (positive = CW; negative = CCW)
* `RBG`,`RBR`,`RBB` are the Green, Red and Blue buttons on the right
* LTT is the turntable on the left as a 6-bit signed integer (positive = CW; negative = CCW)
* `LBG`,`LBR`,`LBB` are the Green, Red and Blue buttons on the left

I'm trying to do this:

```
 signed long DJ_ED()
{
  pack5 ED;
  ED[0] = (DJ_buf[3] >> 5) & 1;
  ED[1] = (DJ_buf[3] >> 6) & 1;
  ED[2] = (DJ_buf[3] >> 7) & 1;
  ED[3] = (DJ_buf[2] >> 5) & 1;
  ED[4] = (DJ_buf[2] >> 6) & 1;

  return ED;
}

```

Where pack5 is the following:

```
#define packet5
union pack5
{
   signed long value;
   int ints[5];
};

```

but I'm getting the following error:

`no match for 'operator[]' (operand types are 'pack5' and 'int')`

What am I doing wrong?

# Answer
You are using a union so you have to specify which part of the union you want. Your function should read:

```
 signed long DJ_ED()
{
  pack5 ED;
  ED.ints[0] = (DJ_buf[3] >> 5) & 1;
  ED.ints[1] = (DJ_buf[3] >> 6) & 1;
  ED.ints[2] = (DJ_buf[3] >> 7) & 1;
  ED.ints[3] = (DJ_buf[2] >> 5) & 1;
  ED.ints[4] = (DJ_buf[2] >> 6) & 1;

  return ED.value;
}

```

It still looks wrong because you are only putting a single bit into those 5 bytes (because of the & 1). And 5 x int will be a lot longer than one signed long.

---

The code below seems to match the data structure you posted an image of:

```
struct packedFields
{
  // byte 0
  unsigned int sx      : 5;
  unsigned int rtt_4_3 : 3;

  // byte 1
  unsigned int sy      : 5;
  unsigned int rtt_2_1 : 3;

  // byte 2
  unsigned int rtt_5   : 1;
  unsigned int cs      : 4;
  unsigned int ed_4_3  : 2;
  unsigned int rtt_0   : 1;

  // byte 3
  unsigned int ltt_4_0  : 5;
  unsigned int ed       : 3;

  // byte 4
  unsigned int ltt_5    : 1;
  unsigned int rbr      : 1;
  unsigned int b_plus   : 1;
  unsigned int filler_2 : 1;
  unsigned int b_minus  : 1;
  unsigned int lbr      : 1;
  unsigned int filler_1 : 2;

  // byte 5
  unsigned int filler_4 : 2;
  unsigned int rbb      : 1;
  unsigned int lbg      : 1;
  unsigned int be       : 1;
  unsigned int rbg      : 1;
  unsigned int filler_3 : 1;
  unsigned int lbb      : 1;

};

union packedFieldsUnion
  {
  packedFields a;
  byte b [6];
  };

void doSomethingWithTheFields (packedFieldsUnion & theFields);  // prototype
void doSomethingWithTheFields (packedFieldsUnion & theFields)
  {
  theFields.a.rtt_4_3 = 3;
  theFields.a.ltt_4_0 = 2;
  }  // end of doSomethingWithTheFields

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("packedFields sized = "));
  Serial.println (sizeof (packedFields));

  packedFieldsUnion foo;
  memset (&foo, 0, sizeof foo);

  doSomethingWithTheFields (foo);

  Serial.println (F("-- packedFields bytes --"));
  for (int i = 0; i < sizeof foo; i++)
    Serial.println ((int) foo.b [i], HEX);

  }  // end of setup

void loop ()
  {
  }  // end of loop

```

I have a bitwise struct, as Ignacio Vazquez-Abrams suggested. Testing indicates you put the low-order bits first. Then I made a union of this struct and 6 bytes. You can't fit the whole thing into a signed long anyway (a long is 4 bytes) so that part of your code was doomed to fail.

A small bit of test code proves that the bits are being accessed in the correct way. You still need to fiddle around with things like RTT which has individual bits scattered in different places.

---

If you look at the data format you posted there are 6 bytes, not 5. They are numbered 0, 1, 2, 3, 4, 5. A total of six of them.
> 1 votes

---
Tags: arduino-mega, i2c, library, data-type, byte-order
---


# Question
Title: Suggest me an Arduino development board, with a removable ATmega chip?
I want to buy an arduino development board which has facility to remove its chip and insert a new one anytime. I want to use multiple chips in a single board for different purposes.

If it is not possible, Please suggest me any alternative.

# Answer
> 4 votes
Only the Arduino Uno has a socketed IC chip. All the rest are using soldered SMD ICs.

# Answer
> 2 votes
You could get an ATmegaXX8 target board from Evil Mad Scientist. That has (or can have) a ZIF socket so you can easily remove the chip without bending its legs.

That's around $US 3 for the board, $2 for the ZIF socket, $1 for the crystal, 45 cents for the ICSP header.

You can put an Atmega328P into the socket (same chip as on the Uno). Note that *some soldering is required*. You would need to solder on the ZIF socket, the ISP header, and make up an FTDI header if you wanted to easily program it from the IDE.

You would also need (or it would be helpful to have) a 16 MHz crystal along with 2 x 18 pF capacitors. They have them for sale at that site.

You would also need a 10 k pull-up resistor for Reset, a couple of 0.1 µF decoupling capacitors, and another 0.1 µF capacitor for handling reset via the FTDI interface - if you use it.

If you want to program serially (and do serial debugging) you need some sort of USB interface, such as an FTDI cable or board.

Example FTDI Serial TTL-232 USB Cable.

That is around $US 18. (Of course, you only need to buy the cable once, so this is a one-time cost).

You would need to solder in 6 header pins in a line to plug that into (on the prototyping area) and then run appropriate wires to Tx/Rx/Gnd/5V and Reset via the 0.1 µF capacitor I mentioned.

Adafruit have an Arduino bootloader-programmed chip (Atmega328P) for $US 6.

All-up it would probably cost you around $US 30 to put it together. (The FTDI cable is a once-off cost, as you can use that on multiple projects).

---

Other vendors will probably have similar products.

# Answer
> 2 votes
The ultimate solution would be to build it yourself!

Arduino has an excellent step by step guide on how to build a standalone Arduino, using a ATMega328, on a breadboard. Now everything is removable, not just the chip.

Note that there is one slight error in the guide, which I have highlighted here, Arduino Standalone - photo shows incorrect pin wired to MOSI.

There is a video on how to achieve, more or less, the same thing, 1-Day Project: Build Your Own Arduino Uno for $5.

# Answer
> 0 votes
It is possible, you could probably do it on most of the Arduino boards too.

This page on the Arduino website may help you - https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

I have personally never attempted it but I know quite a few people who have and they have never had too many big issues.

# Answer
> 0 votes
If the question is driven by need of minimizing the overall cost, well, on ebay you can find plenty of Arduino Mini Pro at about $2, shipment included. Add an USBASP programmer at the cost of $5 and you get a solution which is still pretty cheap and allows each board to be used, rather than having just one with multiple chips to insert/remove. At a fraction of the cost of the other solutions described here.

---
Tags: multiplexer
---


title: I2Cdev #include weirdness

text:
# Question
Title: I2Cdev #include weirdness
I am using Jeff Rowberg's MPU6050 library, and I simply don't understand what is going on in the following lines of the first example (MPU6050\_raw.ino):

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

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE
// implementation is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include <Wire.h>
#endif

```

So, what I got from that is, if I2Cdev is using Wire instead of some alternative I2C library, I should include Wire.h. I really don't see why that's necessary, so I removed the line in which Wire.h is included, and got this error:

```
C:\Users\Franco2500k\Documents\Arduino\libraries\I2Cdev/I2Cdev.h:80:26: fatal error: Wire.h: No such file or directory
     #include <Wire.h>

```

So, apparently, I2Cdev.h already tries to include Wire.h, but somehow fails? And another #include a few lines later goes back in time and fixes everything? Can someone explain what is going on?

# Answer
> 1 votes
The Arduino IDE means well, really it does. It copies your source, the device core, and any libraries used by your source all to a separate directory so that it doesn't poison any of their original locations unintentionally.

But of course, there's something missing from that list. The IDE *doesn't copy libraries used by other libraries*. Therefore if you don't include Wire.h in your .ino file then Wire will be missing from the build and you get the error observed. Cracktastic.

---
Tags: mpu6050
---


title: ATtiny461 PWM CTC mode help

text:
# Question
Title: ATtiny461 PWM CTC mode help
I am a beginner at AVR and programming. I am using ATtiny461 and asked to make code to use timer in PWM and CTC mode and use interrupts and pin toggle, this code worked for me with normal timer and toggle but I don't know how to make it work with CTC and PWM:

```
#include <avr/io.h>
#include <avr/interrupt.h>

//Init PD6 pin as output
void InitPort(void)
{
    PORTB&=~(1<<PB1);//initial value 0
    DDRB|=(1<<PB1);
}
//Initialize Timer0
void InitTimer0(void)
{
    //Enable Timer0 overflow Interrupt
    TIMSK|=(1<<TOIE0);
    //Set Initial Timer value
    TCNT1=5;
}
void StartTimer0(void)
{
    //Set prescaller 64 and start timer
    TCCR0B|=(1<<CS01)|(1<<CS00);
    //Enable global interrupts
    sei();
}
//Timer0 Overflow ISR
ISR(TIMER0_OVF_vect)
{
    //Reset Initial Timer value
    TCNT1=5;
    //toggle PD6 pin
    PINB=(1<<PB1);
}

int main(void)
{
    InitPort();
    InitTimer0();
    StartTimer0();
    while(1)
    {
        //doing nothing
    }
}

```

and I know those commands for setting fast PWM and CTC:

```
TCCR1D |= (0<<WGM10)|(0<<WGM11);
TCCR1A |= (1<<PWM1A)|(1<<COM1A0)|(0<<COM1A1);

```

# Answer
PWM is only supported for timer1 on the ATTiny461. Not in timer0.

Look at TCCR1A; specifically the COM1xn bits.
> 1 votes

---
Tags: pwm, attiny, avr, atmel-studio
---


# Question
Title: How can I build a simple "Smartwatch" with Arduino Pro Mini and Display?
I want to know how I can build a simple "Smartwatch" with an Arduino Pro Mini and a Display with a size from maybe 1,5" what Display should I use for Touch and color?

I only want simple things like synchonising the time with my Smartphone trough a HC-06 Bluetooth Module.

# Answer
> 1 votes
If your goal is to make a watch you'll need a RTC (Real Time Clock) this can take the form of breakout board, or you can build the circuit yourself. The RTC is needed if you want the mini to display the time. The mini (in fact, most micros) have no internal clock (though they may have a crystal that can simulate time keeping, but this isn't as useful if you want the time)

It sounds like you want an OLED display. They come in watch-like sizes. There are a few small ones. None are touch displays. I have seen larger touch displays. Maybe combine an OLED with a clear capacitive surface?

---
Tags: bluetooth, arduino-pro-mini, time
---


title: Not in sync: resp=0x00

text:
# Question
Title: Not in sync: resp=0x00
I had problems with Arduino uno and reseted firmware. Followed this tutorial. Now I can't upload my code Arduino IDE says:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

```

I tried loop-back mode, everything is fine.

Firmware was located in this location:

```
/usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

```

# Answer
There are two processors on the Uno board.

* The Atmega328P which is the "main" processor with your sketches on it
* The Atmega16U2 which handles the USB interface

> Firmware was located in /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

Hopefully you reflashed the **Atmega16U2** with that file. Did you?

> I tried loop-back mode, everything is fine.

Therefore the Atmega16U2 is OK. The problem may be with the Atmega328P.

---

> I had problems with Arduino Uno and reseted firmware.

You shouldn't need to do this, I never reflash the firmware on my Atmega16U2.

What problems did you have? Did it involve motors? LEDs? High voltages? Sparks? Flames? Screaming?

Please see the steps described here, run through them, and see if that fixes the problem: Have I bricked my Arduino Uno? Problems with uploading to board
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How can I turn this into an (Ableton) controller?
I found this lovely decade box in a demolished house recently and want to turn it into an Ableton controller. As you see, there are 18 knobs, each with 12 individual states.

I'd like to have a program which can access the states of all the knobs at any time, and I have an arduino which I can use. Is this possible to do without a shield?

My first thought is that, since many of the leads on the back already have resistors on them, I could use a sort of total-resistance-across-the-connection approach which would suit itself to the analog inputs. But I'm not sure that's the way to go, especially if I want very low latency.

How can I wire up a board that has digital access to all the pins here? How does a multiplexer play into this? How many inputs would I need? I am super new to this kind of stuff, so I imagine this must be a pretty simple answer.

Thanks for your help.

# Answer
The other answers are excellent, however I want to address this question:

> How does a multiplexer play into this?

Just as an example of how multiplexing helps, I opened up a scrolling LED sign which has 504 individual LEDs which "appear" to be all on at once (if wanted).

Internally were 10 x 74HC595 serial shift registers. 9 of them were hooked up to the individual columns (giving 72 columns), and the last one was connected to the 7 rows.

```
 9 * 8 =  72    columns
72 * 7 = 504    LEDs

```

Thus we could turn on 504 LEDs. However to have individual LEDs appear to come on the code has to turn on one row (out of the 7) and then output the pattern for that row to the 72 columns. Then it switches to another row, does the next pattern, and so on.

I have a video of this effect on Vimeo.

If you do it fast enough, all the LEDs appear to be one at once.

---

Now you can do this for switches too, just connect all the individual positions together, and then apply "power" to each switch in sequence, and read the results. This time you want an **input** shift register, eg. the 74HC165 for the reading, and an output register for powering each switch.

The problem is with switches though, that you would get "phantom" reads because switches aren't diodes (or, worse, the inactive switches would short the power to ground). So you would need a **diode** in series with each switch to prevent that. Ah well, diodes are cheap.

This is exactly the same concept as the way keypads work. Say, a 16-key keypad will have 8 wires: 4 rows and 4 columns.

---

Having said all that, you will still need quite a few chips unless you set up quite a complex "simulated" keypad array. Maybe it wouldn't be too bad.

You have 17 switches so that would be 2 x 74HC595 for activating each switch, plus one spare pin on the Arduino. And the switches seem to have around 12 positions, so that would be 2 x 74HC165 to read which position it was at.

So, for each switch, you make that one HIGH and the others LOW. Current will flow through the diodes and the rotary switch, presenting a HIGH on one of the 12 "reading" pins. The diodes stop the current from shorting the HIGH to the LOW through other switches.

You take a reading, and move onto the next switch. This can be done quickly, in the same way the LED sign scrolls so fast you can't spot any flickering.

This schematic illustrates the idea:

In this example we apply a HIGH to the common part (rotor) of the left switch. It goes through the diode, and the selected position, to make input "read 1" high. The diode on the other switch prevents the HIGH from being shorted to the LOW, even though both switches are in the same position.

You would need a pull-down resistor for each of the 12 "reading" lines, so that if they weren't being forced HIGH, they would read LOW. And one diode per rotary switch. So, not too many extra parts. And the wiring is simple, just connect each corresponding switch pin together (except for the common one, of course).

I think this will work, unless anyone can see a major flaw. :)
> 1 votes

# Answer
The hard part here is that you essentially have 216 inputs you need to read.

You could multiplex the analog pins using two 74HC4051. Analogread takes around 0.1ms, so around 2ms for all 18 knobs. Debouncing would however be pretty hard.

I'd probably go with input shift registers, and remove all the resistors. You would however need 27 8-bit shift register (3 registers per 2 knobs).

To reduce this you could encode the rotary position into 4-bit using a diode network. That way you can use only 1 shift register per 2 knobs. So 9 in total.
> 1 votes

# Answer
You can use the analog route by using a CD74HC4067, then you can hook it up to a analog demultiplexer, such as the CD74HC4067(breakout from SFE) which has 16 analog/digital inputs. You would use one of these and two analog pins, one from the breakout and one from the panel, as there are 17 dials from what I can see.

An example of a resistor ladder:

The 4067 is addressed using 4 digital pins to make up a binary address relating to each input. You would put this into a for loop and read from each address and put in an array of values each time you loop. And when leaving the loop read the last analog value. I would use port manipulation to write the address as it would speed up the operation.

Once you have the values in the array you can then do the math require to get where the dial is or you can do that as you read the analog pin the the for loop, kind of keep it all in one function. You can find the calculation for converting in the Wikipedia article, the R-2R style.

Bildr have a nice write up with some code, an image of the basic setup:
> 1 votes

---
Tags: wires, prototype, multiplexer
---


# Question
Title: Converting Arduino UNO's analog pins to digital I/O
I am working on an Arduino UNO Project and running out of digital pins.

Can I convert the six analog pins to digital I/O and use them to drive servos?

Please suggest me a method

# Answer
> 4 votes
A0 through A5 already have GPIO capability; treat them as you would any other non-PWM pin.

A6 and A7, found in similar boards that use a SMD package, do not have any GPIO capability whatsoever and can only be used for analog input.

---
Tags: pins, servo
---


# Question
Title: Arduino + 4051 -> noise on certain 4051 pins
I am trying to use two `4051` ICs with an Arduino Micro right now. The idea was to have an 16-sensor demo station (8 sensors per `4051`) wherein each `4051` pin selection is controlled by a potentiometer as input. I am new to using MUX's, so I mocked the following up as a quick demo based on this help document via Arduino (it's basically the same), which only uses one `4051` and does not use a potentiometer as selector input. So, I should be able to set the variable `which` to whatever number (0 - 7) to change the sensor selection that shows up at `A2` on the Arduino.

Setting `which` to 0 is fine, but when I have more than two sensors plugged into `4051` and set the selector pin to any other number than 0 there is a strong likelihood that the output that shows up in the `Serial Monitor` is both unresponsive to the selected sensor change and appears to be simply noise (random numbers around 200 or so). I have been trying to isolate where this noise is coming from and am totally stumped. Has anyone had this issue and, if so, any suggestions on how to further diagnose what is happening? I am currently powering everything off of the Arduino `5V`, which I am under the impression should be okay, though I have tried this with external power supplies (`12V at 2A`, for example) and gotten the same results (so I am fairly certain power is not the issue here).

Measuring voltage on pins 2, 3, and 4, I am seeing 1mV on pin 2, 1mV on pin 3, and 0.9mV on pin 4 following the initial spike during upload. When comparing against the Arduino 4051 doc I linked to above, I see that in that file pins 2, 3, and 4 show a Voltage of 2.5V following the initial spike during upload. Any idea what I am doing incorrectly?

```
/*
Sensor Station via MUX

 * code example for useing a 4051 * analog multiplexer / demultiplexer
 * by david c. and tomek n.* for k3 / malmï¿½ hï¿½gskola
 *
 * edited by Ross R.
 */

int r0 = 0;      //value of select pin at the 4051 (s0)
int r1 = 0;      //value of select pin at the 4051 (s1)
int r2 = 0;      //value of select pin at the 4051 (s2)
int which = 0;   //which y pin we are selecting
int val;

void setup() {
  pinMode(A2, INPUT);       // mux1 input
  pinMode(2, OUTPUT);    // s0
  pinMode(3, OUTPUT);    // s1
  pinMode(4, OUTPUT);    // s2
}

void loop () {

  which = (0);

  // select the bit
  r0 = bitRead(which, 0);
  r1 = bitRead(which, 1);
  r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

  digitalWrite(2, r0);
  digitalWrite(3, r1);
  digitalWrite(4, r2);

  //Either read or write the multiplexed pin here
  // refactor, this should be digitalWrite with millis or something
  val = analogRead(A2);     // MUX ouputs here

  Serial.print("sensor number ");
  Serial.print(which);
  Serial.print('\t');
  Serial.print("val is ");
  Serial.println(val);

  delay(2);
}

```

# Answer
I have a post about that chip at 74HC4051 multiplexer / demultiplexer.

I made up the circuit shown on my page above with modifications as described below:

I moved the A/B/C and O/I pins to match your code.

A is the **low-order bit** so pin 11 on the 74HC4051 should go to D2 on the Arduino.

```
74HC4051  Arduino   Meaning
    11       D2        A
    10       D3        B
     9       D4        C
     3       A2        O/I

```

I put a pot on I/O0 (pin 13 on the 74HC4051) and randomly set the other pins to +5 V or Gnd, as shown.

---

In `setup()` I added:

```
Serial.begin (115200);

```

I also modified it to automatically sequence through all 8 possible ports, and then stop after 1000 iterations to stop flooding the USB port on my computer. Code is:

```
int r0 = 0;      //value of select pin at the 4051 (s0)
int r1 = 0;      //value of select pin at the 4051 (s1)
int r2 = 0;      //value of select pin at the 4051 (s2)
int which = 0;   //which y pin we are selecting
int val;

void setup() {
  Serial.begin (115200);
  pinMode(A2, INPUT);       // mux1 input
  pinMode(2, OUTPUT);    // s0
  pinMode(3, OUTPUT);    // s1
  pinMode(4, OUTPUT);    // s2
}  // end of setup

unsigned long counter;

void loop () {

  // select the bit
  r0 = bitRead(which, 0);
  r1 = bitRead(which, 1);
  r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

  digitalWrite(2, r0);
  digitalWrite(3, r1);
  digitalWrite(4, r2);

  //Either read or write the multiplexed pin here
  // refactor, this should be digitalWrite with millis or something
  val = analogRead(A2);     // MUX ouputs here

  Serial.print("sensor number ");
  Serial.print(which);
  Serial.print('\t');
  Serial.print("val is ");
  Serial.println(val);

  delay(2);

  if (++which > 7)
    which = 0;

  if (++counter >= 1000)
    {
    Serial.flush ();
    exit (1);
    }
}  // end of loop

```

---

The output from your sketch was as expected:

```
sensor number 0 val is 781
sensor number 1 val is 0
sensor number 2 val is 1023
sensor number 3 val is 1023
sensor number 4 val is 0
sensor number 5 val is 0
sensor number 6 val is 0
sensor number 7 val is 1023

```

I suggest you check that your wiring agrees with mine.
> 2 votes

---
Tags: power, arduino-micro, multiplexer
---


# Question
Title: Arduino Bluetooth connection with Android
I am wondering why my Arduino program won't start its sketch to connect a bluesmirf to an android device and send data to the android whenever I use an external power supply. The sketch starts whenever i open the serial monitor, but using the power supply, it wont work.

# Answer
> 2 votes
You'll probably find that you are not supplying enough power to operate the Arduino and the components attached to the Arduino. Your current (Amps) draw is most likely higher than your external power supply can output.

I had this problem when using a 9v battery to power an Arduino with an XBee chip and some LEDs attached. The 9v would be able to power the kit for a while but would then not output enough current to power the Arduino. In the end I had to scrap a few LEDs.

You need to find out how much current your Arduino and its components are using and use a suitable power supply that can output enough current to power your Arduino.

Also remember when you send and receive a packet out of a Bluetooth radio - more current is required than when the Bluetooth radio is idle.

---
Tags: serial, programming, bluetooth
---


# Question
Title: Processing error with processing-arduino examples
I have followed the instructions to run the Arduino processing examples but with no success.

Always `import processing.serial.*;` does not name a type. Which is perhaps a library (processing-arduino) related error.

My sketch is a sketch that comes with processing-arduino library.

I have searched for a long time with no solution. Any suggestion?

Errors:

```
arduino_output:28: error: 'import' does not name a type
arduino_output:30: error: 'import' does not name a type
arduino_output:32: error: 'Arduino' does not name a type
arduino_output:34: error: 'color' does not name a type
arduino_output:35: error: 'color' does not name a type
arduino_output:37: error: expected unqualified-id before '[' token
arduino_output.pde: In function 'void setup()':
arduino_output:42: error: 'size' was not declared in this scope
arduino_output:45: error: 'Arduino' was not declared in this scope
arduino_output:45: error: 'println' was not declared in this scope
arduino_output:50: error: 'arduino' was not declared in this scope
arduino_output:50: error: expected type-specifier before 'Arduino'
arduino_output:50: error: expected `;' before 'Arduino'
arduino_output:58: error: expected unqualified-id before numeric constant
arduino_output.pde: In function 'void draw()':
arduino_output:62: error: 'off' was not declared in this scope
arduino_output:62: error: 'background' was not declared in this scope
arduino_output:63: error: 'on' was not declared in this scope
arduino_output:63: error: 'stroke' was not declared in this scope
arduino_output:66: error: 'values' was not declared in this scope
arduino_output:66: error: 'Arduino' was not declared in this scope
arduino_output:66: error: expected unqualified-id before numeric constant
arduino_output:66: error: expected `)' before numeric constant
arduino_output:67: error: 'fill' was not declared in this scope
arduino_output:69: error: 'fill' was not declared in this scope
arduino_output:71: error: 'rect' was not declared in this scope
arduino_output.pde: In function 'void mousePressed()':
arduino_output:77: error: 'mouseX' was not declared in this scope
arduino_output:80: error: 'values' was not declared in this scope
arduino_output:80: error: 'Arduino' was not declared in this scope
arduino_output:80: error: expected unqualified-id before numeric constant
arduino_output:80: error: expected `)' before numeric constant
arduino_output:81: error: 'arduino' was not declared in this scope
arduino_output:81: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected `;' before numeric constant
arduino_output:84: error: 'arduino' was not declared in this scope
arduino_output:84: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected `;' before numeric constant

```

# Answer
> Note: I am testing this on OS X, so my paths may differ slightly from yours.

I have managed to reproduce your issue, by *incorrectly* copying the `arduino` directory, from the unzipped processing2-arduino.zip package, to the `libraries` directory under the `Arduino` directory in my home directory, thus

```
/Users/user/Documents/Arduino/libraries/arduino

```

Then opening the Arduino IDE and running the `arduino_output` example, via the menu, `File -> Sketchbook -> Libraries -> Arduino -> arduino_output`. When I hit the compile button, in the Arduino IDE, the compiler throws up the exact same errors that you describe in your question.

However this is not the correct usage of this package. This package is intended to be used in conjunction with the **Processing** application, *not* the **Arduino IDE**. You should download Processing and then follow the instructions again:

> 1. Unzip the library and copy the "arduino" folder into the "libraries" sub-folder of your Processing Sketchbook. (You can find the location of your Sketchbook by opening the Processing Preferences. If you haven't made a "libraries" sub-folder, create one.)

Thus, on OS X, the path should now be

```
/Users/user/Documents/Processing/libraries/arduino

```

However, as usual, the documentation on the Arduino website leaves a lot to be desired. Pay careful attention to the following paragraph if you are running OS X or Linux:

> Note: if you run Linux, you need to change `Arduino.jar` into `arduino.jar`, because Linux is case sensitive and it does not work if you don't change this letter (Arduino.jar is in the folder "library" of this Processing Library).

So,

```
/Users/user/Documents/Arduino/libraries/arduino/library/Arduino.jar

```

becomes

```
/Users/user/Documents/Arduino/libraries/arduino/library/arduino.jar

```

Relaunch the Processing application. `File -> Examples...`, opens up a window, scroll down to `Contributed Libraries`, open that, open `Arduino (Firmata)`, open the `arduino_output` example. Hit the **Run** button, and after compiling you should see the window below:

HTH.
> 2 votes

---
Tags: serial, processing-lang
---


# Question
Title: Problems uploading sketch to Arduino Due
Windows 7 here. I just bought an Arduino Due and downloaded the Arduino IDE. I wrote a simple "blink LED" program (see below) and am trying to flash it to the Due.

When I connected the Due to my laptop (via micro USB cable), I got a warning on my laptop that it could not find the correct device driver. So I followed the instructions discussed on this excellent video tutorial and went into `Control Panel >> System >> Device Manager >> Arduino` and pointed it to load the appropriate device driver from `C:\Program Files (x86)\Arduino\drivers`. This got rid of the warning. Hooray!

I then Verified & Compiled my program:

```
int led = 13;

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

void loop() {
    digitalWrite(led, HIGH);
    delay(5000);
    digitalWrite(led, LOW);
    delay(5000);
}

```

Great success! Now it was time for me to upload the program to my Due. The first time I tried to upload it, I got the following error:

```
Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno"
Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

```

So then in the IDE I went to `Tools >> Port` and changed the selection from `Serial` to `COM3` (again, sort of explained in that video tutorial). I tried to upload again:

```
Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno"
Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x09
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x09

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

```

I thought it was interesting that the IDE thinks this is an Arduino Uno. So then I went to `Tools >> Board` and changed the selection from `Uno` to `Duemilanove`, hoping that Due and Duemilanove are compatible for the programmer/flasher tool. This time the error was the same as last, except the first line reads:

```
Arduino: 1.6.4 (Windows 7), Board: "Arduino Duemilanove or Diecimila, ATmega328"

```

So at least the IDE is switching board correctly. :-) I should note that my `Tools >> Board` menu **does not** have an "Arduino Due" option. And when I go to `Tools >> Board >> Board Manager`, searching for Due does not turn up anything either.

I also tried running the upload with verbose output, but that really didn't tell me anything more. I'm happy to post the exact verbose output but figured I could omit it here for brevity. I also *did* peruse the troubleshooting link that the error output recommends, but it looks like I've already exhausted all of those recommendations as well.

I'm stuck and frustrated, any suggestions?

What do I need to do to get the IDE programming my Due?

# Answer
> ... hoping that Due and Duemilanove are compatible for the programmer/flasher tool.

Not even close. You will need to go into the Boards Manager and download and install the SAM support files, select the Due from the list, and *then* upload the sketch.
> 1 votes

# Answer
Yes, I just had this problem myself.. Unless you use the Boards Manager Menu and install the Arduino SAM Boards (32Bits ARM cortex M3) board info you will not be able to upload your sketch. After installing in the Boards Manager you will see the Arduio Due programming port and Arduino Native port as an extra options at the bottom or the TOOLS\>BOARD menu. That should fix the problem.(Check which you are connected to and which COM port) If you still have trouble, disconnect and reconnect the DUE and restart the IDE and if required restart you computer.

This seems to be a common problem when people switch from the Uno or MEGA to the Due. I'm surprised this is not installed as standard in the IDE. I am using 1.6.5r2.

Thanks also to Ignacio Vazquez-Abrams.
> 0 votes

---
Tags: arduino-ide, arduino-due, uploading, avrdude
---


# Question
Title: Strange comportment of stepper motor while connected to internet
Problem moving a stepper motor after reading a value from a webpage....

I have a project to move a stepper motor from an angle after reading a number from internet; I have a typical 28BYJ-48 stepper with the hardware driver and an arduino + ethernet shield.

I have tested the motor alone with different library and it is working very well, the motor turn correctly to the proper angle and without shaking.

I have also been able to read a specific page with a number on it with the Ethernet shield and library. I am able to light a led whenever a certain value is read from this webpage.

Once I connect the 2 parts, either the stepper motot is vibrating a lot and moving from half the correct angle, either it is only shaking and not moving at all....

Note: I have powered it with an external power source thinking it was because of power issues but it doesn't change anything.....

I don't get it... Why would it work well before the etheret connection an not after?? Maybe it's late and I miss something obvious, but frankly I spent a lot of time looking online and checking my code

Here is my sketch if it anyone could help... thanks a lot in advance, I know it's quite long....but i'm quite desperate :-(

```
#include <AccelStepper.h>
#include <Ethernet.h>
#include <SPI.h>

////////////////////////////////////////////////////////////////////////
//CONFIGURE
////////////////////////////////////////////////////////////////////////

#define HALFSTEP 8

// Motor pin definitions
#define motorPin1  8     // IN1 on the ULN2003 driver 1
#define motorPin2  9     // IN2 on the ULN2003 driver 1
#define motorPin3  10     // IN3 on the ULN2003 driver 1
#define motorPin4  11    // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
const int stepsPerRev =  2038;

byte server[] = { 192,168,0,11 }; //ip Address of the server you will connect to
String serverIP = "192.168.0.11";

int port = 8888; // server port

// if need to change the MAC address (Very Rare)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// byte ip[] = { 192, 168, 0, 188 }; // case we want to use fixed IP

//The location to go to on the server
//make sure to keep HTTP/1.0 at the end, this is telling it what type of file it is
String webPage = "/index.php HTTP/1.0";

EthernetClient client;

char inString[32]; // string for incoming serial data
int stringPos = 0; // string index counter
boolean startRead = false; // is reading?
int ledPin = 5;
String pageValue;

//////////////////////////////////////////////////////////////////////////////
// SETUP
//////////////////////////////////////////////////////////////////////////////

// setup the stepper parameters

void setup() {
  stepper1.setMaxSpeed(3000.0);
  stepper1.setAcceleration(1000.0);
  stepper1.setSpeed(500);

// start a full rotation ==> this is perfectly working!!

int steps = degreesToSteps(360);
  stepper1.moveTo(steps);
  stepper1.runToPosition();

   Serial.begin(9600);

   Serial.println("starting communication");

  //Connect the Ethernet Shield by specifying the board's mac and ip address

  if(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
   }else{
    Serial.println("Ethernet shield connected & obtained IP address : ");
    Serial.println(Ethernet.localIP());

   //Shield already connected during setup phase, now connect to the webpage and retrieve the value

    //Connect to the server
    if(!connectToServer(server, port, webPage)){
        Serial.println("Failed to connect to server");

        }else{

               Serial.println("connected to server page");

               //Read the output value written on the webpage

              int angle = readPage().toInt();
              Serial.println(angle);

              int steps = degreesToSteps(angle);
              Serial.println(steps);

              stepper1.moveTo(steps);

              stepper1.runToPosition();

              delay(1000);

      //end of success case connection
      }

   }

 //end of setup
 }

void loop(){}

///////////////////////////////////////////////////////////////////////////////////////////
//Connect to a web page
////////////////////////////////////////////////////////////////////////////////////////////

boolean connectToServer(byte* server, int port, String webPage)
{
  //connect to the server
  Serial.println("connecting...");

  //port 8888 for our mamp server
  if (client.connect(server, port)) {
    Serial.println("connected");
    client.print("GET ");
    client.println(webPage);
    client.println();
    return true;
  }else{
    Serial.println("connection failed");
    return false;
  }

}

///////////////////////////////////////////////////////////////////////////////////////////
//Parse a value located between a < and a >
////////////////////////////////////////////////////////////////////////////////////////////

String readPage(){
  //read the page, and capture & return everything between '<' and '>'

  stringPos = 0;
  memset( &inString, 0, 32 ); //clear inString memory

  while(true){

    if (client.available()) {
      char c = client.read();

      if (c == '<' ) { //'<' is our begining character
        startRead = true; //Ready to start reading the part
      }else if(startRead){

        if(c != '>'){ //'>' is our ending character
          inString[stringPos] = c;
          stringPos ++;
        }else{
          //got what we need here! We can disconnect now

          startRead = false;
          client.stop();
          client.flush();
          Serial.println("disconnecting.");
          return inString;

        }

      }
    }

  }

}

///////////////////////////////////////////////////////////////////////////////////////////
//Convert the degrees into the closest number of steps relative to the step motor model.
////////////////////////////////////////////////////////////////////////////////////////////

int degreesToSteps(float angleDegrees) {
  //return the closest number of steps to accomplish to move the motor for the specified angle

  const float stepsPerDegree = stepsPerRev/360.00;
  int steps = angleDegrees * stepsPerDegree + 0.5;  // we add 0.5 as when converting to an int the floating part is truncated, this allows to round the value to the nearest Int
  return steps;

}

```

# Answer
Pin 11 is used for SPI to communicate with the Ethernet Shield. And pin 10 is used for the ChipSelect. So using the ethernet shield will toggle those pins, making the motor shake around.

Try using pins 6, 7, 8, and 9 instead.
> 0 votes

---
Tags: arduino-uno
---


title: Arduino IDE on Fedora

text:
# Question
Title: Arduino IDE on Fedora
I'm using Fedora\_21\_MATE.img on a Raspberry Pi. Installing the Arduino IDE 1.0.6 using these commands, taken from Arduino On Pi. Those instructions are for Raspbian, I assume, so changing for Fedora, `apt-get` to `yum`:

```
sudo yum install arduino

```

One waits and `arduino` installs. One can then run the Arduino IDE from the Fedora GUI menu, and it loads - after moaning about the user has to be a member of the `dialout` and `lock` groups. This is easily resolved by adding the user to the required groups, using the control panel.

However, trying to compile anything, i.e. `blink`, in the IDE, gives me the following error:

```
avr-g++: error trying to exec cc1plus: execvp: No such file or directory

```

In verbose mode, little additional information is offered.

```
Arduino: 1.0.6 (Linux), Board: "Arduino Uno"
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build6314348775898760987.tmp/Blink.cpp -o /tmp/build6314348775898760987.tmp/Blink.cpp.o
avr-g++: error trying to exec 'cc1plus': execvp: No such file or directory

```

The file in question, `cc1plus`, is actually present in the filesystem:

```
[piebody@berrybody ~]$ locate cc1plus
/usr/libexec/gcc/armv7hl-redhat-linux-gnueabi/4.9.2/cc1plus
/usr/libexec/gcc/avr/4.9.2/cc1plus
[piebody@berrybody ~]$

```

Does anyone know why it doesn't run "out of the box"? Do I need to modify any environment variables, and if so, which ones and with what exactly? I assume my `PATH` environment variable needs fixing, but is there any environment variable specific to `avr-g++` that needs changing?

I appreciate that this is probably a simple UNIX paths issue, and that the question may be more suited to SE: Unix & Linux.

# Answer
There seem to be two issues:

* Getting the IDE to fully function when launched from the command line, and;
* Getting the IDE to fully function (i.e. compile) when launched from the Fedora GUI menu.

I have found a solution if I run the Arduino IDE from the command line, by adding the path to one of the `cc1plus` binaries to the `PATH` environment variable:

```
[piebody@berrybody ~]$ PATH=${PATH}:/usr/libexec/gcc/avr/4.9.2
[piebody@berrybody ~]$ export PATH
[piebody@berrybody ~]$ arduino&

```

However, if I launch the Arduino IDE from the Fedora application menu, and then try to compile a sketch, it still can't locate `cc1plus`. Maybe the `PATH` needs to be added in my `.profile`, or some other mechanism, to get an application launched from the Fedora menu to see the path?1

Yet, even with the command line launch, it still does not finish compiling. I now get the following error when the IDE attempts to compile:

```
In file included from Blink.ino:18:0:
/usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:23:20: fatal error: stdlib.h: No such file or directory
 #include <stdlib.h>
                    ^
compilation terminated.

```

In verbose mode

```
Arduino: 1.0.6 (Linux), Board: "Arduino Uno"
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build1210300884764677972.tmp/Blink.cpp -o /tmp/build1210300884764677972.tmp/Blink.cpp.o
In file included from Blink.ino:18:0:
/usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:23:20: fatal error: stdlib.h: No such file or directory
 #include <stdlib.h>
                    ^
compilation terminated.

```

I assume that this is another `PATH` issue. One that relates to the path to the Arduino libraries, or `libc` libraries.

After reading can't locate avr libraries2, I can't see why `avr-g++` is not picking up the `avr` directory in the `/usr` directory.

The actual path to `stdlib.h` is `/usr/avr/include/stdlib.h`

The output of `avr-gcc` (and `avr-g++`) shows `--prefix=/usr`

The Arduino IDE preference file (`~/.arduino/preference.txt`) shows the line

```
last.ide.1.0.6.hardwarepath=/usr/share/arduino/hardware

```

**Linking the includes**

If I manually link some header files to where the compiler actually is looking, then it works (until `avr-gcc` needs a header that I have not linked to):

```
cd /usr/share/arduino/hardware/arduino/cores/arduino
sudo ln -s /usr/avr/include/stdlib.h stdlib.h
sudo ln -s /usr/avr/include/string.h string.h
sudo ln -s /usr/avr/include/math.h math.h

```

but I can not do this for *every* header file, it is ridiculous. There must be a way of linking to `/usr/avr` from `/usr/share/arduino/hardware/arduino/cores/arduino`. I have tried linking the parent directories `/usr/avr` and `/usr/avr/include`, at various points along the directory hierarchy of `/usr/share/arduino/hardware/arduino/cores/arduino`, but none of those seem to work.

**Copying the include directory**

After reading default include file path?, and running `avr-cpp -v` I saw that the default `#include` search path was

```
#include <...> search starts here:
 /bin/../lib/gcc/avr/4.9.2/include
 /bin/../lib/gcc/avr/4.9.2/include-fixed
End of search list.

```

From this, I could see that `avr-cpp` was searching in `/lib/gcc/avr/4.9.2/include`. I examined, and compared, the contents of `/lib/gcc/avr/4.9.2/include` with `/usr/avr/include` and they held similar (the same) files, except `/lib/gcc/avr/4.9.2/include` was a subset, that is to say that it was missing the required files.

I ended up copying the `/usr/avr/include` directory, which contains the required header files (`stdlid.h` etc., to which I had linked previously), and replacing the original `include` directory, in the directory where `avr-gcc` seemed to be looking, which was in its own directory location `/lib/gcc/avr/4.9.2/`.

```
cd /lib/gcc/avr/4.9.2/
mv include include.old
cp -r /usr/avr/include .

```

Then the Arduino compiler seemed to work, until it then gave an assembler error:

```
Assembler messages
Error: unrecognized option -mmcu=avr5

```

This is an issue with `avr-as`.

I will update as I resolve these issues.

---

1 I eventually resolved this by creating a script in `/usr/bin` (where the `arduino` binary was located) called `arduino.launch` which contains the `PATH` settings and a call to `arduino`:

```
#!/bin/sh
PATH=${PATH}:/usr/libexec/gcc/avr/4.9.2
export PATH
arduino

```

setting it to be executable with `chmod +x arduino.launch`. Then I edited the properties of the Fedora Arduino launch icon, by right-clicking on the icon and selecting **Properties**, and changed the **Command** entry from `arduino` to `arduino.launch`.

However, there must be a better way of doing this, as this seems to be a bit of a hack.

2 Other posts ,  and ) that I have read, apart from providing useful paths to investigate, merely suggest reinstalling. However, as bone headed as I may seem, there must be a way of linking up what is already on the file system (everything is there - just in the "wrong" place), such that compiles work as they should.
> 1 votes

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


# Question
Title: Updating MAX7456 library to work with Arduino 1.6.6
I've got this library for communicating with the MAX7456 chip.

The library is abandoned and the only one I found that actually works, so I'd really like to use it.

---

It compiles fine with Arduino IDE 1.0.5, but not with Arduino IDE 1.6.6 .

This happens with 1.6.6, I tried to fix it but I only made it worse.

```
Arduino: 1.6.6 Hourly Build 2015/07/03 10:26 (Linux), Board: "Arduino Nano, ATmega328"

Using library SPI at version 1.0.0 in folder: /home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI
Using library max7456 in folder: /home/t/Dropbox/Arduino/libraries/max7456 (legacy)

/home/t/Dropbox/Arduino-IDE/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/cores/arduino -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/variants/eightanaloginputs -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI -I/home/t/Dropbox/Arduino/libraries/max7456 /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp -o /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp.o
In file included from HelloWorld.ino:2:0:
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:40: error: 'prog_uchar' does not name a type
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                    ^
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:52: error: ISO C++ forbids declaration of 'table' with no type [-fpermissive]
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                                ^
Error compiling.

```

---

How would one make the library compatible with 1.6.6?

# Answer
In the file max7456.h at line 228 change it from:

```
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);

```

to:

```
static void getCARACFromProgMem(const char *table, byte i,charact c);

```

---

In the file max7456.cpp at line 484 change it from:

```
void Max7456::getCARACFromProgMem(const prog_uchar *table, byte i, charact car)

```

to:

```
void Max7456::getCARACFromProgMem(const char *table, byte i, charact car)

```

---

Then it compiles OK (under 1.6.4 at least).
> 5 votes

---
Tags: library
---


# Question
Title: Can I use a 6 pin Bluetooth module in a 4 pin socket?
I have a Funduino joystick shield and it features a 4 pin bluetooth socket in the top right hand corner (just above the `D`, `T`, `-` and `+` legends).

For some reason, on eBay, 6 pin bluetooth modules are cheaper and more common than 4 pin bluetooth modules.

The joystick shield's 4 pin socket is labelled `R T - +`. Obviously these correspond with `RXD`, `TXD`, `GND` and `VCC` on the bluetooth module.

I was wondering:

1. What is the difference between the 4 pin and 6 pin modules?
2. Can I use a 6 pin module in the four pin socket on the joystick shield?
3. What is the function of additional `STATE` and `EN` pins on the bluetooth module?
4. Are these two additional pins necessary as other modules do not have them?

# Answer
> 2 votes
> 1. What is the difference between the 4 pin and 6 pin modules?

The 6-pin modules have more pins, used for other features.

> 2. Can I use a 6 pin module in the four pin socket on the joystick shield?

I don't see why not, as long as you tie/float the other pins appropriately.

> 3. What is the function of additional STATE and EN pins on the bluetooth module?

Whatever the documentation says they do.

> 4. Are these two additional pins necessary as other modules do not have them?

Probably not. But they provide additional functionality.

# Answer
> 4 votes
After some more concerted searching I have found the answer on Success Using the JY-MCU (linvor) Bluetooth Module:

> The module has 6 pins labeled on the back, but most modules only have 4 of those populated with pogo pins. KEY & STATE seem to be not required, as KEY is used for flashing the device and STATE simply indicates if the device is awake or not. So that leaves only GND, VCC, TXD, RXD. Not shown is Pin 11 which is the RESET pin, resetting the module when pulled LOW.

So, the answer is apparently yes, and you can buy a cheaper 6 pin module and remove (snip/desolder) the two additional pins. The `EN` pin is also apparently labelled as `KEY` on some modules.

---
Tags: bluetooth
---


# Question
Title: What are the connectors used in the arduino mega?
I am trying to build a shield for an arduino mega.For that i need to know the type of the female connectors that are soldered in the pins of the arduino mega in order to choose the correct male connectors.

# Answer
> 0 votes
Look for male pin header strip, with 0.1 inch (2.54mm) pitch.

In single and dual row form.

Specifically they are:

* 8x1 ADCL
* 8x1 ADCH
* 8x1 PWML
* 8x1 PWMH
* 8x1 Communication
* 6x1 Power
* 18x2 digital IO (on the side)

Source: Schematics

---
Tags: arduino-mega
---


# Question
Title: Use the TCS3200 color sensor without the included LEDs
just a quick question. I want to know if it is possible to use the TCS3200 color sensor without the 4 LEDs included on the breakout board. I want to get the sky colors. Is that possible?

# Answer
The photodiodes in the device itself have filters so it should *theoretically* be possible to use it without auxiliary light sources. Note, however, that the green and blue sensors have *two* sensitivity peaks and so using it outdoors without an infrared filter is not advised.
> 2 votes

---
Tags: sensors
---


# Question
Title: Can I use an ATmega328 alone without anything and what is the max voltage I can power the atmega328 with
Okay 2 questions. If I am to replace the Arduino with an ATmega328 programmed with a standard blink on pin 13, is this configuration correct, do I still need oscillators and whatnot?

Second question is, what is the max voltage I can power the ATmega328 with without frying it? I have seen conflicting answers of this on the net. Some have said 5V while some say 6V can someone clarify?

# Answer
> 3 votes
The datasheet describes the electrical and clock requirements of the chip, and AVR042 describes the external hardware configuration required. Decoupling, analog voltages, external crystal or oscillator if required.

# Answer
> 2 votes
If you take a look at the Standalone Arduino on the Arduino website, then this is what you require:

Note that there is one slight error in the guide, which I have highlighted here, Arduino Standalone - photo shows incorrect pin wired to MOSI.

There is a video on how to achieve, more or less, the same thing, 1-Day Project: Build Your Own Arduino Uno for $5.

# Answer
> 2 votes
I have a page describing How to make an Arduino-compatible minimal board. The minimal setup would be:

That excludes the circuitry for uploading your code.

By the way, in the image in the question you have an LED with no resistor. That will damage both the LED and the Atmega328. You need a **current-limiting resistor**.

---

> do I still need oscillators

Not if you program the fuse to use the internal oscillator.

> Some have said 5v while some say 6v can someone clarify?

The datasheet says 1.8 to 5.5 V operating range with an **absolute maximum rating** of 6 V.

This is what the datasheet says about absolute maximum ratings:

> This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.

Page 2 of the datasheet says:

> * Operating Voltage:
> * 1.8 - 5.5V

---
Tags: atmega328, hardware
---


# Question
Title: Can I use analogReadResolution() on an Uno or Leonardo?
I am trying to get a spectrum analyser up and running. I found the following code on Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer1:

```
/*
 *
 * Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer
 * https://communities.intel.com/docs/DOC-23406
 *
 *
 * ERROR: analogReadResolution() ???
 *
 */

#include <stdint.h>  //For New Arduino
#include "PCD8544.h"
#define pin_adc 0
#include "fix_fft.h"
char im[128];
char data[128];
int analog_value[128];
int i=0;
PCD8544 nokia = PCD8544(3, 4, 5, 7, 6);
// pin 7 - Serial clock out (SCLK) connects Dig3
// pin 6 - Serial data out (DIN) connects Dig4
// pin 5 - Data/Cmd. selct. (D/C) connects Dig5
// pin 4 - LCD reset (RST) connects Dig6
// pin 3 - LCD chip select (CS) connects Dig7
void setup() {
  nokia.init();
  nokia.command(PCD8544_DISPLAYCONTROL | PCD8544_DISPLAYNORMAL);
  nokia.clear();
  analogReadResolution(8);
}

void show_big_bars(char *spektrum) {
    int spek_for_draw;
    nokia.drawline(10, 15, 10, 39, BLACK);
    for (byte i = 1; i < 64; i++){ // Skip 0 Channel
      // Serial.print(spektrum[i],BYTE);
      spek_for_draw = 1.5*(spektrum[i]); // 0/2.5 ~ 255/2.5
      if (spek_for_draw > 39) spek_for_draw = 39;
      nokia.drawline(i+10, 39 - spek_for_draw, i+10, 39, BLACK);
    }
    //nokia.drawstring(5, 5, "0 09 22 36 49");
    nokia.drawstring(5, 5, "0");
    nokia.drawstring(21, 5, "4");
    nokia.drawstring(37, 5, "8");
    nokia.drawstring(48, 5, "12");
    nokia.drawstring(67, 5, "18");
    nokia.drawstring(5, 0, "Spectrum");
    nokia.drawstring(5, 1,"* 0.1KHz");
    nokia.display(); // Update Screen
    nokia.clear(); // Clear Screen for the animation
}
void loop(){
  static long tt;
  int val;
  if (i < 128){
      analog_value[i] = analogRead(pin_adc);
      i++;
   }
   else{
        for (i=0; i< 128;i++){ //Prepare data for FFT
            data[i] = analog_value[i] - 128;
            im[i] = 0;
        }
   //this could be done with the fix_fftr function without the im array.
        fix_fft(data,im,7,0);
   // I am only interessted in the absolute value of the transformation
        for (i=0; i< 64;i++)
             data[i] = sqrt(data[i] * data[i] + im[i] * im[i]);
   //do something with the data values 1..64 and ignore im
        show_big_bars(data);
        i=0;
   }
}

```

When I attempt to compile the above code, I get the error

```
Arduino: 1.6.5 (Mac OS X), Board: "Arduino Micro"

fft_galileo.ino: In function 'void setup()':
fft_galileo:31: error: 'analogReadResolution' was not declared in this scope
'analogReadResolution' was not declared in this scope

```

When I search for the location of `analogReadResolution()` on Google, I repeatedly get the information that it is only available for the Due and Zero. From Arduino - AnalogReadResolution:

> analogReadResolution() is an extension of the Analog API for the Arduino Due and Zero.

I was wondering if I needed to add an `#include` statement but all of the code examples that I found do not have any specific `#include` for the Analogue library.

Also, thinking maybe it is board specific (as the video Arduino Due error: 'analogReadResolution' was not declared in this scope suggests), I selected the ***Duemilanove*** board (as the ***Due*** is not on offer in my "Board" menu), but I still get the same error. I have even tried the ***Arduino NG or older*** Board menu item, but with the same results.

So, how do I get rid of this compile time error? Or, more poignantly, how can I compile this code for my Uno or Leonardo board. Should I just comment it out? If I do comment the line out then the code *does* compile, so does this mean that `analogReadResolution()` is not required any longer?

If it isn't required, then why does this Uno specific example, How to Use ADC in Arduino Uno?, state:

> As default we get the maximum board ADC resolution which is 10bits, this resolution can be changed by using instruction (“analogReadResolution(bits);”). This resolution change can come in handy for some cases.

How can the resolution be changed if the method has, indeed, been deprecated?

Also, why do I not have a "Due" in my **Board** menu?

---

1 For completeness `fix_fft.h` and `fix_fft.cpp` can be found on TJC's github and here is the PCD8544 Arduino library for Nokia 5510 LCD library. The password for decompressing `Intel_Nokia5110.rar` file is 406.

# Answer
There is no point to having `analogReadResolution()` on AVR devices since that function *only exists* to provide/ensure backwards compatibility with the fixed 10-bit ADC that is found in AVR devices. If you want higher or lower resolution then you will need to perform the appropriate actions manually.

You don't have a Due entry because you haven't installed Atmel SAM support in the Board Manager.
> 3 votes

# Answer
> Also, why do I not have a "Due" in my Board menu?

See:

Then:

---

> I selected the Duemilanove board (as the Due is not on offer in my "Board" menu) ...

The Duemilanove and the Due are completely different boards, with different processors.
> 2 votes

---
Tags: arduino-uno, arduino-leonardo, analogread, adc, analogreadresolution
---


# Question
Title: What are the distances between Arduino Mega connectors?
I am trying to build an Arduino Mega shield. For that, I need to know the exact distances between the different connectors.

# Answer
> 3 votes
The pin layout and dimensions of the Mega are as follows:

Dimensions are in thousandths of an inch. Source

---
Tags: arduino-mega
---


title: Why is my variable not getting updated?

text:
# Question
Title: Why is my variable not getting updated?
I have the following snippet of code:

```
const unsigned long fiveMinutes = 5 * 60 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

```

The `doStuff()` routine is getting called on every `loop()` iteration, because the value of `lastCheck` isn't getting updated. I thought Icould update global variables inside subroutines, but the behavior I'm seeing says otherwise. What am I doing wrong? (`doStuff()` is defined and works correctly, I'm not posting it here for brevity.)

# Answer
> 1 votes
I modified your code to produce a working example:

```
const unsigned long fiveMinutes = 20 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  Serial.println (fiveMinutes);
  }  // end of setup

void doStuff ()
  {
  Serial.println ("Doing stuff");
  }

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

```

I reduced the interval to 20 seconds, and Ignacio Vazquez-Abrams is correct about the initial test, however apart from that, I see "Doing stuff" every 20 seconds.

---

> I thought I could update global variables inside subroutines ...

You can.

---

Are you sure you didn't have:

```
void loop() {
  unsigned long lastCheck;
...

```

---
Tags: c, sketch, variables
---


title: Why does this code execute?

text:
# Question
Title: Why does this code execute?
After experiencing failures of my Arduino projects due to low memory, I decided to do some research into it so I could understand better where the problems were. I eventually came to this code:

```
void setup() {
  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));
}

void loop() {
  int timing = 1000;
  delay(timing);
  digitalWrite(13, HIGH);
  delay(timing);
  digitalWrite(13, LOW);
}

```

I expected that since my Arduino Uno does not have enough RAM to hold an array of 5000 bytes (Atmel's information on the Atmega328P shows us it only has 2KB of SRAM), the code in `void loop()` would not be able to run due to lack of memory. As far as my understanding goes, once `malloc` has allocated 5000 bytes (or as many as it could of the 5000 bytes), there would physically not be enough space left in memory for the variable `timing` and the LED I attached on pin 13 would not flash on and off at intervals of 1 second.

However, my LED toggles at perfect intervals of 1 second. Why would this occur? Isn't memory allocated by `malloc` unavailable for use by anything else until `free` is called on it?

# Answer
If you add a debugging print you will see what is happening:

```
void setup() {
  Serial.begin (115200);
  Serial.println ();

  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));

  Serial.print ("data = ");
  Serial.println ((int) data);
}

```

Output:

```
data = 0

```

The malloc failed, it returned NULL, the rest of the program proceeded normally.

---

> once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes)

`malloc` does not return with a partial allocation. It either allocates the amount you requested or none at all.
> 7 votes

---
Tags: c++, compile, memory-usage
---


# Question
Title: Why do only specific arduinos support the keyboard and mouse libraries?
The Arduino website suggests that only three boards are supported for the Mouse and Keyboard library page:

* Leonardo
* Micro
* Due

What is special about those boards, that the other boards in the Arduino family don't have? I thought they might have the same proceesing chip on them but only two of them do. The CPUs are correspondingly:

* ATmega32u4
* ATmega32u4
* Atmel SAM3X8E ARM Cortex-M3

I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

So my question is: **what do those three boards have that lets them support those libraries?**

# Answer
Those chips have hardware support built into them to handle the rather strict timing requirements for interpreting (and responding to) USB sequences. You will notice, for example, that on the Arduino Uno there is a *second* chip (the Atmega16U2) which also can handle USB. In fact the chips with a "U" in the name generally can do this.

> I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

You have a couple of options. Some people reflash the USB chip on their Uno (for example), although personally I think that is a bit fiddly.

Alternatively, there is a library called VUSB (virtual USB) which lets you do some USB on the non USB chips. Google `vusb arduino`.

You need three resistors and two zener diodes to make up the hardware that lets this library do its stuff.
> 1 votes

# Answer
Another option is to use the PS2Keyboard library, a PS2 connector and a PS2-to-USB converter.

You will need only two digital pin of your Arduino and have keyboard solution.
> 1 votes

---
Tags: arduino-due, arduino-leonardo, arduino-micro, arduino-duemilanove
---


# Question
Title: Arduino won't send serial data if connected with external power supply
I am trying to make a connection between 2 Arduino's with the APC220 rf modules.

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

void loop() {
   int value = 5;
   Serial.println(value);
   delay(1000);
}

```

I uploaded this code to my Arduino Nano and Uno. I disconnected the rf modules for uploading the code.

I tried to run this program with an external power source (lipo 11.1V 2200mAh). The Arduino is powered on(power led is on) BUT the tx led doesn't blink.

The only way to make it work is by using the usb and opening the serial monitor on my pc.

I tried to use a 10k resistor between tx and rx (or rx to ground) but the code won't run...

Can someone help me?

Solution : the arduino worked perfect. When you connect the arduino with an exernal power supply the tx and rx lights won't light up, Even when they are transmitting or receiving.

# Answer
> 1 votes
Solution : The Arduino worked perfectly. When you connect the Arduino with an external power supply the Tx and Rx lights won't light up, Even when they are transmitting or receiving.

---

I'm adding this as the solution to stop this being re-added as an unsolved problem.

---

That is correct. The Tx and Rx LEDs are connected to the Atmega16U2 processor, and thus only flash if there is serial comms via USB.

# Answer
> 0 votes
I think tx not activated without available serial connection. What is you rf module and what is the baud rate of RF module. Also can you share connection diagram or a test video. Alternativeliy you can look SoftwareSerial: http://www.arduino.cc/en/Reference/SoftwareSerial

---
Tags: serial, usb
---


# Question
Title: Can I use GPS sensors in a country (India) that doesn't have its own GPS Sattelites?
I am living in India. I want to work on Arduino Projects with GPS Modules. But only a few countries like US, Russia, China etc. have their own GPS satellites. India is working on it. So I am hesitating to buy GPS sensors. Can I work normally with GPS modules in my country as shown in Online projects in my country ?

# Answer
Each of the countries listed has their own *satnav system*. GPS satellites cover the *entire world* and the US government allows *anyone* with a GPS receiver to use it, regardless of where on or above the surface they are located.
> 1 votes

---
Tags: gps
---


title: Building a digital camera?

text:
# Question
Title: Building a digital camera?
Does anyone know of a way to DIY a digital camera by buying a sensor and lens and processing the image using an Arduino?

# Answer
You can buy a camera module for the Arduino, and you can interface it fairly simply. There are numerous modules around - ask Google, it knows more than me.

But I have yet to work out why people do it. All you can do with an Uno is to pass the data through to something else like a PC to process the image - so why wouldn't you just use a simple webcam?

The Arduino UNO has 2KB of RAM. A 24-bit 640x480 image (VGA) requires (640\*480\*3)/1024 = 900KB to store it in memory. If you really wanted to process an image on an Uno then you would be limited to (say 8-bit grayscale) 48x32 pixels (1.5KB) which is pretty pointless really.

Even a Due would only allow (again grayscale) around 320x240 (which is better) but nothing colour unless you want to start messing with CLUTs which aren't fun when receiving a truecolour (24-bit) image from a camera.

For this kind of task you are better off with an embedded computer with plenty of RAM such as a Raspberry Pi or maybe a Galileo or something.
> 3 votes

---
Tags: arduino-uno
---


title: lcd.print then dataFile.print

text:
# Question
Title: lcd.print then dataFile.print
My program is a bit large and I'm worried about stability.

I need to print data to both a file and to my LCD. It's like this:

```
if (hour<10) {
    dataFile.print("0");
}
dataFile.print(hour, DEC);
dataFile.print(":");
if (minute<10) {
    dataFile.print("0");
}
dataFile.print(minute, DEC);
dataFile.print(":");
if (second<10) {
    dataFile.print("0");
}

```

Then

```
if (hour<10) {
    lcd.print("0");
}
lcd.print(hour, DEC);
lcd.print(":");
if (minute<10) {
    lcd.print("0");
}
lcd.print(minute, DEC);
lcd.print(":");
if (second<10) {
    lcd.print("0");
}

```

What is a smart way to make this shorter? Should I write a function to add the leading zero then another that does something like:

```
void printboth (thing) {
    dataFile.print(thing);
    lcd.print(thing);
}

```

good idea?

# Answer
> 1 votes
You could format the data with snprintf:

```
char timestamp[9];
snprintf(timestamp, 9, "%02d:%02d:%02d", hour, minute, second);
dataFile.print(timestamp);
lcd.print(timestamp);

```

`%02d` in the snprintf *format* means "print at least 2 digits of this value and pad with leading zeros".

---
Tags: programming
---


# Question
Title: Sending "Blink" to pin 12 is causing on-board led to blink?
I recently picked up an Uno clone and noticed that if pin 12 is set to an output and I run the Blink sketch on it, the built in led (supposedly connected to pin 13) blinks. It's not as bright as it is when I run it on pin 13, but nonetheless it blinks. If I run it on any other pin, nothing happens, which is the behavior I expected with pin 12.

Is this a common issue with arduino boards, the microcontrollers, etc. or did I get a bad board?

Overall the board visibly appears to have solid construction and appears as the one on the site that I linked to.

Lastly as a side note, I'm currently living in India and won't have a problem going back to their factory for a replacement, if it is a bad board. They include a 6 month warranty.

```
int ledPin = 12;
int delayPeriod = 100;

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

void loop()
{
  digitalWrite(ledPin, HIGH);
  delay(delayPeriod);
  digitalWrite(ledPin,LOW);
  delay(delayPeriod);
  delayPeriod = delayPeriod + 100;
}

```

# Answer
See Have I bricked my Arduino Uno? Problems with uploading to board

As I state on that page, if pin 13 is set to input the LED may turn on due to being driven by an op-amp. A nearby pin turning on may be enough to cause that effect. Try adding:

```
 pinMode(13, OUTPUT);
 digitalWrite (13, LOW);

```

See if that changes the behaviour.
> 1 votes

---
Tags: arduino-uno, led, pins, clones
---


# Question
Title: What will use less memory, an array or if ... else?
I'm trying to make my sketch smaller. Right now I use an array for the AM/PM part of my time display. My thinking is this makes it easy to change the formatting:

```
char* ampms[]= {"am", "pm"};

void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; ampm=1; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      dataFile.print(ampms[ampm]);
}

```

I could do this instead:

```
void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      if (hour>12) { lcd.print("am");} else {lcd.print("pm"); }
}

```

No more am/pm array. But, I have to add an if... is one better than the other for memory? Why?

# Answer
As Ignacio says, if the compiled size is the same both ways, look for something else. (But note that having the constants in flash memory (program memory) may still use about the same amount of RAM, and typically will take more program space.)

When I compile the code you showed (together with minor additions like declaration of variables) I show the array method using 4 bytes less code and 5 bytes more RAM than the `if` method, so there are tradeoffs.

You can replace the clunky `if` statement and its two `lcd.print`s with the following:

```
      lcd.print(hour>12? "am" : "pm");

```

Note that that line retains the two bugs that your `if` statement has, but it produces them more compactly. :) \[One error is that your `if` statement prints `pm` for hours 0 through 12 and `am` for hours 13 through 23. Another error is that it prints zeroes instead of twelves for the hours after midnight and noon. More properly, a program should print like 12:xx am during hour 0 of the day, and like 12:xx pm, 1:xx pm, ... 11:xx pm during hours 12 through 23.\]

Also note that as Gerben mentions, moving the "am" and "pm" strings into program memory via

```
lcd.print(hour>12? F("am") : F("pm"));

```

saves 6 bytes of RAM. However, that improvement in RAM usage is offset by 74 additional bytes of program space! The following saves 6 bytes of RAM while increasing program size by only 12 bytes so may be preferable:

```
lcd.print(hour>12? 'p' : 'a');
lcd.print('m');

```

The following lines of C can replace much of the code you showed. However, the `printf` library uses about 1300 bytes of program space, so the following compact-source-code approach cannot be recommended unless you are already loading some `printf` functions. It replaces the lines from `if (hour>12) { hr = hour - 12; } ...` to the end with

```
enum { bufsize=8 };
char buf[bufsize];
snprintf (buf, bufsize, "%02:02%cm", hour%12, minute, hour>12? 'p' : 'a');
lcd.print(buf);

```
> 1 votes

---
Tags: memory-usage, rtc
---


# Question
Title: Arduino car on bluetooth remote appears to crash when motors started
I built a Arduino robot car which accepts instructions via bluetooth. The instructions are pretty simple, they tell the car to stop, go forward, reverse, turn left or turn right.

When I have the car powered through the computer USB (ie when I have just uploaded the sketch), all works fine. However, when I run off independent battery power, the arduino seems to restart whenever I give the car an instruction which means the motors have to operate.

I know the sketch is restarting inside the Arduino because the blue tooth terminal displays the startup text which is inside the 'setup' function.

What is going wrong here? What issue am I encountering?

The board is an Arduino UNO with an Arduino Motor Shield attached. The blue tooth and two sonic sensors are attached to the motor shield pins.

Also, I have a 9V battery attached to the motor shield. Plus 4 times 1.5V batteries powering the UNO. Am I screwing up the power at all? Getting too much? Or too little?

# Answer
> 0 votes
You seem to be using your heavy-duty batteries for the Arduino and the light-duty 9 V battery for the motor. To me this seems backwards. Also the Vin pin to which you have the 9 V battery connected is by default connected to the Arduino as well. This means that if the motors draw a lot of current it will drag the Arduino's voltage down and it will probably reset (thus cutting power to the motors, and then it reboots).

From the Arduino Motor Shield page:

> Vin on the screw terminal block, is the input voltage to the motor connected to the shield. An external power supply connected to this pin also provide power to the Arduino board on which is mounted. By cutting the "Vin Connect" jumper you make this a dedicated power line for the motor.

You should cut that jumper so that the Arduino and the motor have dedicated supplies.

Also, arrange better batteries for the motor. You may find you can run the Arduino from the 9 V battery, and then make sure you have enough AA batteries to drive the motors.

# Answer
> 0 votes
it sounds like the motors are pulling down the battery voltage enough to reboot the Arduino; and the USB-port is able to supply enough current without as much voltage drop.

We'd need to see a schematic, but check that the power supplied to your Arduino and power supplied to the motors are completely independent; that the Arduino only supplies current to a switch or a relay in the motors' power circuit but not to the motors themselves.

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


# Question
Title: Detect button on a ground line (reverse eng)
I've found a circuit board that has a couple of circuits (buttons, IR Receiver, LED, USB). The thing is that following the line for interfacing the buttons I came across what seems to be like buttons that are connected only to the ground line of the PCB while the other end is a free pin cable.

Is there a way for the arduino to detect the ground when the button is pressed or a way to detect a short of some kind? There is a smd and a resistor on both buttons.

Circuit:

Main Ground-----Button-----SMD Capacitor-----Resistor(101)-----Free Pin

Thanks in advance!

Edit: Circuit Board

# Answer
> 3 votes
Just connect the ground to the ground on the arduino, and the free pin to a IO pin. Enable the pull-up resistor on that pin using `pinMode(<nr>, INPUT_PULLUP);`. If the button is not pressed, you will read a HIGH. If the button is pressed you will read a LOW.

# Answer
> 3 votes
It sounds like you might have a PCB with debounced switches on them. One such circuit for debouncing switches looks like this:

That circuit and more about switch debouncing can be found here.

A debouncer basically masks the problem of switch "bounce" which is what happens when the contacts get close and the circuit is quickly closed and opened in rapid succession until a firm connection is obtained. Its a natural problem mechanical switches.

If that's not quite right, maybe you could help us help you better by posting a photo of the board in question.

# Answer
> 1 votes
I did some research on the subjects and I came with a solution: I borrowed the code from here and made some modifications to fit my needs.

```
const int buttonPin = 6;
const int buttonPin1 = 7;

int previousReading = HIGH;
int previousReading1 = HIGH;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin1, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int reading = digitalRead(buttonPin);
  int reading1 = digitalRead(buttonPin1);

  if (previousReading == HIGH && reading == LOW) {
     Serial.println(HIGH);
  }

  if (previousReading1 == HIGH && reading1 == LOW) {
     Serial.println(LOW);
  }

  previousReading = reading;
  previousReading1 = reading1;

}

```

---
Tags: button
---


title: Arduino Relay Shield

text:
# Question
Title: Arduino Relay Shield
I am wondering if this Arduino Relay Shield design would be good enough to handle 120v 1amp The transistor is a 2n4401. Also The Two capacitors on the other 3 circuits would be going to ground opps its to late for this

# Answer
As already mentioned, everything to the left of the relays is completely irrelevant when it comes to what the system can cope with. It's purely down to the relays what voltage and current they can deal with. As far as the circuit goes there's nothing wrong with it that I can see at first glance.

So to go from there to an actual physical shield there are a number of things you do need to consider:

1. Ensure that the relays have a rating *at least* as high as the expected maximum voltage and current, ideally *derate* it by *at least* 50%. For CFLs (which present an inductive load as well as a resistive load) you want to dereate it even more.
2. Ensure that the mains voltage track layout is kept well away from the low voltage digital signals and ground plane.
3. Ensure that the mains voltage tracks are sized appropriately and kept as short as reasonably possible. Use a track width calculator to get the right width.
4. Be sure to use appropriate connectors for the mains power. They need to be able to cope with as much current and voltage as the relays and at the same time be *safe*.
5. Keep all mains voltages away from human contact. This means no exposed live metal on the upper side of your board where it can be inadvertently touched. Any components with exposed leads that have mains voltage in them should have their leads insulated.
6. Be absolutely certain that, since this is a shield, no mains voltages even come close to the Arduino the shield is plugged into. This is especially critical around such areas as the USB socket where through-hole components (like screw terminal blocks) are likely to short circuit and cause very very nasty things to happen.

**Remember: Mains voltages are dangerous, caution and safety should be your first concern over everything else!**

One more tip: Do all your mains experimentation as safe as possible. Either ensure that you have an ELCB *and* an RCD on your ring main / power outlet (with the former you must ensure that you have your earth wires connected properly), or even better (and what I would certainly recommend above all else), use an Isolation Transformer to separate you from the mains circuit entirely. With an Isolation Transformer electrocution is only possible if you contact *both* terminals at once as opposed to just one terminal of the normal mains supply.

**Edit:** One thing that does puzzle me with your circuit is how you have wired up the common pin of the relays. That part of the circuit makes no sense to me at all. You should have 2 connections to each relay - *in* and *out* where *in* connects to the *NO* and *out* connects to the *common* pin¹. The only way your arrangement could work would be to designate one relay as a *master* power control and that one has the main power coming in which then feeds through to the common rail to supply the other three relays. If this is what you want, then you will have to ensure that the relay designated as master (and its connector) has *at least* three times the capacity of the other three relays and connectors (or all four relays have *at least* three times the capacity you would otherwise need).

---

¹ Note: doing it this way around ensures that when the relay is in the *off* position the *NC* pin isn't live. The only pin that would ever be live is the *common* pin. Safety first...!
> 0 votes

# Answer
**The critical part is the relay.**

I'd want relays with rated to switch the load and and handle the cold current that the lamp wants.

I also want to see a good creepage clearance distance between digital side and the relay outputs. Relays which put the common contact between the coil terminals are probably a bad choice here, relays that instead have the contact terminals at one end and the coil terminals at the other make the PCB layout easier.
> 0 votes

---
Tags: relay
---


title: Arduino analog joystick

text:
# Question
Title: Arduino analog joystick
I'm planning to make a handbrake for my racing simulator (Assetto Corsa) and I wanted to know how can I transform arduino into a joystick so the game can read the **analog** input?

Thanks in advance, and sorry for my bad english.

# Answer
I made this video and github just for this about a year ago.

And here is the code:

```
/*
2-axis joystick connected to an Arduino Micro
to output 4 pins, up, down, left & right

If you are using pull down resistors, change all the HIGHs to LOWs and LOWs to HIGH.
This skectch is using pull up resistors.

*/

int UD = 0;
int LR = 0;
/* Arduino Micro output pins*/
int DWN = 13;
int UP = 12;
int LEFT = 11;
int RT = 10;
/* Arduino Micro Input Pins */
int IUP=A0;
int ILR=A1;

int MID = 10; // 10 mid point delta arduino, use 4 for attiny
int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, HIGH);
  digitalWrite(UP, HIGH);
  digitalWrite(LEFT, HIGH);
  digitalWrite(RT, HIGH);

  //calabrate center
  LRMID = analogRead(ILR);
  UPMID = analogRead(IUP);
}

void loop(){

  UD = analogRead(IUP);
  LR = analogRead(ILR);
  // UP-DOWN
  if(UD < UPMID - MID){
   digitalWrite(DWN, LOW);
  }else{
   digitalWrite(DWN, HIGH);
  }

  if(UD > UPMID + MID){
   digitalWrite(UP, LOW);
  }else{
   digitalWrite(UP, HIGH);
  }
  // LEFT-RIGHT
  if(LR < LRMID - MID){
   digitalWrite(LEFT, LOW);
  }else{
   digitalWrite(LEFT, HIGH);
  }

  if(LR > LRMID + MID){
   digitalWrite(RT, LOW);
  }else{
   digitalWrite(RT, HIGH);
  }

  delay(400);

}

```
> 3 votes

# Answer
Never tried it with the Arduino, but it's quite easy to do with Teensy (which is mostly compatible with Arduino).

Teensyduino actually includes several examples.
> 0 votes

---
Tags: arduino-uno, programming, potentiometer, emulation
---


# Question
Title: Count RISING edges of a wave form by using ARDUINO
I have realised an electrical circuit that gives 5V in output. When I press a button, it gives 0V. So I have in output a square wave (5V - 0V). I would like to count how many times I press the button, by using an Arduino MEGA AT2560. I have written this code below, but it doesn't work, because when I press the button, it increase the counter three or four times. For example: I press the button 5 times, but the counter has arrived to 30!

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

unsigned int count_hall_f = 0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(0, interrFront, RISING); //18
}

void loop(){

}

void interrFront() {
  count_hall_f++;
  Serial.println(count_hall_f);
}

```

An example of the result is:

```
1 <- I pressed here
2
3 <- I pressed here
4
5
6
7
8
9
10
11
12 <- I pressed here
13
14
15
16

```

# Answer
> 1 votes
> I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have a page about switches \- somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.

---

Example schematic:

Results on input pin:

(Maths supporting that figure on the above page).

---

Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.

# Answer
> 0 votes
Simple way to do it: since the first interrupt, wait a pre-determined amount of time (depends on the button you use, could be 100us to few tens of ms) and check again that the value is what triggered the interrupt.

This will kill the effect of the mechanical bounces.

You can even disable interrupts during the delay.

There are much more sophisticated way to do it, but this should be good enough to get you started on the way to debounce your inputs.

---
Tags: interrupt
---


# Question
Title: Is there any problem about calling if (Serial) many times?
I am trying to debug a problem that I think may be related to the debug code itself and I tried to use theese macros:

```
#define DEBUG_PRINT(x) { if (Serial) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (Serial) { Serial.println(x);} }

```

That works a bit but everything starts running really slow and my sketch get to hung up quite fast. Maybe it is timing related but does not seems like that.

if I change that by this the problem is gone:

```
#define DEBUG_PRINT(x) { if (true) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (true) { Serial.println(x);} }

```

I'm using Arduino Pro Micro (Leonardo).

Is there any problem about calling if (Serial) so many times?

Full sketch here

# Answer
There is no *problem*, no, but yes it will slow you down.

This is the source code to the boolean operator for the Serial constructor for CDC:

```
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

```

As you can see from that all it does is check the value of a variable. However it also imposes a 10ms delay¹. Personally I'd have written it as:

```
Serial_::operator bool() {
    return (_usbLineInfo.lineState > 0);
}

```

And on top of that I'd have made it inline.

You might want to experiment by editing CDC.cpp to replace the bool operator with that smaller, leaner, code and see if it improves things (or breaks them completely)².

**Edit:** I have submitted a pull request to the Arduino GIT repository with a better method of monitoring the line state and imposing the `delay(10)` when it is actually needed rather than at every call to the `bool` operator regardless of need.

---

¹ *This is done to allow the port to complete opening at the PC end before data is allowed to be sent. A better system would only perform the `delay()` at the moment of port opening rather than every call to the operator.*

² *Note that this would remove the delay which may be a bad thing as you may lose the first few bytes of the first debug message. A better system is in the pull request mentioned in the edit to this answer.*
> 2 votes

# Answer
The real flaw is testing if Serial is available all the time. For one thing, that wouldn't work on a Uno etc. How about something like this?

```
// make true to debug, false to not
#define DEBUG true

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); while (!Serial) { } } while (0)
  #define Trace(x)      Serial.print   (x)
  #define Trace2(x,y)   Serial.print   (x,y)
  #define Traceln(x)    Serial.println (x)
  #define Traceln2(x,y) Serial.println (x,y)
  #define TraceFunc()   do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

```

That only does the Serial.begin() once, and the test for waiting for Serial to become available once.

Then, depending on the DEBUG define, the debugging code is executed or not. The fancy `((void) 0)` calls get optimized away completely by the compiler if DEBUG is false, thus making them have no effect if debugging is off (which wouldn't apply to your code).

---

*(Edited to add)*

> As you can deduce from my macros I wanted to debug IF the serial port is connected. I don't want to wait for it to be connected.

Well it wasn't *immediately* obvious from your code. In that case I suggest you test in the main `loop` function every second or so, to see if `Serial` is true. If so, set a flag. Test that flag in your debug function. That way you aren't slowing down every single `Serial.print` by 10 ms.

Like this amended code:

```
// make true to debug, false to not
#define DEBUG true

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); } while (0)
  #define Trace(x)      do { if (serialConnected) Serial.print   (x); }     while (0)
  #define Trace2(x,y)   do { if (serialConnected) Serial.print   (x, y); }  while (0)
  #define Traceln(x)    do { if (serialConnected) Serial.println (x); }     while (0)
  #define Traceln2(x,y) do { if (serialConnected) Serial.println (x, y); }  while (0)
  #define TraceFunc()   do { if (serialConnected) { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__);} } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

const byte LED = 13;

bool serialConnected;
unsigned long timeSerialLastTested;

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced debugging!"));
  TraceFunc ();  // show current function name

  pinMode (LED, OUTPUT);
}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  // every second, see if the Serial port is available
  if (millis () - timeSerialLastTested >= 1000)
    {
    timeSerialLastTested = millis ();
    serialConnected = Serial;
    digitalWrite (LED, !digitalRead (LED));  // blink LED
    }

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

```
> 0 votes

---
Tags: serial, arduino-leonardo
---