# Question
Title: How to move from arduino to physical prototype
I've been reading a bit about moving from Arduino to PCB and it seems a bit daunting. For now, all I really want to do is take something I've built, and make a few changes so that I can actually create a casing for it and make sure everything stays connected.

I've attached a photo of my project. What I am trying to do is create a box, where 4 pushbuttons sit in a box, with LEDs next to them. I will probably create foamboard cutouts for the spaces where the pushbuttons and leds sit. The wiring for the push buttons and the LEDs need to be hidden below the foam board, along with the arduino itself and the servo motor - which is where I get stuck.

What do I need to do to essentially "lengthen" the wires for the pushbuttons and LEDs, and make sure all the components stay secure in the breadboard (the push buttons in particular like to pop out)? Is there a way to do this without making a PCB? I understand the concept of soldering components into protoboard, but as far as cutting / printing the circuits or whatever, it is really confusing to me.

I'd appreciate any guidance. If you see anything wrong with my wiring setup too, I'd love a learning experience on that as well. Thanks!

# Answer
The best thing to do is, of course, to use a PCB. But it doesn't need to be a custom PCB; there are plenty of pre-made PCBs that are usable for approximately 98% of designs. Here are just a few:

For switches just use a panel mount form. They come in everything from simple to robust to ridiculous.

LEDs can also be panel mount, or you can use a light pipe to make a LED on the PCB visible from the outside.

For power you can use a USB connection or a separate power jack with a voltage regulator. If you also need a serial connection then you should consider a pre-made serial module, and either use its built-in USB jack or a separate panel mount USB jack.

The servo can be mounted inside the case if appropriate, or can be connected to a PCB mount or panel mount connector instead.

Naturally the MCU itself should also be placed in a socket directly on the PCB. Don't forget the decoupling, the oscillator, and the ISP connector.

As for the circuit itself, you can get rid of the pullup resistors on the switches if you use internal pullups instead. And 100ohm is *way* too low a value for switch pullups regardless.
> 10 votes

# Answer
Learning to design a PCB can be a challenge. First, there's software choices, there's file formats, and then actually laying out a good board. That's before production and assembly, each with its own struggles along the way. It's no different than the first time you open Xcode and learn about Storyboards and Frameworks and Simulators and all that, or for that matter, learning any new skill, which at first is a daunting experience but through both setbacks and success eventually becomes easy.

So, I agree with everyone that suggests perfboards and variants. But I also want to show, as perhaps motivation, where you could be in a few months. I tend to see Arduinos as the development tool, not the final product, but I understand others are content to just use a standalone Nano or Pro Mini and forever dedicate it to their project.

These are three variants of the same device, it combines an Arduino/ATMega, a GPS, a serial port, and an RGB LCD. I first created it in on a breadboard, then moved to a perfboard, thought "that is ugly" and made a simple PCB. Pleased with that experience, I kept refining the schematic and layout until I finally called the project "done."

You also might consider making tiny PCBs just for specific components, like these two boards I make for buttons and lights.

The very first PCB I ordered from OSHPark was an amazing experience, opening the envelope and holding it like some religious relic. But since then it's become routine. If you do later go the PCB route, you might appreciate my summary of low-volume shops I've ordered from.
> 4 votes

# Answer
Using a **stripboard** is perfectly convenient to create a circuit that:

* will last longer than a breadboard prototype
* will cost less than wasting a breadboard for a long time

Stripboards can be found in any good electronics retailer (I buy mines at Conrad).

You will need a soldering iron (and the skills that are needed for it, but that is not so difficult as some people think).

You could even go one step further and create an Arduino on the same stripboard (many components from the UNO are not required for a circuit you want to build and keep "forever").

Another option, just a little bit more expensive, would consist in affording a **prototype shield** for Arduino, solder you circuit onto it and directly plug it onto your Arduino. The principles are the same as for a stripboard, except the prototype are has typically no strip, only holes on which you can solder components and wires.
> 3 votes

# Answer
You can use Arduino proto shield. It's a prototyping board shaped the way it can be plugged into the Arduino. There are over 9000 of them from different manufacturers. Then just solder the stuff you need on the proto shield.
> 3 votes

---
Tags: arduino-uno, sensors, wires
---


# Question
Title: Connecting two pressure sensors with one uno
I'm trying to connect two BMP180s to an arduino uno by using a multiplexer.

Here is the code that a guy has written before: I imported SFE\_BMP180 library but didn't do anything with the "typedef.h" thing.

I'm getting "Data does not name a type" error at the line 9. How can I solve this problem?

```
     #include <SFE_BMP180.h>
    #include <Wire.h>
    #include "typedef.h"

    #define SELECT_PIN 9
    #define ALTITUDE 510.0

#define P1_ACTIVE digitalWrite(SELECT_PIN,HIGH); //delay(10);
#define P2_ACTIVE digitalWrite(SELECT_PIN,LOW);  //delay(10);

SFE_BMP180 bmp1,bmp2;
boolean readSensors(Data *data1, Data *data2);

Data newData(char id)
{
  Data d ;
  d._id = id ;
  return d ;
}
void setup()
{
    boolean failed = false ;
    pinMode(SELECT_PIN, OUTPUT);

    Serial.begin(9600);

    P1_ACTIVE

    if(bmp1.begin()){
        Serial.println("BMP #1 init success.");
    }
    else
          failed = true ;

    P2_ACTIVE
    if(bmp2.begin()){
          Serial.println("BMP #2 init success.");
    }
    else
        failed = true ;

    if(failed){
        Serial.println("Error in BMP180 init.");
        while (1);
    }
}

void loop()
{
  Data d1 = newData('1');
  Data d2 = newData('2');

  boolean read = readSensors(&d1,&d2);

  if(read){
          /* print the value to serial terminal */
...

```

# Answer
You can try my BMP080/BMP180 Arduino library My library doesn't require use of floats of math library, making your sketch very small and fast.
> 1 votes

---
Tags: arduino-uno
---


title: IDE support for Arduino micro

text:
# Question
Title: IDE support for Arduino micro
I have an Arduino micro http://arduino.cc/en/Main/arduinoBoardMicro I was looking to know which is the lowest version of the IDE that support it. Actually on the IDE 0023 is not present in `Tools > Board`.

# Answer
According to the Arduino Software Release Notes, support for the Arduino Micro was added in 1.0.2.
> 2 votes

---
Tags: ide, arduino-micro
---


# Question
Title: Temperature sensors TMP36 and LM35 have temperature diff. (offset) in the same circuit
I am trying to use the two temperature sensors TMP36 (from Sparkfun Inventor's kit) and KEYES LM35.

In read TMP36 Sensor and I convert the result to Celsius using the following code:

```
// TMP36 input sensor -> degrees Celsius calculation
TM36reading = analogRead(TM36sensor);
TM36voltage = (TM36reading/1024.0)*5.0;
//converting from 10mv per degree with 500 mV offset
//             (TMP36 voltage - 500mV) times 100)
TM36degreesC = (TM36voltage - 0.5) * 100;

```

In read LM35 Sensor and I convert the result to Celsius using the following code:

```
// LM35 input sensor -> degrees Celsius calculation
LM35reading=analogRead(LM35sensor);    // reads the LM35 output
LM35voltage = (LM35reading/1024.0)*5.0;
LM35degreesC=LM35voltage*100.0;

```

I have connected also a LCD display to monitor visually the values of these two sensors. Here is my full code. I use also a serial log. Here is a sample from this serial log (as you can see there is a difference/offset between 0.5 to 0.9 Celsius).

```
TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 16.89, LM35: 16.11 diff -> 0.78
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.87, LM35: 16.60 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 17.09 diff -> 0.20
TM36: 17.38, LM35: 17.09 diff -> 0.29
mean difference between sensors: 0.48
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 16.41, LM35: 17.58 diff -> 1.17
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 17.09 diff -> 0.20
mean difference between sensors: 0.71
TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 17.09 diff -> 0.29
TM36: 16.89, LM35: 16.11 diff -> 0.78
mean difference between sensors: 0.93

```

I power the Arduino from the computer using the USB cable. When the computer is ON we have the offset that I already demonstrated above. When the computer is turned off (after computer shutdown), immediately the sensor of TMP36 falls around 1 Celsius.. And then both sensors have similar temperature.

Why there is this temperature difference between TMP36 and LM35 sensors? How can we "fine tune" these sensors to monitor the real temperature?

# Answer
The sensors have different accuracy, according to their datasheets. The TMP36 has **±2°C typical accuracy**, while the the LM35 has **0.5°C typical accuracy** (over 25°C). Read the datasheet carefully and pay attention to the characteristics, more specifically to the accuracy error graphs for each sensor. At your measured temperature (~17°C), you should expect the following error (the red line is not super accurate, but should give a general clue):

**LM35:**

**TMP36:**

In addition, as **Michal** stated, you might have noise in your circuit, and you are not connecting the TMP36 as per the datasheet suggests (note the capacitor between +V and Ground):
> 5 votes

# Answer
There are many things, first different sensors have different accuracy or they may not have been calibrated from the factory. In addition both are analog and analog reading is susceptible to noise. My guess is there is a high frequency noise on power line coming from the computer interfering with your readings. Try putting a small (100nF) capacitor between AREF and GND pin. You can always just take median of the measured values as the actual temperature.
> 3 votes

---
Tags: temperature-sensor
---


# Question
Title: How to avoid the code interrupting itself?
I have this code, which I am using with a potentiometer to control the speed of a automotive fuel injector. In it, I have specified how long the injector shall stay open by using the delay functions. However, whenever the code runs into a delay call, it pauses the whole code for that amount of time. Although it's not significantly long, it would still be better if it could keeping running analogInput and at the same time run through the if statements, without any interference from either. So basically run two different process simultaneously.

I remember reading somewhere that this is possible with threading? But do you need a library for that? I know Python has a threading library built in, and you can actually use it pretty easily, but what about Arduino? How could I run these two process at the same time?

Here's my code:

```
#define in1 12

void setup(){
 Serial.begin(9600);
 pinMode(in1, OUTPUT);
}

void loop(){
 float rotationValue = analogRead(A1);            //read raw input from potentiometer
 float percentValue = rotationValue / 10.23;      //convert to percent 0-100
 Serial.println(percentValue);                    //print it to screen
 if(percentValue >= 0.0 && percentValue <= 1.0){
  digitalWrite(in1, LOW);                         //injector 1 off
 }
 else if(percentValue > 1.0 && percentValue <= 25.00){    //cycle at 100 millisec.
  digitalWrite(in1, HIGH);
  delay(100);
  digitalWrite(in1, LOW);
  delay(100);
 }
 else if(percentValue > 25.00 && percentValue <= 50.00){    //cycle at 50 millis.
  digitalWrite(in1, HIGH);
  delay(50);
  digitalWrite(in1, LOW);
  delay(50);
 }
 else if(percentValue > 50.00 && percentValue <= 75.00){      //cycle at 25 millis.
  digitalWrite(in1, HIGH);
  delay(25);
  digitalWrite(in1, LOW);
  delay(25);
 }
 else{              //cycle at 10 millis.
  digitalWrite(in1, HIGH);
  delay(10);
  digitalWrite(in1, LOW);
  delay(10);
 }
}

```

# Answer
You can't use threads on an arduino, they don't exist. you can get some pseudo multitasking going with interrupts, but that is not necessary in your case.

You should be able to refactor your code to avoid using delays without much work. The arduino library provides `millis()` to keep tract of the time since the arduino was powered on in milliseconds.

something like this could replace all the delays in your code

```
static boolean state;
static uint32_t time;
if(time < millis()){
    time += delayFromPercent(percentValue);

    state = !state;
    if(percentage < 1.0) state = false;
    digitalWrite(in1, state);
}

```

Then, somewhere else place

```
uint32_t delayFromPercent(float percent){
    if(percent < 25) return 100;
    if(percent < 50) return 50;
    if(percent < 75) return 25;
    return 10;
}

```

alternately, if you don't really want the discrete steps, you could use this instead

```
uint32_t delayFromPercent(float percent){
    return max(10, 100-percent); // don't return less than 10ms
}

```

you could change it to react a bit quicker by comparing the time plus calculated delay now rather than when it last set the pin, but that strays farther from what your initial implementation would have done.

In any case, this code will should be able to switch pin in1 without making the rest of your code slow down, as long as the other code does not use delays either.
> 2 votes

---
Tags: arduino-uno, programming, analogread, threads
---


title: MFRC522 minor problems

text:
# Question
Title: MFRC522 minor problems
I'm working on a small project for a presentation. My goal is to read the UID of multiple Mifare Classic cards and compare it to a hardcoded list for different actions. All is well (the reading and comparing part that is) but 2 small problems that I have encountered are:

* The first (maybe up to three, since the reader is a little bit on the fast side) read after uploading my code will return a UID of just 0s and a wrong PICC type.
* After reading a PICC and then trying to read another, the reader prints the UID / PICC Type of the reader before, which is kinda not helpful when trying to light LEDs based on UID.

Here is my sketch:

```
/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
  String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}

```

# Answer
> -1 votes
```
/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
// String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
// byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();
     // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
 String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
 byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}

```

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


# Question
Title: Program got so many errors about expected ) or ; before either
This is my first time to try program arduino, and I am clueless. I have a friend who told me about things work, and he told me the programming language is C (or similar to C) which we have learned in our class. I just program as my friend examples, but it doesn't work and return error codes about expected ; before ( or ) before ; etc.

I'm not sure why this wont work. This is the hardware (simulated) I going to make.

here's the code:

```
#define dw 8; //buttons down
#define ri 9; //buttons right
#define le 10; //buttons left
#define up 11; //buttons up
#define ok 12; //buttons ok
#define mn 13; //buttons menu
#include <LiquidCrystal.h>
LiquidCrystal lcd(6,5,4,3,2,1);
int i=0;
char input[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

void setup()
{
  pinMode(dw, INPUT);
  pinMode(ri, INPUT);
  pinMode(le, INPUT);
  pinMode(up, INPUT);
  pinMode(ok, INPUT);
  pinMode(mn, INPUT);
}
void intext()
{
  int c=0, lim=16;
  for(i=0;i<lim;)
  {
    lcd.setCursor(c,1);
    input[i]=97;
    if(dw=HIGH)
    {
      if(input[i]>122)
        input[i]=97;
      input[i]=input[i]+1;
      lcd.print(input[i]);
    }
    if(up=HIGH)
    {
      if(input[i]>97)
        input[i]=122;
      input[i]=input[i]-1;
      lcd.print(input[i]);
    }
    if(ri=HIGH)
    {
      c=c+1;
      lcd.setCursor(c,1);
      lcd.print(input[i]);
    }
    if(le=HIGH)
    {
      c=c-1;
      lcd.setCursor(c,1);
      lcd.print(input[i]);
    }
    if(ok=HIGH)
    {
      lim=i+1;
    }
  }
}

void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Masukan kata:");
  intext();
}

```

I have no idea why it wouldn't work. I'm sorry if I'm too stupid to understand. Thank you!

Edit: oh yeah, the errors, here:

```
  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Windows NT (unknown)), Board: "Arduino Uno"
programyuhu.ino: In function 'void setup()':
programyuhu:14: error: expected `)' before ';' token
programyuhu:14: error: expected primary-expression before ',' token
programyuhu:14: error: expected `;' before ')' token
programyuhu:15: error: expected `)' before ';' token
programyuhu:15: error: expected primary-expression before ',' token
programyuhu:15: error: expected `;' before ')' token
programyuhu:16: error: expected `)' before ';' token
programyuhu:16: error: expected primary-expression before ',' token
programyuhu:16: error: expected `;' before ')' token
programyuhu:17: error: expected `)' before ';' token
programyuhu:17: error: expected primary-expression before ',' token
programyuhu:17: error: expected `;' before ')' token
programyuhu:18: error: expected `)' before ';' token
programyuhu:18: error: expected primary-expression before ',' token
programyuhu:18: error: expected `;' before ')' token
programyuhu:19: error: expected `)' before ';' token
programyuhu:19: error: expected primary-expression before ',' token
programyuhu:19: error: expected `;' before ')' token
programyuhu.ino: In function 'void intext()':
programyuhu:28: error: expected `)' before ';' token
programyuhu:28: error: expected primary-expression before '=' token
programyuhu:28: error: expected `;' before ')' token
programyuhu:35: error: expected `)' before ';' token
programyuhu:35: error: expected primary-expression before '=' token
programyuhu:35: error: expected `;' before ')' token
programyuhu:42: error: expected `)' before ';' token
programyuhu:42: error: expected primary-expression before '=' token
programyuhu:42: error: expected `;' before ')' token
programyuhu:48: error: expected `)' before ';' token
programyuhu:48: error: expected primary-expression before '=' token
programyuhu:48: error: expected `;' before ')' token
programyuhu:54: error: expected `)' before ';' token
programyuhu:54: error: expected primary-expression before '=' token
programyuhu:54: error: expected `;' before ')' token

```

# Answer
In C and in C++, `#define` is not an instruction of the language, but a directive of the **pre-processor**.

What it does is define a "macro" which will be replaced everywhere it appears later on in the source file.

For instance:

```
#define DUMMY 152

int x = x + DUMMY;
myfunction(DUMMY);

```

will be changed, before compilation, into:

```
int x = x + 152;
myfuntion(152);

```

In the example above, `DUMMY` is replaced everywhere by what follows it in the `#define` line, i.e. 152.

As pre-processor directive is not an instruction, it shall not be ended by `;`. If you add `;` at the end of a `#define`, then it will be part of the replacement:

```
#define DUMMY 152;

int x = x + 152;;
myfuntion(152;);

```

As you can see now, `DUMMY` is replaced by `152;`, not just `152`.

So the solution in you example is to remove all `;` that are at the end of `#define` lines:

```
//buttons down
#define dw 8
//buttons right
#define ri 9
//buttons left
#define le 10
//buttons up
#define up 11
//buttons ok
#define ok 12
//buttons menu
#define mn 13

```

Note that comments should also be removed from the `#define` otherwise they would also appear everywhere the replacements are done.
> 2 votes

# Answer
Here's the first line of your code:

> ```
> #define dw 8; //buttons down
>
> ```

Here's the first error line:

> ```
> pinMode(dw, INPUT);
>
> ```

Let's put them together and see what we get:

```
pinMode(8; //buttons down, INPUT);

```

That's not valid C++. Using the output I've shown you, modify the input until it looks correct. And then keep doing it until the code compiles.
> 6 votes

# Answer
The errors are in your `#define` statements.

These should not have `;` as they are not executable statements
> 2 votes

---
Tags: programming, display, string
---


# Question
Title: Sending multiple channels with bluetooth
I have ordered my HC-05 BT modules. My question is this: Is it possible to send multiple channels over bluetooth. For example, stereo sound has two channels. I think i have seen people do this but i'm not sure.

If it is possible, could you please provide some more information on how its done? Thanks!

# Answer
> 2 votes
The BT module will connect as a SPP (serial port) device, and then pass the serial data to and from the arduino and whatever you choose to connect to (that supports SPP).

There is only one channel, and in any case only one set of TX and RX wires that will be connected to your arduino, but this does not stop you from sending as much data of as many different types as you want. You are only limited by the BAUD rate and how much time the message will take to send.

For complicated data transfers you will need to write the code for a protocol so both sides can make sense of what the other says. You are free to do whatever you can think of here, although if you need to make a complicated protocol you might get some use out of the answers to this question:

Communication Protocol Best Practices and Patters

# Answer
> 1 votes
To add to BrettM answer, Bluetooth is the *RF* standard on which many protocols can *stack up*; each such protocol is called a 'Bluetooth Profile'.

The Bluetooth model you purchased comes only with the Serial Port Profile (**SPP**) profile implemented in the firmware. This mean that you can use it for establishing serial communication.

As serial protocol will probably be too slow for stereo Audio over Bluetooth, Audio usually use a different profile called Advanced Audio Distribution Profile (**A2DP**). Unfortunately, the HC-05 does not come with this protocol stack implemented in its firmware. If your primary goal is to send stereo Audio over Bluetooth, consider purchasing a dedicated chip, such as **XS3868** or Sparkfun's **RN-52**. For beginners, it is recommended to get one with a breakout board for easy integration with Arduino projects.

For completeness, there are many other Bluetooth profiles, each is optimized for different task. See Wikipedia for the full list: http://en.wikipedia.org/wiki/List\_of\_Bluetooth\_profiles

---
Tags: bluetooth
---


# Question
Title: Playing audio files with sine wave from arduino
So, when searching for a way to play audio files through the Arduino, I came across this site: How to play WAV audio files with Arduino Uno and MicroSD card

This seems like a really good library (although I haven't had the time to really play around with it yet). Has anyone used this before, and, if so, is it a good library to use, or do you know of better ones out there which you would recommend?

# Answer
> 1 votes
I used some time ago the TMRPCM library that the tutorial you linked used and I was very satisfied.

It doesn't take too much space and it has some really unique and neat features like the possibility to use two speakers instead of one to reproduce stereo audio (Unfortunately you need a more powerful AVR IC, surely not an UNO board/328 IC for this feature if you don't want to occur in bad reproduction)

From GitHub's wiki:

> All 328 based boards: Arduino Uno, Nano, Duemilanove, etc
>
> Mega Types: 1280, 2560, etc
>
> No Due support currently.

You can only have WAV files on the SD but they can be very large (other libraries limit you to a specific maximum size/duration) and you need to connect the SD to the arduino via SPI (as far as I know it is the only way to communicate directly with an SD card).

Also, you will need to convert the files to 8 bit WAV (so it's faster and easier for the arduino to reproduce the sound) with sample rate from 8 to 32khz, mono audio.

Be careful just because you'll need to power the SD with 3.3 volts otherwise you'll fry the entire card.

> Most of the extra features require more memory, more program space, and in some cases, more processing power for playback Some of them are still being fine tuned. Please keep this in mind when enabling these features.

If you want to take a look, go to this page for more informations on the advanced features

A last thing that I have to say is that the functions are really straightforward:

```
TMRpcm audio;
audio.play("filename");    plays a file
audio.play("filename",30); plays a file starting at 30 seconds into the track
audio.speakerPin = 11;     set to 5,6,11 or 46 for Mega, 9 for Uno, Nano, etc.
audio.disable();           disables the timer on output pin and stops the music
audio.stopPlayback();      stops the music, but leaves the timer running
audio.isPlaying();         returns 1 if music playing, 0 if not
audio.pause();             pauses/unpauses playback
audio.quality(1);          Set 1 for 2x oversampling
audio.volume(0);           1(up) or 0(down) to control volume
audio.setVolume(0);        0 to 7. Set volume level
audio.loop(1);             0 or 1. Can be changed during playback for full control of looping.

```

---
Tags: pins, sd-card
---


# Question
Title: control a jack/cylinder to open/close a window
I want to open the window to let the cat enter or go out, but the mecanism of the window may me think that the best way should be to use a jack/cylinder (I don't know what term is more appropriate in english for that) to open and close the door.

I will use rfid or another wireless think to know it the cat is in the place and then open the wondow but I want to close the window and let the wndow close event if there is little bit of wind, so I need domething robust.

Do you know a good hardware with (this would be the best) piece of code that can help me for that?

Thanks in advance

# Answer
Check out this instructable \- for opening a window for a cat :) The guy used a servo, Towerpro MG995 with 10 kg torque for opening/closing the window, and a 10cm distance sensor for sensing the cat (he used Pololu Carrier with Sharp GP2Y0D810Z0F Digital Distance Sensor, but I believe that any proximity sensor will do).

This is a pictrure of the mechanism, seems quite robust:
> 1 votes

---
Tags: hardware, communication
---


# Question
Title: Is there a radar - like sensor that can tell me the distances of multiple things around the sensor?
I'm trying to develop something that requires accurate distance measurement of objects around the center of the contraption. However, I cannot find any way to achieve this other than using a bunch of infrared distance sensors. Really, I'm looking for something that costs at most $200 and is compatible either with arduino, PC, or raspberry pi.

This may not be the place for this, if not, please inform me.

Thanks in advance!

# Answer
> 2 votes
What you're looking for is called **lidar** \- but it's not cheap. RPLIDAR is the current price leader for non-hacky solutions, and I haven't seen it for much less than $400 anywhere.

---
Tags: sensors
---


# Question
Title: Read all Digital input in arduino once time and sent theme to serial
i need to read all Read all Digital input in arduino once time; example:

```
Serial.write(digitalRead(0),digitalRead(1),...,digitalRead(13));

```

to receive state of all digital pin in one times from my app build with delphi

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

void loop()
{
  Serial.print("<");
  for (int p = 0; p < 14; p++)
  {
    Serial.print(digitalRead(p));
  }
  Serial.println(">");
}

```
> 1 votes

# Answer
According to the pin mapping, D0-D13 and A0-A5 are mapped to ports B, C, and D. So simply read the raw ports as bytes, send the values, and decode them on the other side.

```
Serial.write(PINB);
Serial.write(PINC);
Serial.write(PIND);

```

Note that A6 and A7 (on boards that have them) are not mapped to digital pins and so cannot be read in this way.
> 3 votes

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


# Question
Title: Raspberry Pi with Arduino, Serial connection stops working
This is the hardware set-up at home,

Raspberry Pi GPIO -\> Logic Level Converter -\> Arduino -\> Multiple Relays

I am running Raspbian and NodeJS on the Pi while the Arduino is loaded with StandardFirmata. I connect NodeJS to the Arduino with the `johnny-five` package and it works well after it's started. But after extended periods, a few hours? The Arduino stops responding. Whatever command that I send to the Arduino won't be acted on. It's as though as the Arduino hung. Both the Raspberry Pi and Arduino are being powered indenpendently with a 1A Nokia USB Adapter.

Does anyone know why this is happening?

1. johnny-five
2. StandardFirmata
3. NodeJS Server Code

# Answer
If none of the code is yours, and all code from the Firmata library, then the most possible cause that comes to mind after reviewing the library code is memory leak, which makes the next allocation to fail and by thus breaking the code.

The Firmata library does perform dynamic memory allocation, checkout Firmata.c, so it is realistic - I would suggest to take it with the Library's author.
> 1 votes

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


# Question
Title: Using an Ethernet Shield and a tlc5940 together
I have am using an Arduino Uno R2 and TLC5940 to control a bunch of RGB LEDs. I want to add an Ethernet Shield R3 so that I can control the LEDs over a web-interface. However, the ethernet shield and TLC5940 use many of the same pins. Can I use them together? How?

# Answer
You can do this with out any additional hardware by putting the TLC5940 to BITBANG mode instead of SPI mode and making the Ethernet Shield use D8 pin instead of D10 pin.

## Software Changes

1. On line 61 of `sketchbook/libraries/Tlc5940/tlc_config.h` replace

```
#define DATA_TRANSFER_MODE    TLC_SPI

```

with

```
#define DATA_TRANSFER_MODE    TLC_BITBANG

```
2. On lines 339 - 341 of `arduino/libraries/Ethernet/utility/w5100.h` replace

```
 inline static void initSS()    { DDRB  |=  _BV(2); };
 inline static void setSS()     { PORTB &= ~_BV(2); };
 inline static void resetSS()   { PORTB |=  _BV(2); };

```

with

```
 inline static void initSS()    { DDRB  |=  _BV(0); };
 inline static void setSS()     { PORTB &= ~_BV(0); };
 inline static void resetSS()   { PORTB |=  _BV(0); };

```

## Hardware Changes

1. Bend leg of the D10 pin on the Ethernet Shield so it doesn’t connect to the D10 pin on the Arduino.
2. Connect D10 pin of Ethernet Shield to D8 pin on the Ethernet Shield
3. Connect the TLC5940 using the following pins:

```
-------------                                  ---u----
Ethernet   13|                           OUT1 |1     28| OUT channel 0
Shield     12|                           OUT2 |2     27|-> GND (VPRG)
           11|                           OUT3 |3     26|-> SIN (pin 7)
10,underneath|-> BLANK (pin 23)          OUT4 |4     25|-> SCLK (pin 4)
            9|-> XLAT (pin 24)             .  |5     24|-> XLAT (pin 9)
            8|-> to pin 10 on shield       .  |6     23|-> BLANK (pin 10 underneath shield)
            7|-> SIN (pin 26)              .  |7     22|-> GND
            6|                             .  |8     21|-> VCC (+5V)
            5|                             .  |9     20|-> 2K Resistor -> GND
            4|-> SCLK (pin 25)             .  |10    19|-> +5V (DCPRG)
            3|-> GSCLK (pin 18)            .  |11    18|-> GSCLK (pin 3)
            2|                             .  |12    17|-> SOUT
            1|                             .  |13    16|-> XERR
            0|                           OUT14|14    15| OUT channel 15
-------------                                  --------

```

Tested with Arduino 1.0.5 on Linux Mint 17 with r14 of the tlc5940arduino library.

References:
http://blog.andrewwei.mu/?p=19
http://forum.arduino.cc/index.php/topic,22111.0.html
http://forum.arduino.cc/index.php/topic,142977.0.html
http://forum.arduino.cc/index.php/topic,118265.0.html
> 0 votes

# Answer
When using multiple SPI devices the normal way to have them share a bus is to assign them distinct slave select lines. The problem here is that although the '5940 libraries use SPI to send data to it, the '5940 is not actually a proper SPI device and so lacks any sort of slave select line.

All is not lost, however. Since the '5940 responds only to SCLK (and GSCLK of course, but you should be running that one separately) all you need to do is inhibit it while nSS for the Ethernet module is active. This can be done with just a little bit of external circuitry. Since nSS must be high in order for the Ethernet module to be inactive, we can AND SCK with nSS to derive SCLK from it.

Using a 74HC08 for this would work, although it leaves 3 of the gates unused. A 74HC02 will let you do it with no wasted gates, but with a slightly higher propagation delay.

And of course, the requirement to clock in the grayscale data before the grayscale cycle completes is still there; properly interleaving this with the Ethernet communications is left as an exercise for the reader.
> 0 votes

---
Tags: arduino-uno, ethernet, tlc5940
---


# Question
Title: Why does Arduino use USB A-B plug, instead of A to micro USB plug?
I understand that A-B plug used to be common but they could have switched to micro without issues.

My questions:

* Why does Arduino use USB A-B plug, instead of A to micro USB plug?
* What are the challenged Arduino would be facing if they switched to micro USB?

Note: By "Arduino" I'm referring to Arduino models that do not come with a micro USB port such as the most common Uno & Mega.

# Answer
*Please note that this answer is based on speculation and some common sense rather than on insider information*:

If you take look at the hardware index, you'll notice that significant parts of the layout (drill holes, pin spacing, and position and **type of the USB jack**) haven't changed between the *Arduino Extreme* and the current *Arduino UNO R3*), while other improvements have been made. For changes between the UNO R2 and R3, please see Arduino UNO FAQ at adafruit (link provided by **jfpoilpret**).

It is thus reasonable to me that keeping the USB jack was a deliberate design decision: Improve if possible, but keep the layout changes to a minimum and allow for maximum backwards compaptibility.

*But again, this is just the guess of a user!*
> 2 votes

---
Tags: usb
---


title: ov7670 + Sd Card + arduino

text:
# Question
Title: ov7670 + Sd Card + arduino
I have three devices for making a motion activated security camera system:

* this is the camera : LINK OV 7670
* this is the SD Card module: LINK
* and a basic motion Sensor: PIR with 3 pin

I have an Arduino UNO and an Arduino Mega 2560.

I can connect the SD card and sensor, they work fine but I cannot connect the camera as there are not enough pins for it on UNO.

Is there a chance to connect all of them without any additional device?

I saw some working project with additional device (arducam) but I do not have much money to spend on this project.

# Answer
This camera module requires the use of additional hardware, as the camera and Arduino operating frequencies differ, which can result in loss of synchronization and changes to the image, and other connection problems.

Thus, we must use an integrated circuit intermediary, making the connection between the camera and the Arduino. The function of this chip is to receive the camera information, store them and then send them to the Arduino using the digital doors, much faster than if we used the serial communication.

An example of an integrated circuit that could be used is AL422, suitable for treating a video signal, which also is embedded in **some** OV7670 modules.

Looking like the connection pins behave in 7670, your module should be equal to it. So spare pins to be able to make other necessary connections.

Would better check the connection through the datasheets:

7670 datasheet

AL422 datasheet

An example of project

But to answer your question; You'll need to purchase a piece more if you don't have AL442.

Regards,
> 5 votes

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


# Question
Title: What are the benfits of global variables over static class members?
On an embedded system we use global variables often to keep dynamic memory consumption on heap and stack low. But global variables are also considered bad programming practice if they aren't used in a global sense, i.e. they are used only inside one or two functions.

So I really want to make use of the possibilites to protect my code from myself. Of course, the instantiation mechanism of c++ is to avoid on an embedded system with low resources, like an arduino. So I write classes with static members (and member functions) only. Many of the libraries shipped with arduino seem to work this way, too.

I'm curious if there's a single drawback of moving static variables or even const arrays (designed for deposit in progmem) from global namespace to a class namespace and making them private?

I'm primarily interested in drawbacks arising from the combination of OOP with the arduino platform (using an arduino uno) with avr-gcc.

# Answer
I can see no specific drawback in using static class members instead of global variables on Arduino. They will be managed the same in the end program.

The only difference I can see may arise based on how you design your classes (if design is correct, then no special problem shall arise):

Let's suppose you decale a class A:

```
class A {
    public:
    void f();
    void g();
    ...
    static void z();

    private:
    static int myStaticField;
    ...
};

```

if you need an instance of `A` for method `f()`, which does not need `myStaticField`, then that field exists anyway in your SRAM space.

But this is a corner-case, as in good OOD, `myStaticField` should be needed as soon as you need to work with class A (whatever method youwant to use).
> 3 votes

---
Tags: programming, c++, variables, progmem, avr-gcc
---


title: Servo motor swinging back to 0°

text:
# Question
Title: Servo motor swinging back to 0°
I just got my arduino and servo. But my servo may be acting strangely.

Whenever I tell the servo to go somewhere it keeps going to 0 than to that position and stops after 10-15 seconds or more.

This is the code used in this video

```
#include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(11);
      myservo.write(50);
    }

    void loop()
    {
    }

```

https://www.youtube.com/watch?v=rsikknT7z6g

It is connected like this:

Ground from Arduino to breadboard row 3

Ground from external power supply to breadboard row 3

Ground from SERVO to breadboard row 3

Power supply positive to servo VCC

Servo signal to pin 11

# Answer
Try with something like:

```
#include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(11);

    }

    void loop()
    {
        delay(2000);
        myservo.write(50);
        while(1);
    }

```

and let us know. But more important: disconnect the servo +5V wire from Arduino and use another power supplier!!!
> 1 votes

---
Tags: servo
---


# Question
Title: Photoresistor is not working, is there something wrong in the code?
I am trying to make the photoresistor work in a simple project.

The project is as follows: The LED light should light up brighter and brighter as the photoresistor reads less light in the room.

The problem: The reading is fixed on 1023. Therefore the LED never lights up. I cannot understand why.. Sometimes if I cover the sensor the readings go down to 900- 950 but never less even though it is completely dark around the sensor. Is there something wrong in the code? What could have gone wrong? Please note that the resistor connected to the sensor is 10k Ohm as is the one connected to the LED.

Here is the code

```
int photoPin = 0;
int pReading; // analog readings

int LED = 11; // red LED connected to pin 11
int LEDbrightness; //

void setup()
{
  //set up the serial connection
  Serial.begin(9600);
}

void loop()
{
  pReading = analogRead(photoPin);
  Serial.print("Photocell reading = ");
  Serial.println(pReading); // Analog reading

  pReading = 1023 - pReading;
  //map 0-1023 to 0-255
  LEDbrightness = map(pReading, 0, 1023, 0, 255);

  analogWrite(LED, LEDbrightness);
  delay(50);
}

```

Here are the connections

thank you!

# Answer
The code looks OK. It looks like it's your circuit which is the problem.

The main role of a photoresistor is to restrict the amount of **current** flowing through it when the light level is reduced. It won't directly affect voltage the way you're expecting (the analog pins respond to voltage).

However, it's pretty easy to make it affect voltage with a slightly different circuit. Try creating a **voltage divider** circuit, such that the supply voltage (5V) goes through the photoresistor, then through another resistor, and then to ground. The Arduino's analog pin should be connected between the photoresistor and resistor. (See the image below, although the resistor on the output probably isn't necessary in this case.)

This should cause the voltage on the analog pin to decrease when the light level decreases. You may need to experiment a little to find a suitable resistor value on the ground connection, although 2K Ohms is probably a good starting point. It basically affects the sensitivity of the circuit.

Image credit: Morteza Lahijanian (source)
> 8 votes

# Answer
Your wiring is wrong.

Analog inputs are high impedance and probably the impedance isn't really linear. So what voltage do you expect on your analog input, if its inner impedance is one or more orders of magnitude greater than that of your sensor and series resistor?

The inner impedance builds up the lower part of a voltage divider and your sensor and series resistor the upper part. The voltage measured will almost anytime almost 5V.

How to fix this? You will have to make a suitable voltage divider outside your arduino. Simly connect your input via another resistor to ground. So, how to determine the right value of the additional resistor? It strongly depends on your sensor and the brightness range you want to perceive. I recommend starting with 1kΩ. Let us know, what your readings are for full light and darkness. Then we can give some more hints.
> 0 votes

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


# Question
Title: Capture output from external device using Arduino Uno
I was unable to find this question anywhere but I want to use my Arduino Uno to capture the output of a Code 39 signal coming out of a separate device. Currently, my setup is similar to this:

I have a biometric hand reader that outputs a Code 39 signal along D1 while D0 stays at a constant 0 which can be seen here:

Ultimately, I want to use the Arduino Uno to take the input from the data line and convert the Code 39 signal to ASCII. The process should functions like this:

1. User enters their code into the hand reader and hand reader measures their hand
2. Reader *outputs* Code 39 signal to Arduino and software on Arduino converts barcode format to ASCII.
    * Note: I believe the Code 39 signal will represent something similar to this `*12345*`. The user ID code will **always** be five digits. `*` represent the start and stop characters for Code 39 barcode format
3. Arduino sends ASCII code to computer which checks remote database to ensure user is valid

I have my correct pins set as follows:

```
#include <SoftwareSerial.h>
#define D1 3
#define D0 2

void setup() {
    pinMode(D1, INPUT);
    pinMode(D0, INPUT);
}

```

Is it possible to either print out the binary representation of the signal via the Serial console or write to a file that I can view later on? My idea is to use the `loop` function to listen for the signals via `digitalRead()`

```
void loop() {
    digitalRead(D1);
    digitalRead(D0);
}

```

The last part is the thing I'm having an issue with since I can't seem to get the information printed to the serial console or written to a file. I tried this but it didn't work:

```
void loop() {
    foo();
}

void foo() {
    digitalRead(D1) == HIGH ? Serial.print("0") : Serial.print("1");
    Serial.println("");
    digitalRead(D0) == HIGH ? Serial.print("0") : Serial.print("1");
}

```

Any ideas on how to make this happen or is it impossible? I want to see the output of device so I can verify it's outputting what I think it is.

Lastly, I am using Visual Studio with the Visual Micro plugin so I can attempt to debug my code. I also have a OS X machine that has the Arduino IDE installed on it if I need a Mac for anything.

**Addendum:** I don't have ready access to an oscilloscope. However, I have tested this device on an oscilloscope and I did have output that seemed all wrong. I want to see what the arduino says it is to verify things before I continue with this project.

# Answer
First, let's find, what's wrong with your method. You try to poll the signal pins continously and write them out to serial. Default serial rate is 9600. Which means, that you can transmit approx. 900 characters per second. Looking at your oscillogram we can tell, that the signal you want to analyse has a base clock of roughly 2.5 kHz. Which means you definitely won't be able to sample every change of level with your method.

You can in fact use the `loop()` function to listen for changes, i.e. poll the signal, when you increase your serial baud rate. But I suggest using interrupts.

My suggestion is a three step process.

1. get the signal thoroughly recorded with all relevant information about the signal. This includes transmission to your PC via serial interface.
2. Analyse the signal offline. i.e. after having it received on your PC
3. Adapt your arduino code to decode it further before transmitting it to your PC

let's get to part 1): read Arduino documentation on interrupts the interrupt allows you to prevent interference of your two tasks (reading the inputs and writing to serial). What is the interesting information? I think it's the waveform (i.e. the signal in best resolution you can deliver). You can sample your waveform at a high rate, but the resulting data volume will overwhelm your serial output. Fortunately your signal has some obvious characteristics. Which are:

* obeys some timing (i.e. a clock)
* has a limited transmission length (protocol frame)
* has a limited transmission rate (as can be seen from oscillograph)

The best way to keep as much of the signal information by reducing the amount of serial transmission is to record the time of every level change.

**Updates: buffer used, buffered output after receiving timeout**

```
#define RECVTIMEOUT 2000 // we think, more than 2000 usec is end of transmission
#define MAXEVENTS 100

uint8_t inpin=2;
volatile unsigned long timestart=0;
uint8_t transmitLevel=LOW;

volatile uint8_t state=0; // little state machine: 0=nothing happened yet, 1=receiving data, 2=receiving timeout
volatile uint16_t tstamps[MAXEVENTS]; // we store timestamps of received symbols here
volatile uint16_t levels[MAXEVENTS]; // we store levels of received symbols here
volatile uint8_t index=0; // we save index of data here.
uint8_t count=0; // counter for later use.

volatile bool conflict=false; // will be set, if transmission conflicts with receive function.

void pinchange() // the ISR (interrupt service routine)
{
    switch(state)
    {
    case 0:
       timestart=micros();
       tstamps[index]=0;
       levels[index]=digitalRead(inpin);
       state=1;
       ++index;
    break;
    case 1:
       tstamps[index]=micros()-timestart;
       levels[index]=digitalRead(inpin);
       ++index;
    break;
    case 2:
       conflict=true;
    }
}

void setup()
{
    Serial.begin(115200); // high serial rate. don't forget to set the same in your IDE
    attachInterrupt(0, &pinchange, CHANGE); // the controller needs to know, where your ISR is.
}

void loop()
{
    switch(state)
    {
    case 1:
       if (index > 20)
       {
          if (micros()-timestart > RECVTIMEOUT)
          {
             state=2;
          }
       }
       if (index >= MAXEVENTS)
       {
          state=2;
       }

    break;
    case 2:
       for (count=0; count<index; ++count)
       {
         Serial.print(tstamps[count]);
         Serial.print(";");
         Serial.println(levels[count]);
       }
       if (conflict)
       {
         Serial.println("too less time to send data");
       }
       index=0;
       conflict=0;
       state=0;
    }
 }

```

This should output a fine csv with all your signal edges in microseconds, which you can paste directly to your favourite spreadsheet application. This is only for one signal. For analysing both, you have to enhance it accordingly.

**Update 1**

part 2)

from the gained data of our previous code version (snippet for brevity)

```
time signal timedifference
2614592 0   468
2615056 1   464
2615524 0   468
2616496 0   972
2616960 1   464
2617956 0   996
2618960 1   1004
2620424 1   1464
2621352 1   928
2622324 1   972
2623320 0   996

```

we can see two things.

1. The code in my first version of the answer didn't work properly. Every 1 should be followed by a 0 in column 2 and vice versa. This is apparently not true, which leads us to the conlusion, that we missed some events.
2. time differences seem to be multiples of roughly 470 μs. We can consider this as the length of a symbol.

So what's wrong with the code? I used noInterrupts() to stop Interrupts for copying the data. I hoped, there won't be level changes in this short period of time, but apparently this was not true. How to fix it? We better find another way to register the events and transfer them. I recommend sticking to the interrupt technique, but changing the way we store the events and reading it out. Let's use a buffer big enough for all events of a transmission. After a transmission we can send all data without hassle via serial to the PC.

What can we expect? 0s and 1s should be transmitted alternating, with reasonable timings. If we can prove this, we can change the main loop again for decoding code 39.

part 3)

* write code which stores a word of code 39 in a buffer
* another code which decodes that word into a byte when the buffer is full
* transmit that byte via serial

(many improvements possible).
> 1 votes

---
Tags: arduino-uno, serial, c++
---


title: Attiny85 and 433Mhz RF

text:
# Question
Title: Attiny85 and 433Mhz RF
I have this cheap RF link that I had working with the Arduni UNO, but I wanted to make it smaller and ATTiny85 should do the trick. The RF module is connected (data pin) to PB3 on the ATTiny.

But I am having some problems. It does not work, and I don't know why. My code:

```
#include <SoftwareSerial.h>

// PINS
#define SERIAL_TX PB3

SoftwareSerial mySerial(-1, SERIAL_TX);

void setup() {
  pinMode(SERIAL_TX, OUTPUT);
  mySerial.begin( 1200 );
}

void loop() {

  mySerial.write(0xAA);
  mySerial.write(0xAA);
  mySerial.write(0xAA);

  delay(1000);
}

```

# Answer
> 2 votes
The code you presented does not fit for working with the RF 433Mhz. I'm not sure what you think this code should do, but this is not the way to go with a 433Mhz transmitter.

I would suggest using a dedicated library for transmitting information using the 433. There are many libraries out there for doing that; two popular libraries would be the ManchesterRF and the VirtualWire, both includes code samples.

For example, sending data with ManchesterRF:

```
#include "ManchesterRF.h" //https://github.com/cano64/ManchesterRF

#define TX_PIN 3 //any pin can transmit
#define LED_PIN 13

ManchesterRF rf(MAN_4800); //link speed, try also MAN_300, MAN_600, MAN_1200, MAN_2400, MAN_4800, MAN_9600, MAN_19200, MAN_38400

uint8_t data = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  rf.TXInit(TX_PIN);
}

void loop() {

  rf.transmitByte(++data, data*data);
  digitalWrite(LED_PIN, digitalRead(LED_PIN)); //blink the LED on receive
  delay(100);
}

```

In addition, there are many other blogs around going step-by-step how to use 433Mhz Tx/Rx with ATtiny85, google is your friend :)

---
Tags: attiny, rf
---


title: 5 Switches 1 AI pin

text:
# Question
Title: 5 Switches 1 AI pin
Im starting to get into Arduino a little. Ive got a Small project to start me off, To keep it simple its: 5 level Switches, 1 flow switch and 3 solenoid valves.

This question is for the Level Switches.

Now Im wanting to save Pins as I'm using a Arduino UNO. So would I be right to use the method ive seen around here a few times of Making a Resistance ladder.

Question is. 1- Will the method of using the same value of resistors (2k2) work? I dont think so..

As multiple "buttons" ie the flot switches will be pressed at once it will end up having no idea whats happening correct?, I need to be able to Identify each one (0%,25% etc etc)

If I was to use different vales of resistance would that make a difference ?

Cheers

# Answer
Just look at this answer. When you press the LEFT switch, the SELECT button has no effect when pressed (i.e. it doesn't get detected, but also doesn't hinder detecting the LEFT button press). So in your case, you aren't really interested in the 0% button, when the 25% is pressed.

I wouldn't use same value resistors, as the resulting voltages would be non-linear, making it difficult to differentiate between the button at the far end ladder. If you'd use 2k2 everywhere, the voltages would be

* 100% 0.00v
* 75% 2.50v
* 50% 3.33v
* 25% 3.75v
* 0% 4.00v
* no value: 5v

In the answer provided above, voltages would be: 0, 0.71, 1.61, 2.47, 3.62, 5v
> 2 votes

---
Tags: serial, voltage-level, analogread
---


# Question
Title: too few arguments to function 'void setColor(int, int, int)'
When I put "c" inside `setColor(c);`

it tells me:

```
error: too few arguments to function 'void setColor(int, int, int)'.

```

I understand that I should put 3 arguments. What I don't understand is that the serial is correctly displaying the 3 arguments (255, 000, 000) so why it keeps telling me this error. What am I doing wrong ?

```
int rPin = 11;
int gPin = 9;
int bPin = 10;

void setup() {
    Serial.begin(9600);
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
}

void loop() {
    if (Serial.available() > 0) {
            delay(100);
            while (Serial.available() > 0) {
                char c = Serial.read(); // serial will display an rgb code, for exemple: 255, 000, 000 (red color)
                setColor(c);
            }
        }
}

void setColor(int red, int green, int blue) {
    analogWrite(rPin, red);
    analogWrite(gPin, green);
    analogWrite(bPin, blue);
}

```

# Answer
> 2 votes
In the context of C/C++, the type `char` refers to a primitive type that can contain exactly one byte of information, or 8 bits if you like.

> the serial is correctly displaying the 3 arguments (255, 000, 000)

In your question, you do not specify how you verify that this is indeed the information that returns from Serial.read. Serial.read returns one byte, which can be cast or parsed to an Integer but cannot be interpreted as the triplet (255,000,000) in no way. If you keep calling it repeatedly, however, as long as there is data (meaning that the result is greater than -1 or `Serial.available` returns a number greater than 0) - you can accumulate the characters to a meaningful string, which you can later split to three different `int` values. For example:

```
String incomingData = "";

void loop()
{
    if (Serial.available() > 0) {
         delay(100);
         while (Serial.available() > 0) {
             char c = Serial.read();
             incomingData.concat(c);
         }

         // now, the string incomingData will contain "255,000,000" which you can split into 3 different integers and send to setColor.
         // so, assuming the format "ddd,ddd,ddd":

         int color1 = incomingData.substring(0,3).toInt();
         int color2 = incomingData.substring(4,7).toInt();
         int color3 = incomingData.substring(8).toInt();
         setColor(color1, color2, color3);
    }
}

```

---
Tags: serial
---


title: Arduino UNO GPS module

text:
# Question
Title: Arduino UNO GPS module
I am thinking about buying a gps module for Arduino UNO.

I would like to install it on a self-build RC-car which is also controlled by Arduino. The problem is, I cannot install the gps module on the top of the car (on the surface), only the bottom and or/middle space is "free". My questions are:

1)Is there a module which can overcome a small layer of steel (max 2cm thick) and some plastic and still get a good signal?

2)It would be nice to be able to store the data into a memory card.

3)It would be a great plus to be able to gather data real-time through some kind of connection. Sadly I do not know how to do here. Is there some place where I can look up any of this?

Do you think that this http://www.adafruit.com/products/1272 is what I need?

thank you

# Answer
> 0 votes
1) Just break out the headers on the GPS module to make for connections to the UNO.

2) Add a SD expansion slot on top of the GPS Module and break out the pins for those as the required pins for those as well.

3) I am not sure what you are asking exactly, but it seems to me that you want to analyze the data real-time. Get a network shield and make sure you can SSH into it through another computer.

Note: When I say "break out the pins", I am simply saying either solder on some extra headers, or wires.

---
Tags: arduino-uno, gsm, gps
---


# Question
Title: How to attach interrupts to Arduino UNO timers?
I understand there are 3 timers on the Arduino UNO. What specific registers do I need to use to access them?

My goal is to use these timers to poll different sensors I am using with a ms period. Are there any pre-made libraries out there to do this?

# Answer
For the UNO, use Timer1.

An example of the way you can use it is as follows:

Download the TimerOne library: https://code.google.com/p/arduino-timerone/downloads/list

```
/*
 *  Timer1 library example
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}

```
> 2 votes

# Answer
Timer 0 is use'd by the arduino core libraries for functions like millis(). It is best left alone. Leaving timer1 and 3 are available for general use. Both 1 and 3 have well established libraries, for simple implementation, without the need to know the mechanics under the hood, about the registers and such.

You can find links and general explanations at timer1. I always recommend the github versions.

And if you are still wanting to know the details the source is quite readible.

---

Note you don't need 3 timers to read 3 sensors. One timer on a multiple of the the 3, should suffice which can then implement a statemachine to sample at the correct periods.
> 1 votes

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


title: RF missing characters

text:
# Question
Title: RF missing characters
I've got two arduino nano devices connected via RF 433 MHz. The modules are MX-05V and MX-FS-03V. I'm using VirtualWire for sending and receiving. The speed is set to 1000 bps.

One has got a pir sensor and sends "1:ON" when it detects movement and "1:OFF" when movement stops.

The other is just receiving these messages, but after a while (20 messages) the text is chopped off. I only receive "1". If I restart everything the same thing happens.

They are currently on my table (cca 20cm distance) and powered by my PC via USB.

What can I do? Is it because the modules are from ebay and probably not the best quality?

Receive part:

```
// recieve

int ledPin = 13;
int rcvPin = 13;

#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message

void setup() {
  Serial.begin(9600);
  Serial.println("Device is ready");

  // Initialize the IO and ISR
  vw_set_rx_pin(rcvPin); // set pin for rx
  vw_setup(1000); // Bits per sec
  vw_rx_start(); // Start the receiver

  digitalWrite(ledPin,HIGH);
}

void loop() {
  // non-blocking receive
  if (vw_get_message(message, &messageLength)) {
    Serial.print("Received: ");
    for (int i = 0; i < messageLength; i++)  {
      Serial.write(message[i]);
    }
    Serial.println();
    digitalWrite(ledPin, LOW);
    delay(500);
    digitalWrite(ledPin,HIGH);

  }
}

```

Transmit part:

```
/*
SimpleSend
This sketch transmits a short text message using the VirtualWire library
connect the Transmitter data pin to Arduino pin 12
pin 11 to high for power
gnd connected to gnd
*/

// RF
int ledPin = 13;
int trxPin = 12;
int pwrPin = 11;

// PIR
int inpPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status

#include <VirtualWire.h>

void setup()
{
  Serial.begin(9600);
  Serial.println("Starting...");

  // PIR
  pinMode(inpPin, INPUT);     // declare sensor as input
  // RF
  pinMode(pwrPin, OUTPUT);   // Set digital pin 11 as OUTPUT pins
  digitalWrite(pwrPin,HIGH);

  // Initialize the IO and ISR
  vw_set_tx_pin(trxPin);
  vw_setup(1000); // Bits per sec

  Serial.println("Device is ready to send.");
}

void loop() {

  val = digitalRead(inpPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion on seonsor 1!");
      send("1:ON");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH){
      // we have just turned of
      Serial.println("Motion ended on seonsor 1");
      send("1:OFF");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }

}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

```

# Answer
In your first sketch, you have

```
int ledPin = 13;
int rcvPin = 13;

```

Did you mean both those to be assigned to the hardware LED on the Nano? (Pin 13 is the on-board LED). If so, why? With all the pins available to you.

The other thing I don't understand is your use of:

```
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message

```

It will always just be one byte, won't it?

Why not use available()?

http://arduino.cc/en/Serial/available

I see this was posted six months ago - no doubt you have already solved it.
> 1 votes

---
Tags: programming, arduino-nano, rf
---


# Question
Title: how to make arduino as mind thought reader?
I'm trying to create arduino base mind reader... And for that I thought that EEG electrode connected to arduino and then the data send to arduino in 01 form .. But I facing problem in how to convert this or which wave (alpha, beta,delta)give very high or acutrate result.

# Answer
> 5 votes
Even if the answer provided by Mike is really doable and can be implemented you should really think about what you want to reach and what is your goal.

The big difference between EEG and mind readers is that the process of thinking, even if you can record all that waves: alpha, gamma,... can be never decoded to get useful informations. I mean: you can record and get a confirm that you have more gamma waves when you are doing meditation. Or that aplha and beta wave are going to be much more present when waking up or in particular hours of the days, but you never get an image of what the person is thinking or what are its emotions... That because you can get some waves coming from the brain but you cannot reconstruct the billion of processes that are happening *inside* the brain.

A lot of researcher are trying to decoder those informations to move as an example an arm or a leg. But it is the front edge of the reasearch really not doable with an Arduino....

Anyway good luck!

# Answer
> 3 votes
You could hack an existing device like the Mattel Mind Flex ($20-50 on Ebay).

There have been a number of projects that do exactly what you have described - there's even an arduino library: https://github.com/kitschpatrol/Brain

http://frontiernerds.com/brain-hack

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


# Question
Title: Can I use the setup() function inside the loop() function
In the normal case the setup() function will be run once automatically and and then the loop() function will run many times.

I want to initialize several modules in the setup() function and then in the loop() I want to read values from them periodically. But if the period between usage is long I want to power off the modules. After defined time the modules will be powered on again and need to be initialized. Can I use the already existing setup() function inside the loop() to initialize the modules or I have to write another similar function? Is there any other better way to power off/on sensors and modules during the execution of code.

# Answer
It could be possible, since it is going simply to call the same function **BUT** it is really a very bad design\*.

Usually the main purpose for a microcontroller is just sitting there and run a procedure or main function repeatedly until the end of the world. And during one loop just to check if some conditions are met.

You should never stop or influence your `loop()` function and never mess up the default design of the arduino.

In you case (but it depends on your code and your application), you just want to run the `loop()` once all sensors have been already started (in the `setup()` function).

In your run, you check periodically the sensor and start a timer (better if interrupted). If an amount of time has expired and the sensor should be turned off, then the timer will call another function, which has the only target to switch sensors off.

The `loop()` runs again and again and if the original condition is met, then you can start your sensors again.

To save up time and code typing, I suggest you write only ONE function for switching on the sensors and call this function in `setup()` and in your `loop()`, something like this:

```
void startSensors();
void stopSensors();

void setup() {
  startSensors();  // I start all sensors here
}

void loop() {
  if( condition?!?! )
     {
       ...
       stopSensors();
       ...
     } else {
       ...
       startSensors();  // I call the same function here
       ...
     }
}

```

\*: for istance you define in your `setup()` the connection through serial port. This means that your object "serial port" is going to be recreated each time you call `setup()` whit undefeined behavior in case it is outputting datas or has same data in the FIFO Buffer. Simply...`setup()` has that name because needs to setup things once. Everything that must be done more than once, then must be called from `run()` too.
> 12 votes

---
Tags: system-design
---


# Question
Title: Discrete H-Bridge very low current output
I have built two parallel H-bridges from "Design 1" on this page as you can see in the attached schematic.

However when I apply the external power (VCC1 in the center of the diagram) the two motors do not spin.

Using my multimeter, I can see that the entire circuit is working: the motor is getting a 'forward' and 'backward' current as the Arduino sets the pins high. The multimeter is reading +/- 5.54V with the motor replaced by the multimeter. (Across the motor this drops to 0.13V)

So then I measure the current by putting my multimeter both in series with the motors and replacing the motors. There's only 40mA available! Looking around the web I found the suggestion to reduce the 220Ω resistors at R2, R3, R5 and R6. So I switched in (randomly) 27Ω resistors and the output current is still only 40mA.

What else should I try to bring up the current enough to drive the motors?

**Edit:** So my uneducated guess is that it's likely that the limitation is coming from the transistors. The Ns are BC549 and the Ps are BC559. The datasheets list "low current" as a feature, but I figured that was the collector.

**Edit 2:** The motor is this one which requires 70mA when running (and presumably more during startup)

**Edit 3:** Code driving the Arduino:

```
// Pin setup
int pinLeftMotorFwd   = 5;
int pinLeftMotorBck   = 6;
int pinRightMotorFwd  = 10;
int pinRightMotorBck  = 11;

// Directions for the {left, right} motors to achieve the four directions
int FORWARD[]   = {  1,  1 };
int BACKWARD[]  = { -1, -1 };
int RIGHT[]     = { -1,  1 };
int LEFT[]      = {  1, -1 };

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

    pinMode(pinLeftMotorFwd,  OUTPUT);
    pinMode(pinLeftMotorBck,  OUTPUT);
    pinMode(pinRightMotorFwd, OUTPUT);
    pinMode(pinRightMotorBck, OUTPUT);
}

void loop() {
    go( FORWARD, 10 );
    go( RIGHT,    3 );
    go( FORWARD, 10 );
    go( LEFT,     6 );
}

// Move the bot in a particular direction from the array above for a given number of seconds
void go ( int dir[], int dur ){
    leftMotor(  dir[0] );
    rightMotor( dir[1] );
    delay( dur * 1000 );
}

// Sill both motors (OK, so stop both motors. But stop is a keyword in C)
void still(){
    leftMotor(  0 );
    rightMotor( 0 );
}

// Set the left motor to Backward (-1), Forward (1), or Stop (0)
void leftMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinLeftMotorFwd, LOW );
    Serial.println("pinLeftMotorFwd LOW");
    digitalWrite(pinLeftMotorBck, LOW );
    Serial.println("pinLeftMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinLeftMotorFwd, HIGH);
        Serial.println("pinLeftMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinLeftMotorBck, HIGH);
        Serial.println("pinLeftMotorBck HIGH");
    }
}

// Set the right motor to Backward (-1), Forward (1), or Stop (0)
void rightMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinRightMotorFwd, LOW );
    Serial.println("pinRightMotorFwd LOW");
    digitalWrite(pinRightMotorBck, LOW );
    Serial.println("pinRightMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinRightMotorFwd, HIGH);
        Serial.println("pinRightMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinRightMotorBck, HIGH);
        Serial.println("pinRightMotorBck HIGH");
    }
}

```

# Answer
Design 1 wouldn't be my first thought on how to do this either! The transistors aren't a great choice, but are cheap & common.

The layout here is more conventional, and you can physically link 1-2, & 3-4 to connect to your arduino without the risk of short circuits.

I suspect your code may be setting both lines high together - the only advantage I can see to the posted circuit is that this does not necessarily cause smoke (but may well do as you describe). This is why posting the code is recommended!
> 1 votes

---
Tags: motor, current
---


# Question
Title: Compilation error when trying to give pointer to a function to another function
I'm trying to write a library for Arduino using the Wire library. Here's my code:

PiCom.h:

```
#ifndef PiCom_h
#define PiCom_h

#include "Arduino.h"
#include <Wire.h>
class PiCom
{
public:
    PiCom(int address, int* integers[], double* doubles[]);
    static void onReceiveCallback(int numbytes);
    static void onRequestCallback();
private:
    //Actually arrays of pointers to the data to be sent, has to be declared that way cause the size of the array isn't known at compile time
    int** _integers;
    double** _doubles;

    void onReceive(int numbytes);
    void onRequest();

    static PiCom instance;
};

#endif

```

PiCom.cpp:

```
#include "Arduino.h"
#include "PiCom.h"

static void onReceiveCallback(int numbytes)
{

}

PiCom::PiCom(int address, int* integers[], double* doubles[])
{
    _integers = integers;
    _doubles = doubles;

    Wire.begin(address);
    void (*receiveFunction) (int);
    receiveFunction = &PiCom::onReceiveCallback;
    Wire.onReceive(receiveFunction);//Here i get an error
}

```

I want the constructor to be created when a new instance is created. A mehtod in this object should be called when data is requested or received. When trying to pass onRequest(int) directly to Wire.onRequest(void (\*) (int)) an error is thrown. Same happend when saving it to receiveFunction.

This problem was solved by using a static function (onReceiveCallback(int). I wanted this static function to call onRequest(int) in the object saved into PiCom::instance.

But now i'm getting another error:

```
PiCom\PiCom.cpp.o: In function `PiCom':
C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'
C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'

```

# Answer
Pointer to a member function is a painful corner of C++ until C++11. This is why when you try to pass an instance method pointer to `Wire.onReceive` (without the `static` keyword), you will get an error similar to:

```
error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say '&PiCom::onReceiveCallback'

```

Well, you can't argue with the C++ ISO standard... changing the function to a static one (with external linkage, as they say) is indeed a workaround, as you have found out. For this workaround to compile properly you just need to omit the `static` keyword from your **definition** (where it is implemented), and leave your **declaration** (in the header file) as is:

PiCom.h:

```
...
static void onReceiveCallback(int numbytes);
...

```

PiCom.cpp:

```
void PiCom::onReceiveCallback(int numbytes)
{
    ...
}

```

By doing this you can pass it to Wire.onReceive without any problem, from the PiCom constructor, as follows:

```
PiCom::PiCom(int address, int* integers[], double* doubles[])
{
    ...
    Wire.onReceive(&PiCom::onReceiveCallback);
    ...
}

```
> 1 votes

---
Tags: library, wire-library
---


# Question
Title: Wiring 5V ultrasonic sensor to Arduino Due
Is it possible to use the 2760342 ultrasonic range sensor with an Arduino Due? The docs say it takes a 5V input, but doesn't specify the output, but I'm assuming it also outputs a 5V signal. Does this make it incompatible with the Due?

I've tested it with an Uno, it it works flawlessly. I've been researching using a Due and some other ARM based single-board computers, but they all seem to use 3.3V, while almost all Arduino shields and sensors use 5V. I'm hesitant to "upgrade" to these boards if I have to purchase an entire new set of shields and sensors. And I have no interest in hacking in some clunky custom voltage level shifter. Why isn't everything standardized on 5V?

# Answer
Is this too clunky?

https://www.adafruit.com/products/735

Breadboard Friendly 8-bit Logic Level Shifter, $1.50.
> 1 votes

# Answer
If your question is "Why isn't everything standardized on 5v?", see this good SO answer: https://electronics.stackexchange.com/questions/135841/voltage-standards-like-3-3v-5v-etc

Bottom line is that the voltage drops as the electronics' technology advances (12v to 5v to 3.3v).

Concretely to your problem, I honestly do not think that a level shifter is somewhat "clunky" solution to your problem, as suggested by mikeY (and as rejected by you). This is the way things are done in the electronics world - when a hardware mismatch arises, there is a hardware adapter to rescue.
> 0 votes

---
Tags: sensors, shields, arduino-due, voltage-level
---


title: Serial debug output looking messy

text:
# Question
Title: Serial debug output looking messy
I've got this quite basic code running on an Arduino Mega 2560, and the output is looking like I have the serial settings wrong, though I can't work out what to change.

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

void loop()
{
  Serial.println("test" + millis());
}

```

The output looks like this:

```
ð¦·Z©÷
×ï¾üÿ7ß^|ïüûÿVÏuØëo~ìÿÓûzëýÿ{ßþ©×xñ×¤¿ïßûÏûýoÏ¿îãõI
õfwi÷`p¬½Ïª»QáÀª»¦·ð¦·Z©÷
test123
D

4ñjü¯÷~µÞMz¹Ý~¼
Ûþ}iû}ÒÖ¦Ç¿÷ÿÂï½Õ¾;îö

```

I'm using the inbuilt "Serial Monitor" in the Arduino suite with settings 9600 baud and no line endings.

I see that the first println in `setup()` is sending the data as expected but all other comms are coming through as nonsense.

Any suggestions of what to do?

# Answer
> 8 votes
This is unfortunately not valid in C++:

```
"test" + millis()

```

Rather than concatenating two strings, it's actually doing pointer arithmetic. It's taking the memory address where `"test"` is stored, and offsetting by the value retrieved from `millis()`. The result is a totally arbitrary memory location which gets treated like a string.

Generally speaking, it's arguably best to avoid string concatenation on Arduino anyway unless absolutely necessary. The reason is that it can use more memory than you might expect.

A simpler approach would simply be to do the serial output as a sequence of individual operations, e.g.:

```
Serial.print( "test" );
Serial.println( millis() );

```

Note the difference between `print()` and `println()`. The first one doesn't add a line break at the end, but the second one does.

# Answer
> 2 votes
Just as a minor addition to Peter's excellent answer and comments on concatenation and implicit typecasting with `String` objects:

Alternatives to construct the message (as a `char[]`) to be send might be:

1. use `sprintf()`

```
char buffer[80];  // for the complete output
char value[4];    // for millis(), which returns an unsigned long

sprintf(buffer, "I'm running for %u ms now", millis());
Serial.println(buffer);

```

*Note that `sprintf()` uses quite some memory!*

2. build the message 'manually':

```
 char buffer[80] = "I'm running for ";

 itoa(millis(), value, 10);
 strcat(buffer, value);
 strcat(buffer, " ms");
 Serial.println(buffer);

```

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


# Question
Title: Read temperature (DS18B20) with the ATTiny85
I'm trying to read the temperature of a DS18B20 with my ATTiny85 - but I'm getting rubbish data :D

I should have gotten ~22 degrees, but I'm getting 129! I followed this tutorial i found here, but maybe there is something funky with the ATTiny85?

# Answer
I would suggest it has to be the clock speed or memory. Whilst you can program the ATTiny85 with the Arduino IDE, it will take up quite a lot of its flash memory. There is a thread on the Arduino form here which might help pinpointing the issue.

One solution is to write it in AVR-C but I don't know if there is an easy way (or a library) for the 1-wire. I think you'll have to do it with the 1-Wire library alone as the DallasTemperature library is too much for the 8Kb of memory you have to play with.

Please feedback any breakthroughs you make as this is a nice project, the ATTiny is an awesome little chip...
> -1 votes

---
Tags: sensors, attiny, temperature-sensor
---


title: Data Report Which Technology

text:
# Question
Title: Data Report Which Technology
I want to create a small position reporter for cars. I found some good GPS Modules with which i could collect data. But i'm unsure with what technology i should send the data.

A possibility would be to setup a service in the www which is feeded by the arduinos.

I want to track the data live. so i think GPRS should be the right choice ? Or more better are there any shields which make this GPRS LOG and SEND as a package ?

Which GPRS hardware would you use ? Would you use something else?

Any hints are very welcome

# Answer
You can actually find all the information for what you want to do on the formal Arduino.cc website. They suggest a GSM shield:

But of course you can find many other GSM shields for purchase. Most of them works the same. Arduino.cc also offer a nice GSM Library, with which you can perform HTTP GET/POST queries to a remote webserver (visible over the web).

You can select whatever web server technology you prefer for receiving the data. Using NodeJS, PHP, MVC.NET or any other, you could expose a REST API to perform the update from the Arduino+GSM Shield side using HTTP.

The web server then could analyze the incoming data and display it in any way you like.
> 3 votes

---
Tags: gps
---


title: Individually control ~200 LEDs

text:
# Question
Title: Individually control ~200 LEDs
I am planning to build a LED polar clock, so it will need about 181 LEDs (12 Month, 31 Day, 7 Day-of-week, 12 Hour, 60 Minute, 59 Second) and I need to control each one individually. I will be buying everything from scratch so I ask for help on:

* Which arduino to use
* How to make it keep time
* How to control the LEDs

The LEDs need to stay on once they're lit, e.g. at 5 o'clock, the 1-5 LEDs would be on. This is why I don't know that multiplexing or charlieplexing will work, as I read that it is better if the LEDs wont be remaining on/only a few are on. The most that could be on is 179 (Friday, December 31, 11:59:59 \[Won't happen until 2021\]).

Thanks in advance.

# Answer
> 3 votes
Instead of a multiplexer you can use a "shift register"; the difference is that it keep the last state of the pin, while the multiplexer goes unconnected (and this is because you need at least 30fps, and even so you'll get low light as you are PWMing the leds). This is why shift register are also called "led driver".

Official tutorial can be found here http://arduino.cc/en/Tutorial/LEDDriver

# Answer
> 1 votes
Check out the TLC5916. It has two advantages over the HC595:

* it can sink a lot of current
* it only needs one resistor

I use it with seven-segment displays. Basically, you tell it "I'm about to send a command." Then you send it, say, "01010101" to turn on every other light. Then you say "okay, make that live." You can chain them together.

Many use the MAX7219 but for me the cost is a drawback.

I might come back and edit this post later to add a Github link to demonstrate...

# Answer
> 1 votes
If the cost is allowed to be moderately higher, your simplest solution could be to use WS2012b individually-addressable LEDs. Since longer chains sometimes have timing problems with the serial communication, I’d probably split them into three groups, attached to three digital pins.

Multiplexing probably requires some flip-flops or other buffers; else, the LEDs may not be bright enough.

# Answer
> 0 votes
Multiplexing will work fine in this case (Charlieplexing isn't practical here).

You create an array of leds, and light up only one row at a time. If you rotate through all the rows at more than 50 times a second your eyes won't notice it.

In the case of 181 leds, you'd need and array of e.g. 13x14. This will mean you need a minimum of 27 IO-pins. More than the regular Arduinos provide.

So you probably need some additional ICs. You could use simple shift registers, or dedicated led-matrix drivers like the max7219 or some other IC. The Max7219 is probably the easiest, as you don't have to do the multiplexing yourself. The can light upto 64 leds (8x8), so you'd need 3 of them.

PS I get a different number though; 12 (month) + 31 (day) + 7 (weekday) + 23 (hours) + 59 (min) + 59 (sec)= 191

---
Tags: led, time
---


title: Choosing right Sleep state

text:
# Question
Title: Choosing right Sleep state
I'm planning on building an LED clock, but I want it to be lit only when I press the POWER button on my remote control. Using an IR receiver, which Arduino sleep mode should I use to reduce the current consumption but still be able to receive this interrupt?

# Answer
> 0 votes
I recommend reading ArduinoSleepCode. Where it demonstrates placing the avr into a sleep state and using an interrupt to awake from the sleep state. In your case you can connect the output of your IR demodulator to the interrupt pin, to simular awake.

Ken Shirriff's IR library allows you to use any pin as a receive input, so that you can use INT0 or 1 on D2 or D3. If you need to use a different pin, the Microtheron's github fork uses Pin Change interrupts. (I am not sure if stock sleep.h will awake from PCint, like int0 or 1 will, without tweek. Section 10.1 of data sheet says it will.)

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


title: Serial interrupts?

text:
# Question
Title: Serial interrupts?
In a project, I’m using an EIA485 bus to send encrypted data packets. That works with Arduino’s buffered serial, but it is kind of awkward, and I’m using none of the more complex stuff in that class anyway.

If I do not use `Serial` anywhere in my Arduino sketch, is it safe to create my own interrupt handlers for `USART_RXC` etc. and to directly manipulate the USART registers?

# Answer
Absolutely. The only interrupt that Arduino takes for itself unilaterally is the timer 0 overflow interrupt, used for timing purposes (`delay()`, `milliseconds()`, et alia).
> 1 votes

---
Tags: serial, interrupt
---


# Question
Title: Is it possible to use ESP8266 modules interchangeably?
I discovered that there are multiple types & versions of `ESP8266` modules.

I'm wondering:

* Build my application around one type (eg ESP-03) and in future swap the module with another (ESP-07), continuing to use the same library and code?

Given the lack of information online, I couldn't find an answer for this online.

# Answer
> 4 votes
yes they are interchangeable since they all use the same chip (esp 8266). However the pin outs of the different modules can (and will be) laid out different. So you have to watch out that your wires are connected to the correct pads on the module.

Also mind that different esp8266 modules can be (stock) loaded with different firmware. If you are using the AT firmware in your current arduino project it can be necessary to flash your new esp8266 module with the same firmware. If you are not sure how to do this you might have a look to the esp8266 forum

# Answer
> 2 votes
Well...
Yes, but... **mostly** only if you are using the simple serial lines(rx and tx) to communicate with it and only using the AT flash image.

Just as a for-instance:
The ESP8266-01 and ESP8266-02 have three and two IO pins (respectively) that are reprogrammable.
The ESP8266-03 has seven IO pins.
The others have different amounts of pins found on this page:
http://hackerspace.pbworks.com/w/page/88183850/ESP8266

So if the program you use to flash the module uses more pins then you have to use the module that has the proper amount of IO pins or rewrite the flash image.

Instructions for compiling a toolchain to write and flash your own flash images to the ESP8266-XX module are found on this page:
https://github.com/esp8266/esp8266-wiki/wiki/Hardware\_versions

---
Tags: wifi, esp8266, networking
---


# Question
Title: What's the smallest Arduino board with wifi capabilities?
The Photon from Spark IO looks super small. Are there smaller wifi enabled microcontrollers available that can be programmed with the Arduino IDE?

# Answer
From your question it implies that *the Spark IO use the Arduino IDE - **it's not**.* It has two different IDE's, one is web based and the other is downloadable. In addition, it's not an Arduino per-se. It is based on the Wiring library, which is similar to the Arduino library but not exactly the same. And of course the MCU is not Atmel, but that is also the case with Intel's Galileo board.

As to the size question in hand - my believe is that the Arduino products are designed for prototyping, so the size of the product is less important. This is the case for several reasons:

* **Costs** \- the different Arduino products are pretty expensive for mass production.
* **Peripherals** \- the Arduino boards come with different peripherals (such as the FTDI chip) which will probably be omitted in an end-user product, and which makes its size larger.
* **Pins** \- almost every (official?) Arduino product comes with pre-built male/female header pins, which are excellent for prototyping but not for production, because of the large vertical space they take.

There are many more reasons, but you get the point.

When moving to production with an Internet of Things product, it makes sense to fabricate your own PCB, and design it with a small Atmel chip you used for prototyping (such as ATtiny85) and small Wifi chip, such as the ESP8266. This is an example for such fabricated PCB, although the size is not the 'smallest' possible.

However, for beginners, or a one-time project, it would absolutely make sense to use a pre-fabricated Arduino product, in a small scale that could provide both easy coding capabilities, various libraries and a WiFi included. For that purpose, the Spark IO seems to be at the bleeding edge at the moment - but you never know what will be there tomorrow...
> 5 votes

---
Tags: wifi
---


# Question
Title: Can the Sparkfun AVR pocket programmer bootload/program a 3.3 V ATmega328p
The product in question - https://www.sparkfun.com/products/9825 \- operating at 5 V (and can also supply it to the device being programmed).

I need to program the bootloader onto a 3.3 V ATmega328p and don't have any level shifters immediately available. Thus the question. The "Hookup Guide" for the product (https://learn.sparkfun.com/tutorials/pocket-avr-programmer-hookup-guide) seems to suggest that it will work fine as long as the 3.3 V device being programmed isn't powered by the programmer. I wouldn't have thought it's the best idea in the world, but maybe I'm wrong.

So any practical experience?

Are the over voltage tolerances for input lines on Atmel devices good enough to handle the extra voltage?

I guess the output level from the device being programmed would be high enough to be buffered up to 5.0 V?

# Answer
With that combination of programmer and Arduino you have two possible options:

* Cut JP1 on the programmer and power the programmer from the Arduino. With this you will have to make sure that the Arduino is connected and powered up before you connect the programmer to USB.
* Cut SJ1 on the Arduino and allow it to be powered by the programmer at 5V. The Arduino itself isn't *required* to be powered at 3.3V, that's simply what the on-board regulator provides, so we cut SJ1 in order to isolate the regulator from the MCU. Note that any devices connected to the Arduino will need to support 5V operation in order to this to be safe.

It is not safe to put 5V at the output of the regulator, so you must make sure that does not happen.
> 1 votes

# Answer
The Pocket AVR Programmer has a logic level shifting (74ACT125) on board, specifically for this situation. There is nothing wrong with powering the target with a separate power supply that the programmer. Why else would there be a "power target"/"No power" switch?

I don't see why other people would suggest cutting traces, when all you need to do is toggle a switch.
> 1 votes

# Answer
ATmega328p Operating Voltage is 1.8v-5.5v, as stated in the second page of the datasheet (PDF):

So there should be no problem feeding it with a regulated 5v VCC while programming it, and then supplying it with 3.3v on normal use. Just make sure you do not leave any 3.3v devices (which are not 5v tolerant) connected to the ATmega328p during the programming of the chip.

Regarding the Sparkfun's Pro Mini 328 3.3v/8Mhz, you can read in the comments section of the Pro Mini page that customers successfully managed to power it with 5v without any issue. You can see from the schematics that the voltage regulator in use (MIC5205) has a max input voltage of 20v, so 5v should not pose a problem to power it up.

**EDIT**: See Ignacio's answer. My answer apply for **powering up** the Pro Mini **not for programming it with 5v signals and 3.3v VCC**. The **SJ1** jumper will need to be removed in order for the MIC5205 regulator to supply 5v instead of 3.3v.
> 0 votes

---
Tags: bootloader, uploading
---