# Question
Title: Arduino motor shield will only work in one direction
I have this Arduino motor shield which is hooked up with two DC motors. The board is the same as this one from Sparkfun.

A PWM output controls the speed of the motor, and a digital out controls the direction. The problem is that it only works in one direction, namely if the direction pin is high.

With the direction pin HIGH and 255 is written to the PWM pin, Vout on the terminals is similar to Vin. If I reverse the direction by setting the direction pin LOW I would expect Vout to be -Vin, ie. the polarity reversed. But not so. I get a little more than zero volt across the terminals.

It's the same for both channels.

**Edit: The setup is powered from a 9V power adaptor through the barrel jack on Arduino.**

Is the board defective, or am I misunderstanding something?

SOLUTION: Thanks to the edited post (especially #3) in the accepted answer, I not only looked at the schematic (again), I actually understood it. I had already noticed the jumper called V-LOGIC which on the picture from Sparkfun was set to 5V where it on my shield was not set. I really didn't know what it was used for, but I set it to 5V so it was the same. But by looking at the schematic and the inverters, I realized that the inverter was fed from V-LOGIC which was connected to 5V. And bingo: I had not connected the 5V pin on the shield, only vIN which I assumed would be sufficient. The thing is, I am awaiting a set of stackable headers instead of the ones supplied, so I only connected the minimum numbers of pins because I will need to desolder them when I get the new headers.

# Answer
I think you may be having an issue with how you are powering the shield. Are you trying to do it with just your USB connection?

In your photo, I do not see a connection to your Arduino's barrel jack or to the Vin connector of the shield itself. According to the SparkFun site:

> The Ardumoto Shield should be powered through one of two power supply inputs. Pick one or the other:
>
> 1. The **barrel jack** input on the Arduino.
> 2. The **Vin input** on the shield
>
> If you don’t want to use the Arduino’s barrel jack input, you can use the **Vin input on the shield** instead. This voltage input will supply **both the shield and the Arduino**. Like the motor outputs, this connection is broken out to both a 3.5mm screw terminal and a 0.1"-pitch header.
>
> Do not supply power to both the Arduino barrel jack input and Vin on the shield!

I hope this helps!

**EDIT BASED ON COMMENTS**
Since you are properly powering the shield, I would recommend the following (see the shield's schematic for specifics):

1. Maintaining the connection shown above (with the addition of the 9V power supply connected to the barrel jack) ensure that you are able to properly set the DIRA input. You can check this with a multimeter on pin 7 of the LN298 whenever you are trying to switch directions.
2. If you are getting the expected results on pin 7 (pin goes HI when your code wants the motor to go one direction and pin goes LOW for the other) - check pin 9... the value here should always be the opposite of what you are setting for DIRA on pin 7. If that is all good, then you probably have an issue with the LN298.
3. If you are not getting the expected results at pin 9, but pin 7 looks good, then you are having a problem with the 74HC1G04 IC (although I would doubt this since you are having problems with both the A and B motor outputs).
4. If you are not getting the expected results at pin 7, then double check the code to make sure you have set and cleared the correct output pin. I would also check the solder joints of the connectors on the shield - you can set a multimeter to do a resistance check from the shield's connector (pin 12) to the direction input on the LN298 (pin 7). If the continuity is measuring close to 0 ohms then there is probably an issue with your code.
5. If your code looks good, I have also had issues with bad outputs on the Arduino - you can check to see if you are properly toggling the direction pin (pin 12) on the Arduino without the shield connected. Then, if the pin is not toggling, there is probably an issue with your Arduino - try toggling a different (unused) pin and jumpering it.
> 2 votes

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


# Question
Title: Use website to communicate with Arduino WirelessProtoShield
I have a small office with wireless network, is it possible to make a wireless doorbell?
Practical example:
Arduino is connected to the main wireless network and has a static ip, i have a website that connects through arduino using ftp to activate the "open door" function.
note: "open door" activates a motor to press the button, or i will hack the current doorbell to connect wires :D

# Answer
> 0 votes
Arduino wifi web server: http://arduino.cc/en/Tutorial/WiFiWebServer just modify the webserver to show a "open" button and to receive a post request and open the door.

---
Tags: programming
---


title: Cannot retrieve data from homemade ECG

text:
# Question
Title: Cannot retrieve data from homemade ECG
For the past couple of weeks, I have not been able to find a solution to my problem. My problem is that I cannot retrieve the data from my homemade ECG that I created from Arduino. I am a total amateur at this, but I'm pretty sure it's a circuitry issue. Here is what my circuit looks like now. (Note: the thing that says 'Dual O' on the far left is the instrumentation amplifier, not an operational amplifier like the one near the middle)

Here is the code I'm using:

```
const int  signal = 5;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

void setup() {
pinMode(signal, INPUT);
Serial.begin(9600);

previousBeatTime = millis();
}

void loop() {
delay(500);
input = digitalRead(signal);

if ((input != lastinput) && (input == HIGH)) {
    // If the pin state has just changed from low to high (edge detector)
    currentBeatTime = millis();

    period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
    previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
}

lastinput = input; // Save the current pin state for comparison at the next loop iteration

// Detect if there is no beat after more than 2 seconds
if ( (millis() - previousBeatTime) > 2000 )
{
    Serial.println("dead");
}
else
{
    if (period <= 0)
    {
        frequency = 0;
    }
    else
    {
        frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
    }

    Serial.print(frequency);
    Serial.println(" : alive! ");
}
}

```

I would appreciate if someone could get back to me as soon as possible. Thank you!

EDIT: Here's a schematic. I used Fritzing, and since I am a total beginner at this, it looks like a complete mess. Anyways, here it is:

Thank you for your help.

# Answer
> 2 votes
Has any part of it ever worked? What have you done to it since? My approach to debugging this would be to \- Temorarily replace the Bluetooth with wired serial communication; \- Comment out, or stub out(\*), anything you aren't utterly and completely confident in. \- Get some minimum amount of hardware and software working. \- Add back one piece of hardware or one section of code at a time, fixing whatever you have to to get it working again. \- Repeat, until everything is back together and playing nicely.

(\*) Stubbing is the technique of replacing a function or a section of code with something trivial (and therefore hard to get it wrong!) that lets the rest of the code mostly work.
Suppose you had written a digitalRead() function. (I know it's a library function and we have total confidence in it, but for a moment, just suppose....) You might replace the contents of your digitalRead() with a single statement:

```
int digitalRead(uint8_t pin){
   // untested code commented out here
   // ...
   return(4);  // any value that means something to the calling code
}

```

Now you can work on the code that calls your digitalRead() without having a working digitalRead(). The caller will only ever get the same value every time it calls, but that may be enough get some part of it working until you can come back and fix your digitalRead() function.

---
Tags: arduino-uno, bluetooth
---


title: Using an Arduino as an input device

text:
# Question
Title: Using an Arduino as an input device
I had an idea to create a control panel using an arduino and some buttons. How would I go about making the arduino emulate an input device so that when I press a button connected to the arduino, it would cause the same effect as when a keyboard key was pressed? (I'm using arduino UNO, if it helps.)

Thanks in advance.

# Answer
The easy answer is to use a Leonardo, Micro, or Due instead. They already support USB HID functionality via `Mouse` and `Keyboard`.

If you insist on using an Uno **R3** then you will need to reprogram the on-board ATmega16U2 to accept serial commands from the ATmega328P and generate the appropriate USB HID events.

If you're using an Uno or clone that doesn't have an ATmega16U2 as well then you're SOL and will have to write a program that runs on the computer that receives the commands via serial and translates them into HID events.
> 1 votes

# Answer
I have successfully reprogrammed the UNO's R3 8U2 to support keyboard emulation, as to just this. Making dedicated user inputs for kiosks to Computers. I recommend NicoHood's GitHub as it allows simultaneous Arduino Bootloader and Keyboard functionality, making it easy to reprogram the Arduino.

This along with using Capacitive Touch Sensor connected to Copper tap under clear acrylic protecting printed graphics of buttons is very quick and easy to make. Very little machining.

Example of such code is found at artemis-firmwares it was initially created with a different 8U2 method. Where next time we will use NicoHood's.

Note the stock keyboard send key command for the Arduino is limited. Where the above methods allows the code to send complete virtual keys supporting full emulation.
> 2 votes

---
Tags: arduino-uno, emulation
---


title: DS1307 RTC conflicts with DS18B20

text:
# Question
Title: DS1307 RTC conflicts with DS18B20
I'm working on a project to output the temperature from a DS18B20 to a 16x2 LCD while logging the temperature to a CSV file using the Adafruit Data Logging Shield. I keep getting this error when verifying the code:

```
RTClib-master/RTClib.cpp.o: In function `RTC_DS1307::now()':
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:252: undefined reference to 'Wire'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:252: undefined reference to 'Wire'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:252: undefined reference to
'TwoWire::beginTransmission(int)'RTClib-master/RTClib.cpp.o: In function 'TwoWire::write(int)':
/Applications/Arduino.app/Contents/Resources/Java/libraries/Wire/Wire.h:72: undefined reference to 'TwoWire::write(unsigned char)'
RTClib-master/RTClib.cpp.o: In function 'RTC_DS1307::now()':
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:254: undefined reference to 'TwoWire::endTransmission()'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:256: undefined reference to 'TwoWire::requestFrom(int, int)'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:257: undefined reference to 'TwoWire::read()'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:258: undefined reference to 'TwoWire::read()'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:259: undefined reference to 'TwoWire::read()'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:260: undefined reference to 'TwoWire::read()'
/Users/g/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:261: undefined reference to 'TwoWire::read()' RTClib-master/RTClib.cpp.o:/Users/grafton/Documents/Arduino/libraries/RTClib-master/RTClib.cpp:262: more undefined references to 'TwoWire::read()' follow

```

When I comment `RTC_DS1307 RTC;` in the code (below) these errors go away, but of course I get errors related to an undefined RTC. I'm a newbie cobbling together code from various sources, so any help is greatly appreciated. Code follows:

```
#include <LiquidCrystal.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
#include <SD.h>
#include "RTClib.h"

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
const int chipSelect = 10;
File tempLog;
RTC_DS1307 RTC;

LiquidCrystal lcd(6, 7, 8, 9, 11, 12);

void setup() {
  Serial.begin(9600);
   while (!Serial) {
    ;
  lcd.begin(16, 2);
  //         ----------------
  lcd.print("Current temp (F)");
   sensors.begin();
   }

Serial.print("Initializing SD card...");
  pinMode(SS, OUTPUT);

  if (!SD.begin(chipSelect)) {
    Serial.println("Initialization failed!");
    while (1);
  }
  Serial.println("Initialization done.");

tempLog = SD.open("templog.txt", FILE_WRITE);
if (! tempLog) {
  Serial.println("Error opening templog.txt");
  while(1);
}
char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i/10 + '0';
    filename[7] = i%10 + '0';
    if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      tempLog = SD.open(filename, FILE_WRITE);
      break;  // leave the loop!
    }

  Serial.print("Writing to: ");
  Serial.println(filename);
  tempLog.println("Data Logging File");
  tempLog.println("Date,Temp(F)");
  }
}

void loop() {
  sensors.requestTemperatures();
  float temperature = sensors.getTempFByIndex(0);
  lcd.setCursor(6, 1);
  lcd.print(temperature);
  Serial.println(temperature);
  //-----------------------------------------------------------

String dataString = "";

//date time stuff-------------------------------------------

DateTime now = RTC.now();
  // log time
// tempLog.print(now.unixtime()); // seconds since 1/1/1970
//  tempLog.print(", ");
  tempLog.print('"');
  tempLog.print(now.year(), DEC);
  tempLog.print("/");
  tempLog.print(now.month(), DEC);
  tempLog.print("/");
  tempLog.print(now.day(), DEC);
  tempLog.print(" ");
  tempLog.print(now.hour(), DEC);
  tempLog.print(":");
  tempLog.print(now.minute(), DEC);
  tempLog.print(":");
  tempLog.print(now.second(), DEC);
  tempLog.print('"');

  tempLog.print(",");
  tempLog.print(temperature);
  tempLog.print(",");
  delay(500);

tempLog.println(dataString);
tempLog.flush();

}

```

# Answer
The RTC library requires the `Wire` library. Just put `#include <Wire.h>` in front of the line `#include "RTClib.h"`
> 1 votes

---
Tags: shields, lcd, sd-card, temperature-sensor
---


# Question
Title: Which arduino should I start on to learn about it?
I'm pretty interested in arduino and the things I can learn from it. Being that I'm new into this I wanted to know which model I should get that would be easiest to learn on and why. What does this model come with, how much, and reputable place where one can purchase this.

# Answer
I would simply say: buy a startkit like this one.At the end it is not important which Arduino board you'll start. They are (almost) the same\*. At the very beginning you can start with Uno or Nano and even Leonardo could be very good. Those boards are very similar and you can program them in the same. Even the pins location and designation is not really different. The most important thing about Arduino is to understand how to work and program and interface such a board with the sensors. In this sense I would choose a Uno board (or even 2009) which is less expensive and very easy to find overall. I don't really know how much experience you have, but it is likely, at the beginning, that you invert polarities of batteries, you drain too much power, or you invert some pins and damage the microcontroller. In that case doesn't make sense to buy the last powerful mega expensive board on the mark. If you get a Uno you can do almost everything and have for the next month a lot to learn.

To change from Uno or Nano to the other board it is not very difficult. Once you understand the basis you can switch to every board you want. If you need more power and memory you can buy a Mega. If you need much more power you can buy a Due/Tre/etc...you need just an *upgrade* not everything from scratch to learn.

If you are really new to Arduino the best way is to buy such a learn package as I showed you above. That have everything you need to understand basic of programming till to RC-Servo movement and motor drivers.

Happy new year.

\*: stay away for the moment from the Arduino Due/Tre/Zero/Yuan/.. series. they are too expansive and require a lot of attention (3.3V, max drain current from the pins, pull up, pull down...etc..). Here is the risk to get your board damaged within few time very high. And you'll spend a lot of time thinking that the board has some problems.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Speeding up Girino gives strange readouts
I was reproducing the Girino (the Instructable by Caffeinomane) bundled with the Girinoscope (the Java GUI by Chatanga). The results worked well and I went on to see if the oscilloscope can go up to higher kS/s.

In short, originally only upto prescaler 8 works. I removed PWM pin and it works upto 4 but prescaler 2 strangely behaves. Here are the details:

I did a preliminary test on prescaler 32 (~38.5kHz). Settings as follows and the same in other tests.

* The signal (the same hereafter) is generated by a 555 timer astable multivibrator running at 4.5V (3 AA batteries).
* The circuitry was simply omitted. I just tied 3.3V of Arduino NANO / ATmega328 to digital pin 6 as the trigger level.
* There is no +2.5V offset done by the original Girino. (The scale should be 0~5V and the signal is 0~4V)

So then I wanted to try if it can speed up more. The code optimization quoted by Chatanga allowed prescaler 8 and 16 (76.9kHz and 151.8 kHz).

In order to push it the poor Arduino to the limits, I disabled PWM pin in the original Girino which sets the trigger level with duty cycles (PWM from pin ~3 being fed into pin 6). It's because I simply used a fixed 3.3V trigger level.

Prescaler 4 is unlocked.

Ambitious I go on to test prescaler 2. The GUI did not provide this option so I simply set it in the Arduino code.

I thought it did not work. I noticed if the prescaler is exceeding the Arduino's capability, TXRX simply does not blink. But this time the TXRX is just blinking! To verify this, I shifted the wait duration.

In previous screenshots, the leftmost green line is dashed (probably because it's below fullscale deflection). But in the last two, be it offset or not, the line is solid.

The debug output is like this: (8bits 0~255 given by ADC)

* many 0 then suddenly 255 thereafter. (matches the GUI output)

I suspect it's due to slow TXRX? How to solve this? Or anything I overlooked?

Hope that this overdetailed question does not sicken you.

# Answer
> 0 votes
From the ATmega328P datasheet, section 29.8, "ADC Characteristics":

> Clock Frequency — Min.: 50kHz, Max: 1000kHz

With a 16MHz system clock this means that a /16 prescaler is the most the ADC is considered reliable under for a reasonable 10 bit result (for a *full* 10 bit result the maximum frequency is 200kHz, which corresponds to a prescaler of /80).

As the frequency increases the sample-and-hold circuitry of the ADC gets less time to do the "sample" part before conversion begins. As such any correctness goes out the window, certainly at the lower bits. The fact that you got any sort of result that you did at /4 is luck.

**TL;DR:** The ADC is too slow.

---
Tags: serial, arduino-nano, analogread
---


# Question
Title: How can I run two loops simultaneously on an Arduino Uno?
I'm new to Arduino and I have two devices that I'm trying to control:

1. A RGB LED light strip that can change colors
2. A light sensor that can detect the ambient light level

What I'd like to do is have the LED strip continuously cycle through a rainbow of colors, and the light sensor will adjust the brightness of the LED strip based on the ambient light level. Here are the two pieces of code by themselves, which I've tested in isolation and confirmed that they work properly:

LED strip:

```
j = (j + 1) % 256; // current iteration of the light cycle

// set the strip color
for(int i=0; i< strip.numPixels(); i++) {
  strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
}

// display the new colors and wait 20ms before the next cycle
strip.show();
delay(20);

```

Light sensor:

```
sensors_event_t event;
tsl.getEvent(&event); // get a light measurement
strip.setBrightness(event.light); // set the brightness of the LED strip

```

The problem is that the light sensor takes anywhere from 100ms to 600ms to get a reading, and `tsl.getEvent(&event)` is a blocking call, so the end result is that the LED strip updates way too slowly. I would need to run the two side by side so that the light sensor read does not block the LED strip update. Any idea how I can accomplish this?

# Answer
You can make the sensor return data faster by lowering it's accuracy.

```
tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS);      /* fast but low resolution */

```

You can also modify the library to not power-down the sensor after each reading. Just open `TSL2561.cpp`, find the `getFullLuminosity` function, and comment out the line reading `disable();` and the 12 lines reading `switch (_integration){ ... }`

Another solution is, to have the pixels update every 20ms using a timer. You can have the timer, interrupt the main loop every 20ms and update the pixel values.

(I can't really help you with timers, as I myself set the registers for my timers, and ISRs directly, which isn't for beginners. But there are probably libraries for it, to make it more user friendly.)
> 6 votes

# Answer
The arduino is not a multithreaded or multi-tasking device. You have to write your different functions to "play nice" with each other. Blocking code is death for this sort of multitasking. You might need to rewrite your code that reads the light sensor to be non-blocking.

If you can get that code to be non blocking then Visual Micro's post is the way to go.
> 3 votes

# Answer
Setup a 'state server' in your loop(). Put simply this means keeping track of the next command for each task, then doing one thing in each task per loop().

If one task needs to run at a faster speed than another task you can use a timer in your loop to decide what to do next.

If a task needs a pause then save the "Last Run" millis() to a global variable and ignore the task until the correct amount of time has passed. Do not use a delay(), always let the loop() run.

The idea is that the loop() runs as often as possible but you do one thing each time it runs.

It takes a while to get the hang of this way of working but it leaves the Arduino processor free to process all jobs evenly.

```
int task1Status=0;
int task2Status=0;

void loop()
{
  doOneThingOfTask1();
  doOneThingOfTask2();
}

//10 things to light the leds, but only do one
void doOneThingOfTask1()
{
  if (task1Status==10)
    task1Status=0;

  switch (task1Status)
  {
    case 0:
       //start doing a new process

    case 1:
       //do something

    case 9:
       //do the last thing

  }
}

```
> 1 votes

# Answer
Your first, biggest problem is

> the light sensor takes anywhere from 100ms to 600ms to get a reading, and tsl.getEvent(&event) is a blocking call,

You need non-blocking access to the light sensor. Look at the library code to see what it is doing when it blocks. Chances are it waits for the sensor to set a 'done' bit. If so, you'll need to modify the library, either by

1. adding a boolean `.isDone()` function that tests the done bit, and don't let your main program call for a reading until isDone() == TRUE; or
2. making .getEvent() a non-blocking such that it immediately returns an obviously invalid reading (such as -1) instead of blocking if the sensor isn't ready yet.

That leaves your main program free to service whatever needs doing and is ready to do without holding up everything for the slow sensor.
> 1 votes

# Answer
There are libraries that allow multitasking, for instance my library arduOS.

This should work:

```
#include <arduos16.h>
#include <arduos_core.h>
#include <roundscheduler.h>

SYS_enable_preemptive; // do NOT forget this!!!
void setup()
{
    auto sched = new SYS::RoundScheduler(2);
    sched->add(&loop1); // those 2 are functions.
    sched->add(&loop2);
    SYS::start();
}

```

But keep in mind that actual multitasking can be rather tricky, with very obscure bugs. (but you can find them).
> 0 votes

# Answer
1.Use two arduino's and have them talk to each other via serial or i2c. Probably the simplest option (but not the cheapest - though you can get clone arduinos from US$4 ).

2.Find a light sensor that updates faster. Tried an ldr(light dependent resistor)/photocell ? Then could use analog read.

Could also switch from using arduino to c, but thats a lot more work and you are still going to hit similar problems.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino board to control microwave oven?
So I've taken apart an old microwave oven with a touch-sensitive LCD screen. I understand that I could die from playing around with this, so I've disconnected the high-voltage transformer and the magnetron. I'm also not going to remove any of the safety switches like the door switch. My question is, how is the microwave controlled? I'm thinking there is a computer chip somewhere in the circuit, and I'm looking to replace it with an Arduino board plus some extras, like AC relays and such. I'm curious as to how the microwave oven controls its functions, like power level, cooking time, and the beeping. Any advise as to how I could get started interfacing?

Is the power level controlled by PWM by any chance? Can you PWM alternating current?

# Answer
> 2 votes
It's pretty much all proprietary. It can be done, but you'd have to replace all the circuitry with the Arduino, interfacing with the existing magnetic and mechanical devices and doing everything in your own code.

Power level is controlled by PWM, but it's *extremely* low frequency PWM, on the order of 0.05Hz (20s period). That's why there are two different sounds that come from the microwave when it's not at full power; one when the magnetron is active, and one when it is off.

# Answer
> 2 votes
There is no power level in a microwave. It's just on or off. They lower the power by turning on the magnetron for a few seconds, and then off for a few second. You can actually hear this.

It's probably turned on by a relay, triac, or solid state relay. The magnetron is just requires a high voltage to work; nothing else.

The programmes, timing, and handling of the buttons is done by some microcontroller, similar to an arduino.

# Answer
> 0 votes
If you want to learn more about AC power circuits start with relays (start with 5v or 12v dc as a lot safer , cheaper and easier) something like the spark fun power tail if you really do want to control 120V devices note its only on/off control, not different power levels. https://www.sparkfun.com/products/10747

You can generate AC from DC by using pwm at a lower voltage and driving a transformer or a digital inverter. Can use an arduino to do it if you wanted to. Use pwm function, then via optocouplers (to protect the arduino) to power mosfets or an h-bridge to drive a transformer. Can fairly easily produce 120V/240V output

Time to grab a good basic electronics book like Art of Electronics (should be able to find a pdf version) 3rd edition is finally getting published in 2015

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


# Question
Title: Error Compiling on raspberry Pi - no error details provided in IDE
I've just cracked out my Franzis Arduino Tutorial Kit (Best Xmas Present EVER!) and I'm already stuck on my second program.

I successfully wrote and executed a basic 'blink' program, however when I wrote out the second program provided in the manual I get an 'Error Compiling' when trying to check the syntax or run the program.

I tried the obvious of unplugging the board and plugging it back in but this didn't work. When I search for help most forum posts refer to the error message, however I have no message, just the orange warning bar stating 'Error Compiling'

This is the code;

```
// Franzis Arduino
// My second Arduino program

int ledPin = 13; //LED is connected with digital pin 13

// The setup routine configures the digital port
// This routine is executed only once at program start!

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  Serial.printIn("Our second Arduino program");
  Serial.printIn();
}

// The main program is an infinate loop
void loop()
{
  Serial.print("5 + 188 yields");
  Serial.print(5+188);
  while(true)
  {
    digitalWrite(ledPin, HIGH); // Turn on LED
    delay(2000);                 // Wait for a second
    digitalWrite(ledPin, LOW);   // Turn off LED
    delay(2000);                 // Wait for a second
    continue;
  }
}

```

And here's a screenshot of the error message (or lack of);

# Answer
> 1 votes
It's not `printIn`, but `println` (as in "print line").

---
Tags: arduino-uno
---


title: VCNL4000 Proximity/Light sensor

text:
# Question
Title: VCNL4000 Proximity/Light sensor
I want to use the VCNL4000 Proximity/Light sensor s. http://www.adafruit.com/products/466?&main\_page=product\_info&products\_id=466

In the package i've this 6 pin connector but the VCNL has 5 pins (i now i can connect it by myself with male jumper) but what am i missing here? I assume that it is not an "accident" that the thing has one more pin then the sensor ; )

# Answer
You can just cut off the extra pin. Adafruit probably just had a bunch of 6 pin headers in their stock.
> 3 votes

---
Tags: sensors
---


title: Arduino power consumption issues

text:
# Question
Title: Arduino power consumption issues
I'm working on an Arduino project involving an UNO. I'm powering a 20x4 LCD screen and I am using all the ports on the Arduino, to the last.

All but four of them are pulled high at any given time, so by the time I'm done with pulling them all up the screen is going dim when powering via USB. So I tried powering via an external 9V 600mA adapter, but that makes the Arduino overheat and eventually shut down. I then tried another, 12V 500mA adapter, and that one doesn't even get my UNO to the end of the setup function, and it reboots repeatedly.

Anyone got good advice? Ideas?

# Answer
The official arduino uno schematic uses a NPC1117 voltage regulator. This is a linear one. This means that if you put 12V on it, and if your system requises 0.5A, you Will leak 0.5A on the 12V, and, if there is 5V on the output, 12V on the input, there is a 7V drop on the regulator, 7V * 0.5A = 3.5W that turns into heat.

To avoid overheating, the solution isn't to increase the input voltage, but to decrease it. If you have a 6.2V power supply, this will minimize overheating. At least 6.2V are required for the NPC1117 to provide a stable 5V.

An other option is to use a USB 5V power supply with an output current greater than 0.5A. This is often used with smartphones. This allows to bypass the NPC1117, but the power supply shall be exactly 5V (where exactly stands for less than 10% of over or undervoltage).

Also, please note:

> Arduino does not recommend bypass\[ing the\] Vin supply to directly supply 5V rail on the board as it will damage the NPC1117. See the first two line on page # 3 from the document link below. http://media.digikey.com/pdf/Data%20Sheets/Arduino%20PDFs/ArduinoEthernet.pdf You can either do the soldering and remove NPC1117 chip before you apply 5V directly onto the board or find a higher current capability power supply with the output voltage between 7v-12V.
> 2 votes

---
Tags: power
---


title: Multiple Definition of "_Vectors"?

text:
# Question
Title: Multiple Definition of "_Vectors"?
I'm working on an arduino project that uses the GSM Shield and the eHealthSensor from Cooking Hacks. However I ran into an issue in which the interrupt vectors from the header/cpp files used are being defined multiple time.

While I know where the definitions are, I am unsure as to how to circumvent this issue either by Arduino programming or modifying the files since I'm not too experienced in this field. Below are the code for the conflicting files.

Below are the vectors that are in conflict.

PinChangeInt.h

```
    #ifndef NO_PORTA_PINCHANGES
    ISR(PCINT0_vect) {
        #ifdef PINMODE
        PCintPort::s_PORT='A';
        #endif
        PCintPort::curr = portA.portInputReg;
        portA.PCint();
    }
    #define PORTBVECT PCINT1_vect
    #define PORTCVECT PCINT2_vect
    #define PORTDVECT PCINT3_vect
    #else
    #define PORTBVECT PCINT0_vect
    #define PORTCVECT PCINT1_vect
    #define PORTDVECT PCINT2_vect
    #endif

    #ifndef NO_PORTB_PINCHANGES
    ISR(PORTBVECT) {
        #ifdef PINMODE
        PCintPort::s_PORT='B';
        #endif
        PCintPort::curr = portB.portInputReg;
        portB.PCint();
    }
    #endif

    #ifndef NO_PORTC_PINCHANGES
    ISR(PORTCVECT) {
        #ifdef PINMODE
        PCintPort::s_PORT='C';
        #endif
        PCintPort::curr = portC.portInputReg;
        portC.PCint();
    }
    #endif

    #ifndef NO_PORTD_PINCHANGES
    ISR(PORTDVECT){
        #ifdef PINMODE
        PCintPort::s_PORT='D';
        #endif
        PCintPort::curr = portD.portInputReg;
        portD.PCint();
    }
    #endif

    #ifdef __USE_PORT_JK
    #ifndef NO_PORTJ_PINCHANGES
    ISR(PCINT1_vect) {
        #ifdef PINMODE
        PCintPort::s_PORT='J';
        #endif
        PCintPort::curr = portJ.portInputReg;
        portJ.PCint();
    }
    #endif

    #ifndef NO_PORTK_PINCHANGES
    ISR(PCINT2_vect){
        #ifdef PINMODE
        PCintPort::s_PORT='K';
        #endif
        PCintPort::curr = portK.portInputReg;
        portK.PCint();
    }
    #endif

    #endif // __USE_PORT_JK

```

GSM3SoftSerial.cpp

```
// This is here to avoid problems with Arduino compiler
void GSM3SoftSerialMgr::manageMsg(byte from, byte to){};

//#define PCINT1_vect _VECTOR(2)
//#undef PCINT1_vect

#if defined(PCINT0_vect)
ISR(PCINT0_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT1_vect)
ISR(PCINT1_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT2_vect)
ISR(PCINT2_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT3_vect)
ISR(PCINT3_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

```

Any advice on how to fix this will be greatly appreciated.

If it helps, I am using an Arduino Mega 2560.

# Answer
> 2 votes
It's linking problem. More .o files included in linking declares identical global symbol eg. `ISR(PCINT1_vect)`. Ideally write own *makefile* and compile via standard *make*. As hack you can loook in *PinChangeInt.h* conditional parts and make global definitions not to avoid \*ISR()\*s, e.g. `#define __USE_PORT_JK`

---
Tags: programming, arduino-mega, c++, pins, interrupt
---


title: About arduino serial communication

text:
# Question
Title: About arduino serial communication
I've used the arduino uno with the python serial library months ago and some packets got lost in the way. I've been searching about serial communication for arduino and I've been thinking that I could use some parity systems and other things to guarantee that my packets will arrive. First of all, if I use the parity system of the arduino's serial library, how good it will be? I need to send packets like "this button was touched", but ALL packets must arrive, so if some packet fails, I need to send it again.

How to make it possible? I'm thinking about using the parity system of the arduino's library, but I don't think if it's gonna work well.

Can somebody point me some good text about it?

# Answer
There is no way to *guarantee* that all packets will arrive. The best you can do is to have the receiving system acknowledge receipt of all packets, with enough data within to verify the correctness of the packets.

UART parity is not a good method to verify correctness since it can only detect single-bit errors within a byte; two bit errors will verify correctly, and of course the entire byte may get dropped before it can even get to the receiver.

RFC 916, "RELIABLE ASYNCHRONOUS TRANSFER PROTOCOL (RATP)", describes a TCP/IP-like method of sending data reliably over an asynchronous medium. It's more wordy than just sending a byte containing status changes, but if you need reliability then you need more than that.
> 1 votes

---
Tags: serial, i2c, communication
---


# Question
Title: Light LED when 2 others are disconnected
I need to make circuit in which orange LED will light only when yellow and red are disconnected. When one of buttons is pushed orange LED should turn off.

See my attempt at it below.

I am new to electronics so your help is very appreciated.

**EDIT:**

After many atemps I managed to build this circuit as on left side of schematic (tested on live breadboard)

but my primary goal is to make this work with RGB LED. I took Common Anode RGB LED for this and build circuit on right side of schematic. I do not have such RGB LED to test it live so I ask you to review if that schematic will work as it has few changes to one with 3 LED's. Thank you

**SOLUTION:**

Thanks to Bruce's help my circuit now works.

3 separate LEDs emulate common anode RGB LED (as I do not have one to test circuit)
Q2 is BC 560B transistor with CBE type pinout

CODE:

```
void setup() {
  pinMode(2,INPUT);
  pinMode(4,INPUT);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
  digitalWrite(4,HIGH);
}

void loop() {
  Serial.println(digitalRead(2));
  Serial.println(digitalRead(4));
}

```

# Answer
You want the green LED to be on *only* when the red and blue LEDs are both off. In other words, you want the voltage on the green LED to be LOW only when the voltages on the red and blue LEDs are both HIGH. That is a logical NAND function.

Your right-hand circuit with the RGB LED won't work because the transistor's collector is connected to the wrong place - it's shorting out the battery! Another problem is that the Arduino can only switch to Ground or +5V, so it can't replace a 'floating' switch.

You need a configuration that produces a logical NAND function. Your left-hand circuit is doing it, but won't work with a common anode RGB LED. So swap the transistor to a PNP type, and add a couple of resistors to switch it on when either input goes low, like this:-
> 1 votes

---
Tags: led
---


title: WiFi UDP.endPacket() continuously fails

text:
# Question
Title: WiFi UDP.endPacket() continuously fails
I am attempting to send data from my Arduino to my computer using the WiFi shield. However, my code is erroring out on UDP.endPacket(), and I do not understand why. Here is my code:

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

int status = WL_IDLE_STATUS;
char ssid[] = "NETGEAR31"; //  your network SSID (name)
char pass[] = "oddearth926";    // your network password (use for WPA, or use as key for WEP)

char  ReplyBuffer[] = "acknowledged";       // a string to send back

WiFiUDP Udp;

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

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD)
  {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }
  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED)
  {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
  Serial.println("\nStarting connection to server...");
  if(!Udp.begin(8765))
  {
    Serial.println(F("failed"));
  }

  // if you get a connection, report back via serial:
}

void loop()
{
  IPAddress ip(10,0,0,5);
  int port = 8766;
    // send a reply, to the IP address and port that sent us the packet we received
    if(!Udp.beginPacket(ip, port))
    {
      Serial.println(F("Failed beginning packet"));
    }
    Udp.print(ReplyBuffer);

    if(!Udp.endPacket())
    {
      Serial.println(F("Failed ending packet"));
    }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

And here is the log:

```
Attempting to connect to SSID: NETGEAR31
Connected to wifi
SSID: NETGEAR31
IP Address: 10.0.0.34
signal strength (RSSI):-63 dBm

Starting connection to server...
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet

```

It will continue to spit out "Failed ending packet" until I stop it. Any ideas?

# Answer
> 0 votes
Fixed by updating firmware on Wifi Shield.

---
Tags: networking
---


title: Adafruit gps breakout module help

text:
# Question
Title: Adafruit gps breakout module help
I am intending to show the initial, searching for signal..., screen until the location is updated and then show the location on the lcd. However, even after the led on the gps indicates a satellite fix, the screen never leaves the searching for signal screen. Any help would be greatly appreciated-- very new to microcontroller programming. Sorry for the poorly formatted code block as well, I am in a rush. Thanks in advance.

```
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
#include <TinyGPS++.h>

#define RXPin 2
#define TXPin 3
#define GPSBaud 4800

SoftwareSerial ss(RXPin, TXPin);
TinyGPSPlus gps;
LiquidCrystal lcd(12, 11, 10, 7, 6, 5, 4);

double latt;
double lon;
int screen;

void setup(void);
void loop(void);
void readGPS(void);
void update(void);
void render(void);

void setup() {
     //variable initialization
     latt = 0.0;
     lon = 0.0;
     screen = 0;

     //lcd initial setup
     pinMode(9, OUTPUT);
     analogWrite(9, 100);
     pinMode(13, OUTPUT);
     digitalWrite(13, HIGH);

     //display intial screen
     lcd.begin(16,2);
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Searching for");
     lcd.setCursor(6,2);
     lcd.print("Signal ...");
     ss.begin(GPSBaud);
}

void loop() {
    readGPS();
    update();
}

/** Receives data from the gps if available */
void readGPS() {
    while (ss.available() > 0) {
        gps.encode(ss.read());
    }
}

/** Processes the data read by readGPS() */
void update() {
    if (gps.location.isUpdated()) {
        latt = gps.location.lat();
        lon = gps.location.lng();
        render();
    }
}

/** Displays the current screen on the lcd */
void render() {
    if (screen == 0) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Lat:");
        lcd.print(latt);
        lcd.print(" Lng:");
        lcd.print(lon);
        lcd.setCursor(0,1);
        lcd.print("Sats:");
        lcd.print(gps.satellites.value());
    }
}

```

# Answer
> 1 votes
Adafruit GPS breakout has their own library setup.
Below is the code I use for my telemetry. Notice I'm using HardwareSerial though.
You can just change that into SoftwareSerial.

```
#include <SoftwareSerial.h>
#include <Adafruit_GPS.h>
#define GPSECHO false // Disables GPS breakout debug

boolean usingInterrupt = false;

HardwareSerial gpsSerial = Serial1;
Adafruit_GPS GPS(&Serial1);

SoftwareSerial XBee(2, 3); // For wireless

unsigned int REFRESH = 20;

double lat_deg, lon_deg, lat_min, lon_min;
char lat, lon;

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

  GPS.begin(115200);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_5HZ); // Either 1HZ or 5HZ
  GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ);
  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);
}

SIGNAL(TIMER0_COMPA_vect)
{
  char c = GPS.read();
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
#endif
}

void useInterrupt(boolean v)
{
  if(v)
  {
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  }
  else
  {
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

void loop()
{
  if(GPS.newNMEAreceived())
  {
    if(!GPS.parse(GPS.lastNMEA()))
    {
      writeData(1, true);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999"));
    }
    else if(GPS.fix)
    {
      writeData(1, true);
      parseGPS(GPS.latitude, GPS.longitude);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(lat_dd, 8); Serial.print(F(","));
      Serial.print(lon_dd, 8); Serial.print(F(","));
      Serial.print(GPS.speed); Serial.print(F(","));
      Serial.print(GPS.angle); Serial.print(F(","));
      Serial.print(GPS.altitude); Serial.print(F(","));
      Serial.print(GPS.satellites);
    }
  }
  delay(REFRESH);
}

void parseGPS(float _latitude, float _longitude)
{
  lat_deg = (int) (_latitude / 100);
  lon_deg = (int) (_longitude / 100);

  lat_min = _latitude - (lat_deg * 100);
  lon_min = _longitude - (lon_deg * 100);

  lat_dd = (double) lat_deg + ((double) lat_min / 60);
  lon_dd = (double) lon_deg + ((double) lon_min / 60);

  lat = GPS.lat; lon = GPS.lon;

  if (lat == 'S') lat_dd = -lat_dd;
  if (lon == 'W') lon_dd = -lon_dd;
}

void writeData(float data, boolean next)
{
  Serial.print(data);
  if (next) Serial.print(F(","));
}

```

---
Tags: arduino-uno, lcd, tinygps, gps
---


# Question
Title: Problem with while loops while detecting frequency of a signal
I just started to use the unusual part of Arduino language (avr) like interrupts, accessing registers, etc in Arduino IDE. I wrote a program to calculate the frequency of a digital signal using external interrupts.

The following code is to calculate timeperiod of a digital signal, the output of the color sensor (TCS3200) which depends on the color filter choosen via S2 and S3 pins, as in the code. That is, color sensor produces 50% duty cycle square pulses of frequency dependent on the power of the light incident on it. So when sensor faces red color, output signal's frequency in red color mode (by setting S2, S3 pins) is more than the frequency in blue and green modes. Thus we can detect the likeliness of the color which it faces w.r.t R,G,B.

When this code is uploaded in the Arduino, it failed to print the values as expected in the serial monitor i.e. its stuck in while loops. But when `Serial.print(e)` statement in the while loops are uncommented, it is able to print the required time periods. I am unable to figure out the problem here, which is making Arduino to be inside the while loop when no statements are in it.

```
// INT0 interupt is used i.e. digital pin 2
int ti=0,tim=0,e=0,S2=4,S3=5;

void Interruptinit() //initializing interrupt INT0
{
  cli();
  EICRA =  0x02; //Control register
  EIMSK =  0x01; //Mask register
  sei();
}

void setup()
{
  pinMode(2,INPUT);
  digitalWrite(2,HIGH); //enabling pull up register
  pinMode(S2,OUTPUT);
  pinMode(S3,OUTPUT);
  Interruptinit();
  Serial.begin(9600);
}

ISR(INT0_vect)
{
  tim=micros()-ti;
  ti=micros();
  e++;
}

void loop()
{
  digitalWrite(S2,0); digitalWrite(S3,0); //switching over red filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e) //waiting till interrupt is addressed 2 times
  ;
  Serial.print("red:");
  Serial.print(tim);

  digitalWrite(S2,0); digitalWrite(S3,1); //switching over blue filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" blue:");
  Serial.print(tim);

  digitalWrite(S2,1); digitalWrite(S3,1); //switching over green filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" green:");
  Serial.println(tim);

}

```

# Answer
Whenever you modify non-local variables in an ISR, it's important that they are declared as `volatile`. This tells the compiler that the contents may change unexpectedly, ensuring it doesn't use out-of-date cached copies somewhere else. If you don't do this, the code can behave in unpredictable ways, such as outputting the wrong value under some circumstances.

Since the variables are bigger than 1 byte, it's also necessary to disable interrupts around non-ISR code which uses them (e.g. in `loop()`). This is because interrupts could be triggered at any time, potentially half way through an operation which reads/writes them.

You can use `noInterrupts()` and `interrupts()` to disable/enable interrupt handling.
> 3 votes

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


# Question
Title: TIMER1 CTC Interrupts not working with avr-gcc
I am attempting to program my arduino in plain C, and I've come across some very strange behavior. If I load the following code from the Arduino IDE, it works as expected and toggles Pin 6 every 100ms. However, if I compile it with avr-gcc and then load it with avrdude, no interrupts are run. Here is the C code:

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

int main();
void timer1_init();

int main()
{
    // connect led to pin PD6
    DDRD |= (1 << 6);
    PORTD |= (1 << 6);

    // initialize timer
    timer1_init();

    // loop forever
    while(1)
    {
        // do nothing
        // whenever a match occurs, ISR is fired
        // toggle the led in the ISR itself
        // no need to keep track of any flag bits here
        // done!
    }
}

// initialize timer, interrupt and variable
void timer1_init()
{
    /*cli();*/
    /*TCCR1A = 0;*/
    /*TCCR1B = 0;*/
    /*TCNT1 = 0;*/
    OCR1A = 24999;
    TCCR1B |= _BV(WGM12) | _BV(CS11) | _BV(CS10);
    TIMSK1 |= _BV(OCIE1A);
    sei();
}

ISR (TIMER1_COMPA_vect)
{
    // toggle led here
    PORTD ^= (1 << 6);
}

```

And here is the Makefile I'm using to load it onto the arduino:

```
CC = avr-gcc
CFLAGS = -g -O0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106

SOURCE = test

all: load

$(SOURCE): $(SOURCE).o
    $(CC) $(SOURCE).o -o $(SOURCE)

hex: $(SOURCE)
    avr-objcopy -O ihex -R .eeprom $(SOURCE) $(SOURCE).hex

load: hex
    avrdude -F -V -c arduino -p ATMEGA328P -P /dev/tty.usbmodem1411 -b 115200 -U flash:w:$(SOURCE).hex

clean:
    rm -f *.o *.hex
    rm -f `find . -perm 755 | perl -pe 's/\.\n//g' | perl -pe 's/\.\/(\w+)\n/\1 /g'`

```

Is there something that the arduino ide automatically adds to it that makes it work? What am I missing?

Edit: Here is the make output:

```
avr-gcc -g -O0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106   -c -o test.o test.c
avr-gcc test.o -o test
avr-objcopy -O ihex -R .eeprom test test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/tty.usbmodem1411 -b 115200 -U flash:w:test.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
         avrdude: erasing chip
         avrdude: reading input file "test.hex"
         avrdude: input file test.hex auto detected as Intel Hex
         avrdude: writing flash (196 bytes):

         Writing | ################################################## | 100% 0.04s

         avrdude: 196 bytes of flash written

         avrdude: safemode: Fuses OK (E:00, H:00, L:00)

         avrdude done.  Thank you.

```

# Answer
> 0 votes
I just tried using arduino-mk https://github.com/sudar/Arduino-Makefile, and it worked, so I guess I'm just going to stick with that.

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


title: Wiring VCNL 4000 Proximity Sensor

text:
# Question
Title: Wiring VCNL 4000 Proximity Sensor
I was looking for wiring the VCNL 4000 Proximity Sensor.

I found this one http://bildr.org/2012/11/vcnl4000-arduino/

but there is used a sensor on a red board, which has other pins like mine (which has a blue board) see http://www.adafruit.com/products/466?&main\_page=product\_info&products\_id=466

as I see SCL,DSA,GRND on both

the red has IR+ which is connected to the 5V . mine (blue one) has VIN. Is this meant to be the same and should it be connected to the 5V ?

Any hints?

I tried the following wiring but the following call does not finish.

3,3V TO 3,3V POWER

SCL TO SCL (Last pin on the digital side)

SDA to SDA (Beside SCL)

GND TO GND on the Analog side

Vin to 5V

```
 readVCNLByte(0x81); is called

```

i used the example code from adafruiut

# Answer
> 1 votes
There seems to be a big difference between the Sparkfun and the Adafruit breakouts:

* Sparkfun breadkout needs 3.3V and 5V power as **inputs** as shown in their wiring circuit (in the first link you mentioned)
* Adafruit breakout needs only 5V as input but has a 3.3V regulator on it that provides the 3.3V to all its internal circuits that need it; it also has a 3.3V pin which is an **output** not an input as for the Sparkfun

Hence your wiring is wrong. The expected wiring is described in Adafruit sample sketch:

```
// Example sketch for talking to the VCNL4000 i2c proximity/light sensor
// Written by Adafruit! Public domain.
// To use: Connect VCC to 3.3-5V (5V is best if it is available), GND to
//         ground, SCL to i2c clock (on classic arduinos, Analog 5), SDA
//         to i2c data (on classic arduinos Analog 4). The 3.3v pin is
//         an ouptut if you need 3.3V
// This sensor is 5V compliant so you can use it with 3.3 or 5V micros

```

In comments, `VCC` should read as `Vin` on the breakout.

Note that the comments mention `SDA` and `SCL` pins on `A4` and `A5` respectively, this is correct on Arduino UNO, but your wiring on the 2 leftmost pins of the digital pin header is also correct, as these pins are now replicated there on UNO and Leonardo. On Leonardo, the real pins for SDA/SCL are pins 2 and 3. If you don't have a UNO or Leonardo though, you should check where SDA and SCL can be found (that's generally described on Arduino Product page for your board).

Although wiring SDA/SCL on these 2 replicate pins is correct, I would rather recommend using A4 and A5 instead, so that you don't get the illusion that you can both use SDA/SCL and A4/A5 for something else at the same time.

This circuit uses **I2C** which means you should normally add pullup resistors to SDA and SCL wires; however, it seems that the Adafruit breakout already integrates them, so no problem here.

To sum up, and provided that you have a UNO or Leonardo, **your wiring is correct except that you should remove the wire between both 3.3V pins**.

This is shown below for UNO (I used the real pins for SDA and SCL so that you don't use them for something else later):

* Arduino UNO 5V ---\> Breakout Vin
* Arduino UNO GND ---\> Breakout GND
* Arduino UNO A4 ---\> Breakout SDA
* Arduino UNO A5 ---\> Breakout SCL
* Breakout 3.3V left unconnected

For Leonardo it would be:

* Arduino Leonardo 5V ---\> Breakout Vin
* Arduino Leonardo GND ---\> Breakout GND
* Arduino Leonardo D2 ---\> Breakout SDA
* Arduino Leonardo D3 ---\> Breakout SCL
* Breakout 3.3V left unconnected

I show you both UNO and Leonardo since you did not mention which board you use.

---
Tags: sensors
---


# Question
Title: How to send two different sets of int numbers over serial?
I have a project that require for the main computer to do most of the processing then for it to send the X and Y coordinates of this processing to the arduino. This at the time didn't seem very hard but now that I have started to dive into serial some more I am completely confused. All of the example I have seen for serial only consist of 1 set of numbers and rather confusing.

The Arduino code I kinda want to go like this http://pastebin.com/aLJfEExw (I know this is probably completely wrong but I am pretty lost right now)

The Python code is this right now http://pastebin.com/4aN4dnSC

If you guys could help explain this better for me it would be amazing. I understand that my code is probably wrong. So if you guys could provide an example of how to send the two different sets of int's it would be amazing. Because I am completely and utterly lost.

# Answer
I wrote a communication protocol for arduino to node.js over Serial. I sent a buffer of bytes using `Serial.write()` and read it into a buffer. This allows you to send as many numbers as you want. To send long (16 bit) numbers, you simple need to loop over two at a time combining:

C++:

```
long int a = 0x9A44;
uint_8t b = ( a & 0xFF00 ) >> 8;
uint_8t c = a & 0x00FF;

```

Python:

```
a = ( b << 8 ) & 0xFF00 | c & 0x00FF

```
> 0 votes

# Answer
I looked at your code, but the main problem seems to be that you have not defined the problem, and it is thus not possible to definitively answer.

The conventional solution to this would be to send 2 numbers with separator (usually space) followed by a newline. I know Arduino does not have an inbuilt function to do this, but you could write one. http://arduino.cc/en/Tutorial/SerialEvent shows one way this could be done.

Another approach is to send bytes (how long is each number? I would guess 16 bits) so you would send 4 bytes and on reception assemble them into 2 16 bit integers. Whether you need to ensure the data is synchronised depends on your problem. If you are sending continuous data this is essential, and you could use the kind of compelled sequence signalling you seem to be implying.

From the code it looks like you are sending from a Raspberry Pi. If I were doing this I would probably use I²C (at least over a short distance).
> 2 votes

---
Tags: serial, python
---


title: Reading atomic radio clock

text:
# Question
Title: Reading atomic radio clock
i have some data logging to do. And i want some what accurate time meaning accuracy has to be +/- 1 minute.

I have considered a RTC, but then i thought. When i was 10 i got a watch that kept time from this radio clock. And if it is possible 20 years ago to make a clock that updates automatically in such as small form factor, then i should be able to do it with my arduino today.

Does anyone know of a guide/solution with components where i can read this atomic radio clock?

# Answer
So, the first consideration goes to the radio propagation aspect. Every country does things a little different with their radio clocks. And you might only have good signal a few times a day. For a nice overview, check out a solution for the German DCF77. If you're totally set on using a radio clock, time-nuts has discussed in the past ripping open a $10ish clock to get at the fun parts of a WWVB receiver, so that's one overview of the pool you're diving into.

For myself I've skipped past the terrestrial time keeping and went straight to GPS. Find a receiver that provides a pulse-per-second and attach that to an interrupt and process it alongside the timestamp; you can see how I've gone about that in both code and final product.

I think GPS is both easier and more precise than the alternatives, assuming you're above ground and can pick up satellites. I think of RTCs as something to tell me the day and the year, while GPS can tell me the second. But you could consider ripping the antenna out of a cheap bedside radio-controlled clock and using that to set an RTC, careful to consider whether you want a cheap RTC (DS1307) that drifts a minute per day or a slightly more expensive RTC (DS3231 or ISL1220) that drifts a minute per month. (Rough numbers of course.)
> 6 votes

---
Tags: time, datalogging, rtc
---


# Question
Title: Can't send DHT11 temperature data to Xively from Yun
I thought this would be easy but how wrong I am... All I want to do is plot temperature data but I can't seem to get it to work. It reads it out on the serial monitor and says it has sent the data (in the serial monitor) but nothing on the Xively plots! Why?? Below is the code.

I have the API key and feedID from the Xively site. The useragent I'm assuming is the name of the project. My channels are called `sensorValue1` and `sensorValue2`. Please help - this is taking me far too long.

```
#include <Bridge.h>
#include <Console.h>
#include <Process.h>

#include "DHT.h"
#define DHTPIN 0
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

 #define APIKEY "BLablablablabla" // your pachube API key
 #define FEEDID blablabla // your feed ID
 #define USERAGENT "SebYun2" // user agent is the project name

// set up net client info:
const unsigned long postingInterval = 60000; //delay between updates to xively.com
unsigned long lastRequest = 0; // when you last made a request
String dataString = "";

void setup() {
  // start serial port:
  Bridge.begin();
  Serial.begin(9600);
  dht.begin();
  while(!Serial); // wait for Network Serial to open
  Serial.println("Xively client");
  // Do a first update immediately
  updateData();
  sendData();
  lastRequest = millis();
}

void loop() {
  // get a timestamp so you can calculate reading and sending intervals:
  long now = millis();
  // if the sending interval has passed since your
  // last connection, then connect again and send data:
  if (now - lastRequest >= postingInterval) {
    updateData();
    sendData();
    lastRequest = now;
  }
}

void updateData() {
  // convert the readings to a String to send it:
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  dataString = "Temperature,";
  dataString += dht.readTemperature(false);
  delay(250);
  // add pressure:
  dataString += "\nHumidity,";
  dataString += dht.readHumidity();
  int sensorValue1 =  analogRead(A0);
  delay(100);
  int sensorValue2 =  analogRead(A0);
  dataString += "\nVoltage1,";
  dataString += sensorValue1*0.0049;
  Serial.print(sensorValue1);
  dataString += "\nVoltage2,";
  Serial.print(sensorValue2);
  dataString += sensorValue2*0.0049;
  delay(1000);
}

// this method makes a HTTP connection to the server:
void sendData() {
  // form the string for the API header parameter:
  String apiString = "X-ApiKey: ";
  apiString += APIKEY;
  // form the string for the URL parameter:
  String url = "https://api.xively.com/v2/feeds/";
  url += FEEDID;
  url += ".csv";
  // Send the HTTP PUT request
  // It is better to declare the Process here, so when the
  // sendData function finishes the resources are immediately
  // released. Declaring it global works too, BTW.
  Process xively;
  Serial.print("\n\nSending data... ");
  xively.begin("curl");
  xively.addParameter("-k");
  xively.addParameter("--request");
  xively.addParameter("PUT");
  xively.addParameter("--data");
  xively.addParameter(dataString);
  xively.addParameter("--header");
  xively.addParameter(apiString);
  xively.addParameter(url);
  xively.run();
  Serial.println("done!");
  // If there's incoming data from the net connection,
  // send it out the Serial:
  while (xively.available()>0) {
    char c = xively.read();
    Serial.write(c);
  }
}

```

# Answer
As long as I checked, this way of uploading data to Xively only works for up to tree pairs of name,data.

If you try with more pairs at the same time the response is "Done", but nothing happens. I finally divide the upload in groups of 3 parameters, and everything is Ok.

I saw your question yesterday when I was looking for a way to upload data to Xively from Yun. It was really helpful for me. Thank you.
> 1 votes

---
Tags: arduino-yun
---


# Question
Title: Fade LED strip using proximity and map() function
I'm using a sonar sensor to detect proximity, and need to control the brightness of an LED strip in direct relationship to the distance detected. For example, as someone moves toward the sonar, the strip needs to dim.

I'm using map() to do it now crudely but it's way too abrupt and I'm not sure how best to achieve the effect I'm looking for. Ideally, as the person moves toward the light, it very smoothly fades out in relationship to the person's movement/pace.

Initial thoughts / questions:

-- Can I use a more refined number type to set the LED brightness other than int? -- Do I need to do something more complex where I detect the delta in the person's movement and use the loop to fade the LED from one value to another? Seems complicated...

Any help / ideas on this would be much appreciated! Existing code is below if it helps. Claudia

```
//variables needed to store values
long pulse, inches, cm;

//LED VARIABLES
int frontPin = 6;    // front strip connected to PWN pin 5
long interval = 8000; // interval at which to do something (milliseconds)
int val;

void setup() {
  //This opens up a serial connection to shoot the results back to the PC console
  pinMode(frontPin, OUTPUT);
  pinMode(pwPin, INPUT);
  Serial.begin(9600);
}

void loop() {
    //Used to read in the pulse that is being sent by the MaxSonar device.
  //Pulse Width representation with a scale factor of 147 uS per Inch.

  pulse = pulseIn(pwPin, HIGH);
  //147uS per inch
  inches = pulse/147;
  //change inches to centimetres
  cm = inches * 2.54;

  if (inches < 36){
    detect();
  }
}

void detect(){
  Serial.print(inches);
  Serial.print("in, ");
  Serial.println();

  val = inches;
  val = map(val, 6, 36, 0, 255);

  analogWrite(frontPin, val);
  Serial.print("mapped value is ");
  Serial.print(val);

  delay(500);

}

```

# Answer
The biggest problem is that by forcing the code to use integral inches you've restricted it to 31 discrete values. And since the brightness response of a PWMed LED is non-linear you effectively have *very* large steps in brightness when the LED is dim.

`pulseIn()` has *much* more flexibility with regards to its range so use the raw value directly instead of converting it to "pretty" values.

```
val = map(pulse, ..., ..., 0, 255);

```
> 1 votes

---
Tags: led, proximity, map
---


title: Can I program Arduino with Python?

text:
# Question
Title: Can I program Arduino with Python?
I know that I can program Arduino with python but is it possible to make every project, which can be completed by normal IDE?

# Answer
> 3 votes
I imagine you want to use python because you are already familiar with it, know your way around the syntax, etc. But I would advice against this line of thinking, because microcontrollers need a little more of "low-level" thinking (given the limited resources they generally have) and because of that, it's probably best if you learn some C/C++.

The arduino programming framework provides some not-so-low-level libraries and tools (like the arduino IDE itself) to make it easy for non-C programmers to learn C-like programming.

However, if you want to use python as a proof of concept or anything else, sorry about the misunderstanding! :)

# Answer
> 1 votes
The direct answer is almost certainly not.

There are some auspicious developments so that you might be able to adapt a specific open source Python package, but the resulting software would require a special Arduino board with an MCU chip with much more SRAM and a higher clock speed than we usually see on Arduino boards.

**Discussion**

I have looked several times and have never found anything.

I did find a "stripped down" implementation of a Python 3.3 interpreter called Micro Python. The software was developed hand in hand with MicroPy, an ARM-based single board computer (also described at the MicroPython website). MicroPy is closer to a Raspberry Pi or Beaglebone than an Arduino. However, the software environment is less complex because the MicroPy doesn't require a Linux-based or other operating system.

The base Micro Python package software package seems to require about 110KB of SRAM to boot up and expects a 1 MB SD chip with a boot record and MicroPython on it.

The Micro Python software was released under the MIT open source license so, in theory, a clever person could adapt it for the Arduino if they built a board with a really powerful chip SD socket.

Although the Micro Python/MicroPy package is very appealing, I don't think I would head down the path. I would rather be programming for hardware that is available from more than one source.

Another potential issue is that the Micro Python implementation uses a mark and sweep garbage collector which might tie up the processor for 4 msec at time. Depending on your application a 4 msec busy period might not be acceptable.

# Answer
> 0 votes
Not really, since python is an interpreted programming language. If you are not new to the microcontrollers' world and have same experience, maybe this Board is you what you want. More powerful than Arduino and completely programble using Python 3.

Topic: Can I use Python to program Arduino?

---
Tags: programming, arduino-ide, c, python
---


# Question
Title: Washing machine controlled by Arduino for homebrewing
So, this question might sound a bit silly at first glance (no, I know, it sounds flat out insane), but not all that silly at second.

I have heard once about a guy who transformed some (presumably old-ish) washing machine into his own personal home-brewing apparatus. It is quite some idea if you think about it. Washing machine can easily solve most issues people have with homebrewing. It can carefully control and adjust temperature throughout the long and complicated process of brewing, it can stir, it can pump in fresh water.

Main question is, how to control washing machine to do what I want it to do. Most automatic washing machines already have some controllers, but I don't see much chance in trying to simply reprogram them (Am I wrong?). **Arduino seems like best choice for its simplicity and expandability. However I am still fairly new to Arduino and have trouble imagining how would connecting everything from washing machine (motor, pump, maybe water and temperature sensors) to Arduino actually look like.**

*So is it even possible? Are there any projects to "bounce of"?* (I couldn't find any, but maybe I looked for wrong projects) *Should I expect any major problems?*

# Answer
There is an article by Atmel, talking exactly about this (not for homebrewing, though). They provide a link to a PDF file that describe in detail a project involving Arduino and a re-created washing machine.

Note that it seems to be some kind of Bachelor graduation project, and that the students seem to build an entire washing machine. They control the rotor using an Arduino, and even provide the code (and a brief history about washing machines..).

Apart from building the entire machine, there are two main directions here as I see it:

1. Manipulate the existing washing machine's control board using Arduino. The bad news are the it would require some reverse engineering of the existing controller, because, per my understanding (and I'm not an expert on the subject) there is no one standard and any manufacturer seems to use it's own propriety control board (similar to Microwaves or Dishwashers). The good news are that an expert could probably do it, either by dumping the controller memory and examining the hex code or by using JTag.
2. Another way to go here is interfacing the electrical hardware itself; see this instructable where the guy connected the Arduino in parallel to the start button, by thus allowing an alternative way to start.

As for a beginner, it would make more sense to go for the latter; in-parallel connection with an existing hardware button should be a fairly comprehensible task. Consider the hazards of working with a high voltage/power device such as washing machines. I must say that on first glance such a project doesn't seem fit a novice, but I would be the last one to hold an enthusiast's back. And if you know any, I would suggest asking supervision from someone with a strong EE background.
> 3 votes

---
Tags: system-design, electronics
---


# Question
Title: Installing MariaMole (Alternative IDE) on Mac
I've heard about a alternative Arduino IDE called MariaMole and really liked the idea, but I just don't know how to install it on Mac OS X. The GitHub page claims that it is compatible with Mac but I just can't find a tutorial, or instructions, as to how the Git files can be compiled on Mac.

# Answer
> 1 votes
*Note: I haven't tried this myself so YMMV; this is just from my general experience and reading; all information comes with citations.*

To start, I would recommend opening an issue on GitHub to ask for detailed instructions. I noticed that the website says:

> Linux and Mac distributions are still experimental, but MariaMole is working fine on both systems.

so they should have a known recipe for how to do it.

---

In the mean time, here's how I would proceed. Given that there's a file called `CMakeLists.txt` in the root directory, you need to:

* download and install CMake

Then, install the dependencies listed on the wiki:

* Qt 5.2
* QScintilla 2
* QSerial

After that, I presume just cloning the repo and running `cmake` in the root directory should do the trick. If you have any further questions, please open an issue on GitHub with your compilation error message for further assistance.

# Answer
> 0 votes
For mac its not yet released (See website).

To try the experimental mac version, you'll have to compile it yourself with the code found on that github repository you linked to

---
Tags: ide
---


title: Reading keyboard input

text:
# Question
Title: Reading keyboard input
I'm using Serial.read(); to read keyboard input from the serial monitor. It only sends the characters after hitting enter or clicking the "send" button. Is there a way to read keyboard input without having to use "enter"?

# Answer
Not with the Serial Monitor built into the Arduino IDE. It is possible to use an external terminal program with buffering disabled though.
> 1 votes

---
Tags: serial
---


# Question
Title: Arduino RBBB - Device not accepting address
I recently purchases and make a Arduino RBBB with a BUB II from Modern Device. I ordered the package found HERE. I built everything according to the instructions, but when I connect it to my laptop (running Ubuntu 14.10), I get the following in dmesg

```
[63415.213391] usb 3-1: new full-speed USB device number 63 using xhci_hcd
[63415.381403] usb 3-1: device descriptor read/64, error -71
[63415.485225] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 26.
[63415.485240] usb 3-1: hub failed to enable device, error -22
[63415.597236] usb 3-1: new full-speed USB device number 64 using xhci_hcd
[63415.709154] usb 3-1: device descriptor read/64, error -71
[63415.813102] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 27.
[63415.813116] usb 3-1: hub failed to enable device, error -22
[63415.925108] usb 3-1: new full-speed USB device number 65 using xhci_hcd
[63415.925270] usb 3-1: Device not responding to setup address.
[63416.129120] usb 3-1: Device not responding to setup address.
[63416.332902] usb 3-1: device not accepting address 65, error -71
[63416.444973] usb 3-1: new full-speed USB device number 66 using xhci_hcd
[63416.445174] usb 3-1: Device not responding to setup address.
[63416.649008] usb 3-1: Device not responding to setup address.
[63416.852734] usb 3-1: device not accepting address 66, error -71
[63416.852813] usb usb3-port1: unable to enumerate USB device

```

It is repeatable every time I insert. lsusb does not register it. I have read that I should switch out the cable, but it is brand new (and I don't have another to test with. I was wondering if there is something evidently wrong with my circuitry. I posted pictures

# Answer
I fixed it. Here is how I did it.

First, I tried connecting just the BUB II to via the USB. Same error, thus I ruled out the Arduino RBBB as the source. I then decided that perhaps it was the voltage jumpers (black things on the pins sticking out in the first picture). After removing them, it works under dmesg, yielding the below.

```
[  214.044563] ftdi_sio 3-1:1.0: FTDI USB Serial Device converter detected
[  214.044687] usb 3-1: Detected FT232RL
[  214.044696] usb 3-1: Number of endpoints 2
[  214.044704] usb 3-1: Endpoint 1 MaxPacketSize 64
[  214.044712] usb 3-1: Endpoint 2 MaxPacketSize 64
[  214.044718] usb 3-1: Setting MaxPacketSize 64
[  214.045209] usb 3-1: FTDI USB Serial Device converter now attached to ttyUSB0

```

Thus I wanted to put them back on so I wouldn't lose them. I proceeded to try various combinations till it worked. Ultimately, I ended with 5V for VOUT and VL for LGLV. If that is a bad idea, someone please comment, but it works.

May this help someone else.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: what is fastest allowable serial baudrate?
what is the fastest serial read the Mega can do? begin.Serial1(1024000) is accepted for compiling, but reading jibberish

any suggestions on a faster device?

# Answer
The Arduino Mega 2560 runs at 16 MHz. There are online calculators making this easy, as the calculation is not a straight and simple formula.

http://wormfood.net/avrbaudcalc.php

which shows using 16 MHz

| Baud Rate | UBRR(dec) | UBRR(hex) | % of error |
| --- | --- | --- | --- |
| 300 | 3332 | 0x0D04 | 0.0 |
| 600 | 1666 | 0x0682 | 0.0 |
| 1200 | 832 | 0x0340 | 0.0 |
| 2400 | 416 | 0x01A0 | 0.0 |
| 4800 | 207 | 0x00CF | 0.2 |
| 9600 | 103 | 0x0067 | 0.2 |
| 14400 | 68 | 0x0044 | 0.6 |
| 19200 | 51 | 0x0033 | 0.2 |
| 28800 | 34 | 0x0022 | 0.8 |
| 38400 | 25 | 0x0019 | 0.2 |
| 57600 | 16 | 0x0010 | 2.1 - Barely OK |
| 76800 | 12 | 0x000C | 0.2 - GOOD |
| 115200 | 8 | 0x0008 | 3.7 - BAD |
| 230400 | 3 | 0x0003 | 7.8 - BAD |
| 250000 | 3 | 0x0003 | 0.0 |

Where it is noticeable that the Mega's Arduino boot loader uses

```
mega.menu.cpu.atmega2560.upload.speed=115200

```

which is above the acceptable 1% error rate.

While it is possible to support different baud rates than stated above, it is not advisable, as the above values are the standard values. Values in between are very atypical and likely not trustworthy on the corresponding other side of the connection.

As I see your above example is 1024000, it is also worth noting that HardwareSerial.cpp implements a method to convert the requested baud rate to configuration of the USART, and I would not necessarily trust it for non-standard baud rates, especially on older version of the Arduino IDE. You may want to try the latest 1.5.8+ and verify the rate.
> 6 votes

# Answer
It depends mainly on CPU frequency, see *USART/Baud rate settings* in datasheet. For example at 16MHz it might go up to 2Mbps. But you need also consider error in baudrate which is important if communication with "3rd party" device.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: How to protect sensors used on atheletes?
I'm working on a project were we are trying to attach accelerometers to soccer players and capture various aspects of movement data. Breadboarded circuits are coming along nicely and I'm now looking for how to best protect sensors we can mount on players. (All wire at the moment unfortunately - BT next.)

Although I can find ways to protect the sensor for sensor damaging impact (we are essentially interested in player impacts with the ball or ground) there are other aspects of protection I'm not sure about. Any recommendations on how to protect from moisture without increasing bulk too much, minimizing cushioning which could affect the data and of course avoid adding anything that could injure the player? I have come across other examples of movement studies, but they have been by musicians or other situations that do not include outdoor weather and sweaty bodies.

# Answer
The only way this is ever done is with some kind of product casing. You can buy pre-fab cases for electronic projects, but to get something really slick and appropriate for your purpose, you're gonna have to make something yourself. You might look into 3D printing.

Something like this might work: https://www.sparkfun.com/products/8601

For protection from salt-water, this product is worth a look: http://www.corrosionx.com/

There's some different products there, but I've seen a demo of that product, where we ran an entire RC airplane system, servos, motors, and receiver, UNDER WATER.
> 1 votes

---
Tags: sensors, accelerometer
---


# Question
Title: How to send data to sim900 only once in loop()
I am trying to communicate with a client(PC) from my arduino (set up as a server with a sim900 module connected via UART). I have successfully got it to register its IP address with a dynamic DNS provider (no-ip.com) and set up a TCP server using the AT+CIPSERVER command for the sim900. All this is done in setup(). After that in loop() it waits for a client to connect. The moment a client connects the problem arises. The code is:-

```
void loop()
{
  while(Serial.available() <= 0);
  int x=0;
  char server_recv_string[30];
  while(Serial.available()>0)
  {
    server_recv_string[x] =  Serial.read();
    delay(10);
  }
  Serial.println(server_recv_string);
  sendATcommand2("AT+CIPSEND",">","ERROR",1000);
  sendATcommand2("I hear you\x1A","SEND OK","ERROR",5000);
  while(Serial.available()>0)  // I dropped this in to clear out the input buffer.
  {                            // Doesn't help
    Serial.read();
    delay(10);
  }
  Serial.flush();
}

```

The sendATcommand2 is a function as given below. I don't think that has any fault in it because it seems to work fine for all the other commands in setup. However this is the code:-

```
int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
    char* expected_answer2, unsigned int timeout){

    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;

    memset(response, '\0', 100);    // Initialize the string

    delay(100);

    while( Serial.available() > 0) Serial.read();    // Clean the input buffer

    Serial.println(ATcommand);    // Send the AT command

    x = 0;
    previous = millis();

    // this loop waits for the answer
    do{
        // if there are data in the UART input buffer, reads it and checks for the answer
        if(Serial.available() != 0 && x < 100){
            response[x] = Serial.read();
            x++;
            // check if the desired answer 1  is in the response of the module
            if (strstr(response, expected_answer1) != NULL)
            {
                answer = 1;
            }
            // check if the desired answer 2 is in the response of the module
            else if (strstr(response, expected_answer2) != NULL)
            {
                answer = 2;
            }
        }
    }
    // Waits for the asnwer with time out
    while((answer == 0) && ((millis() - previous) < timeout));

    return answer;
}

```

The when I monitor it on the serial terminal I get infinite sends to my client. Its like this:

```
 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 // And on and on and on.

```

Any idea why this is happening? If you guys need any more information, please do tell me.

Thanks

Taz

# Answer
> 1 votes
You can use a boolean variable to decide if you are going to execute the send command. You can set the variable to true in the setup and to false after the command is executed.

If you introduce the send call inside an *if (your boolean variable == true)*, it will only be executed in one loop iteration.

You can execute it again anytime you like setting the variable to true at any moment.

---
Tags: arduino-uno
---


title: Are there any KL03 "arduinos"?

text:
# Question
Title: Are there any KL03 "arduinos"?
I have been trying to find any Arduino or similar prototyping board that uses this MCU

http://www.pcmag.com/article2/0,2817,2453987,00.asp

But the smallest and more robust ones I have been able to find are Microduino and Espruino pico, none of which use this.

Are there any prototyping boards that use these?

# Answer
> 1 votes
This development board uses a chip from the KL03 family: http://www.freescale.com/webapp/sps/site/prod\_summary.jsp?code=FRDM-KL03Z

However, as you can see, it uses the arduino uno form factor (like all their other freedom boards), so it's probably not what you were expecting with respect of size.

If you are looking for a dev board that you can prototype with (easy access to pins and all that) I doubt you can get anything significantly smaller than a teensy (https://www.pjrc.com/teensy/), which also uses a more powerful ARM M4 core. There has been quite a few kickstarters with tiny arduino-compatible boards, but I am not quite sure how many you can actually buy at the moment.

---
Tags: hardware
---


# Question
Title: communicating with arduino over serial via terminal
I'm attempting to write data over a serial line to the arduino, however I don't want to use the arduino IDE but rather use the command line.

In order to do this I have the following commands:

```
$stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
$echo s123 > /dev/ttyACM0

```

The code on the receiving end checks whatever or not the input is s123 and if it is starts blinking. I have tested this using the arduino IDE and it worked, however this did not work.

The sketch looks like this:

```
    void loop(){
     if(Serial.available()==4){
       byte b1,b2,b3,b4;
      b1=Serial.read();
      b2=Serial.read();
      b3=Serial.read();
      b4=Serial.read();
        if(b1=='s'){
               digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
               delay(1000);               // wait for a second
               digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
               delay(1000);               // wait for a second
               digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
               Serial.println("the cow has landed");
          }
     }

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

```

the output of

```
stty -F /dev/ttyACM0 -a

```

was :

```
speed 9600 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W;
lnext = ^V; flush = ^O; min = 0; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts
ignbrk -brkint -ignpar -parmrk inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo -echoe -echok -echonl noflsh -xcase -tostop -echoprt -echoctl -echoke

```

Thank you

# Answer
> 0 votes
This was fixed this morning after a reboot and upgrade command, still don't know which one of these fixed it but it seems to work now.

Ah figured it out we were using the 0 and 1 rx gates to communicate over serial rather then usb and as the used power supply turned out to be only 5V rather then 9-12V it didn't quite work as intended.

---
Tags: serial, usb, linux, ubuntu
---


title: Is my TFT screen defective?

text:
# Question
Title: Is my TFT screen defective?
I bought the standard 1.77" TFT screen months ago and It has never worked. I follow the wiring diagram shown for Uno on the guide on the Arduino website and the best result I have ever got is it seeming like the screen itself is broken. I must have rewired the whole thing many times now and quadruple checked each time. As I have never used this screen before I do not know what is correct any further than the tutorial.

I say that because it seems to understand instructions but does not display them correctly.
I have tried multiple examples and tests on it that all yield weird results.
The tests I have tried are:

* The SD demo that loads the Arduino icon off SD and fills the screen with it. The serial connection says that it has successfully read the image but just displays black lines
* Setting the background colour with random colours which seems to work fine apart from the black bars
* Drawing random colour, positioned and sized rectangles. Result is image below. Colours seems to prefer pink, purple and white.

As you can see it looks like the image is 1D, no rectangles stop across the x axis so I did a test for that, it just draws a 1x1 pixel red dot going down the screen's left side, if it drew a red line moving down then my thought that it was stretching the first column would be correct, it didn't, just white and black bars still, so I modified it to test every column in case it wasn't column 0, same result...weirdly only when I made the 1x1px rectangle 5x5 my idea was correct.

As you can see on both the images, the black bars are a persistent factor, their colour cannot be changed and they appear once TFT.begin has been called.

After looking around the only help I could find is someone mentioned that Arduino the company updated the TFT library but not the software but he/she didn't provide a download link. In the time I've had this I'm sure I'm redownloaded/updated the Arduino software a few times too.

Are the glitches normal for wrong pin connections? Is there some pin wrong on the website?

# Answer
I ran into the same problem, looked around the net a bit. Someone found a solution from the Italian forums translated + posted how to help this.

In short there was something wrong with the TFT library https://forums.adafruit.com/viewtopic.php?f=25&t=45289#p228908

I installed the nightly build, currently 1.6.0 and the screen is working now.
> -1 votes

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


# Question
Title: collecting & visualizing sensor data - best approach?
I'm working on a kite-related project where I'm using Arduino + accelerometer to track data while a kite is in the air. I am struggling a little with the best approach - help on the following questions / issues would be a huge help:

-- how best to grab data only while the kite is in the air? just detect with numbers, use a switch? other ideas? -- how best to collect the data and transfer to computer for visualization (likely with processing but looking at other options). i'm using this project in workshops with kids in low-income neighborhoods in brazil, so will have limited resources. a laptop will be available -but use of mobile also ideal.

Thank you! Claudia

# Answer
Several possibilities; Both at little cost, but since you have an accelerometer, I know your budget is not 0.

1) use a shield with an SD card on the arduino to log the information to a file on the SD card. Open it later from a laptop or PC. Hopefully it will have enough room to store data that you can ignore later for pre-flight, post-flight time. If not, simply add some fixed delay to the start of your program (loop 5 times; wait 1 minute;)

2) some form of remote, like an XBee, or even a wireless WiFi Shield. The setup can be complicated but that would be ideal for real time visualization on a laptop at the flying site.

3) probably the easiest/least expensive - a cheap bluetooth transmitter.

eBay

This method would allow a bluetooth mobile to collect and visualize the data. This device connects to the serial lines on an arduino, (pin 0&1) and standard Serial.Write() function can be used. Any terminal program for your mobile will be able to receive the data. You could also get fancy and write your own if you want to visualize it. You may be able to find something already existing, like this

In cases 2 & 3 you will need a way to xmit the data. I use MQTT. A protocol just for this, but it is TCP only. I also use it with JSON (eg Json for Arduino to manage the data. You will need to find the same. Look at MQTT-SN as a possibility, or you can just write your own serialization protocol based around JSON without too much difficulty.
> 1 votes

---
Tags: accelerometer, communication, datalogging
---


# Question
Title: How to send Json to a webservice from pc/RPI with live data from Arduino(serial)
I'm making a project where my plan is to take sensor input from the Arduino, and then pass that info (by serial/usb connection) through either a laptop or a Raspberry Pi and convert it to Json and send it to a webservice in asp.net c#, where it gets stored in a database, and then the data can be shown on a website, so the visitor can see live data from the Arduino sensor on the site and also be able to see what the sensor measured yesterday, last month, or the average for a extended period of time, or a graph.

It might be easier to illustrate what I'm talking about:

The PC / RPI part is optional, it can be using either one.

There are a few options, as I see it, as to which methods could work. But I am unsure about how to implement them and what programs to use for it.

First one is to log data to a file on the PC/RPI and then have some shell script either listen for changes and then combine a Json string with the newly added info to the file and send it of to the webservice.

Second one is to somehow take the Serial data from the Arduino and have some shell script or program listen for any data coming from the Arduino and converting it to Json, and sending it of to the webservice. The pro's by this method would be omitting the extra "file-step", but it would make the system more vulnerable to any interruptions in the connection.

Does anyone have experience with doing something like this? Or maybe have an idea how I can do what I'm trying to do ? Or just a nudge in the right direction, as to which approach you think is best, or what programs I could/should use. Any help is very much appreciated!

Best regards Daniel

# Answer
I'm kind of tackling the same thing at the moment.

I have been using MQTT for a while for things like this. Including on an Netduino, an Arduino, and today a LEGO NXT.

But it is TCP based. I have been wanting to use serial, not TCP (ethernet) for a while, and when the need came for the NXT, it was time to write my own bridge to existing code.

I runs on the same host as the MQTT broker, but listens to a serial port, and mirrors the data to a TCP MQTT broker.

The code is turning out to be much simpler than I expected, I should have done this months ago.

Nxt Side

```
while (true)
{
    float x, y, z;
    DIMUreadGyroAxes(IMU, x, y, z);

    char json[128];
    sprintf(json, "PUBnxt/Gyro,{\"x\":%f,\"y\":%f,\"z\":%f}\n", x, y, z);
    nxtWriteRawHS(json, strlen(json), 0); // wireless serial over xbee
    wait1Msec(50);
}

```

PC side

```
 void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort p = sender as SerialPort;
        while (p.BytesToRead > 0)
        {
            string line;
            try
            {
                line = p.ReadLine();
            }
            catch (IOException)
            {
                throw;  // +++timeout
            }
            // parse it, it should be CMDtopic[,payload]
            if (line.Substring(0, 3).Equals("PUB"))
            {
                int commaIdx = line.IndexOf(',', 3);
                string topic = line.Substring(3, commaIdx - 3);
                string payload = line.Substring(commaIdx + 1);
                Console.WriteLine("{3}: {0}, publish topic({1}) payload({2})", p.PortName, topic, payload, DateTime.Now.ToLongTimeString());
                Mqtt.Publish(topic, System.Text.Encoding.UTF8.GetBytes(payload));

            }
            else if (line.Substring(0, 3).Equals("SUB"))
            {
                string topic = line.Substring(3);
                Console.WriteLine("{0}, subscribe topic({1})", p.PortName, topic);
                throw new NotImplementedException("MQTT Subscribe not implemented yet");
            }
            else
            {
                //Debugger.Break();   // ignore it, framing error
                Console.WriteLine("{0}, Data dropped", p.PortName);
            }
        }
    }

```

You might also want to look at data.sparkfun.com. A similar, complete concept, already existing.
> 1 votes

---
Tags: arduino-uno, serial, sensors, web-service
---