title: Maximum Current?

text:
# Question
Title: Maximum Current?
This is an extremely noobie question, but I have a 5V at 2A power source. This power source is going to be powering 6 Sharp IR distance sensors(20-150cm) and a few other low current consumption sensors(ie Xbee).

My question is if it is safe to simply use that power source without some sort of resistor between the power source and sensors?

also the IR sensors have a analog output. Is that same to plug into the arduino's analog pins?

# Answer
> also the IR sensors have a analog output. Is that same to plug into the arduino's analog pins?

If the sensors won't generate more than 5V, it should be safe. (Generally, they're all less than 5V. However, verify this...)

> My question is if it is safe to simply use that power source without some sort of resistor between the power source and sensors?

You probably don't need a resistor\*. Current is supplied on demand; if you need 1A but have a 2A supply, only 1A will flow. Voltage, however, is constant.

That being said, some parts will pull more current than they can safely use (like a LED, so *then* you would use a resistor.

This should all be found on the datasheet (especially with a more trusted brand like Sharp). Just look for example circuits and input voltage/forward voltage. A quick note, make sure to connect the grounds if you're not driving the Arduino directly from the power supply.

<sub>\*There probably is an internal resistor for the LED. Again, **datasheets, datasheets, datasheets!**</sub>
> 2 votes

# Answer
A few other points, in addition to Penguin's excellent answer:

Make sure your 5V supply is a REGULATED supply. Unregulated power supplies will exceed their target voltage when unloaded, and "droop" to lower than their target voltage when under heavy load.

Quite a few digital components can be destroyed if their input voltage varies too much from 5V, especially over-voltage. TTL is especially sensitive to over-voltage (which destroys the circuit) and to malfunctioning on under-voltage.

Even a regulated power supply will have some ripple if you switch heavy loads on it. You might want to use separate, isolated supplies for your high power and low power logic systems.

A higher current regulated supply will be "stiffer" and therefore more stable if run at lower loads.
> 4 votes

---
Tags: current
---


title: How do I set Grove GPS to use A-GPS?

text:
# Question
Title: How do I set Grove GPS to use A-GPS?
I am using a grove GPS http://www.seeedstudio.com/wiki/Grove\_-\_GPS

I attached the GPS to Serial1 of Arduino Mega 2560.

The baudrate of the GPS is set to 9600.

Library wise, I am using TinyGps to parse the GPS data.

The GPS receiver can only get a valid data if it can see a clear sky.

I read uBlox documentation and it states that I can use A-GPS.

So, my question is, how do I actually set the Grove GPS that is attached to my Mega, to use A-GPS?

# Answer
A-GPS uses a network connection to download GPS almanac and ephemeris data to enable satellites to be located faster. Otherwise the GPS device has to wait for the data to be sent by a satellite, which may take up to 12.5 minutes. Alternatively, the GPS device can send noise GPS data to an assistance server which will process it and send back a fix.

A-GPS requires a network connection to an A-GPS server. You can't just 'turn it on'. There are some modules out there that combine GPS with a 3G modem which do A-GPS automatically.
> 2 votes

---
Tags: arduino-uno, arduino-mega, c, tinygps
---


# Question
Title: Bit mask first 2 bits of 16 bits for accelerometer
The datasheet for the accelerometer states that:

Here is the data output from the accelerometer:

I have tried to mask the first two bits using a bitwise AND command with B0011111111111111.

I tried to use this code, but unfortunately the first 2 bits are still "11" so the value has not changed:

```
int bresult=0b0011111111111111&result;
Serial.print(bresult,BIN);

```

How would I bits mask the first two bits and will arduino automatically know how to convert to twos compliment?

The variable result is of data type "long"

According to an answer, I tried:

```
int bresult= result<<2;
Serial.print(bresult,BIN);

```

I got this result which is great but is it possible to remove the last two zeros because this is making my value larger? The image below shows result then bresult.

# Answer
Since it won't convert to two's complement if the sign bit is the 14 bit instead of the 16th, it would be easier to just shift the value left by 2. So

```
int bresult= result<<2;

```

Since `<<2` is the same as `*4` the result will be 4 times as high. So you need to divide the result by 4. Since you already have to multiply by `0.025` (or divide by 40), you end up having to multiply by `0.00625` (or divide by 160).
> 2 votes

# Answer
For the arduino, `long` is 32 bits, `int` is 16 and `char` is 8.

Save the result in an `int` not a `long`. Then Gerben's method `int bresult = (result << 2)/4` should work. This is because `<< 2` moves everything left two bits, but `/ 4` move every thing right two bits *with new bytes the same as the sign bit.* So you get a **16 bit** signed variable with the correct number. If you have it as a long you would have to do `int bresult = (result << 18)/(2^18)`.

BTW Serial.print(bresult,BIN); is always going to give you up to 16 bits. There is no 14 bit type.
> 0 votes

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


title: Changing direction of DC motor

text:
# Question
Title: Changing direction of DC motor
i am working on a project which requires changing the direction of the DC motor using arduino. that is I want the DC motor to rotate clockwise when i press key 'A' and anti clockwise when i press key 'D' on my computer.

i have v+ and v- input wires from battery. i have connected one end of the DC motor to gnd of the battery. On the other end of DC motor i want to connect V+ and V- input from the battery to spin the DC motor in clockwise and anticlockwise respectively. I have used BC547 npn transistor. i do not know how to change inputs (v+ to v- and vice-versa) using arduino when key is pressed.

is there any method other than H-bridge method to do so?

i use arduino uno.

# Answer
> 1 votes
Since you have both a V+ and V- you could just use 2 transitors. If you look at an H-bridge, you only need half the circuit.

The only problem is that you need V- to disconnect the NPN transistor, and the arduino can only go as low as GND. So you'd need a second transistor to drive it.

The same might also be needed for the PNP side, if the arduino voltage is regulated to a lower value than V+.

I found this schematic applicable, but only use the left side. The right side of the motor should be connected to ground (or the middle voltage of your battery). , and replace the opto's with normal transistors.

Come to think of it, I'm not entirely confident about replacing the bottom opto, since battery-negative is below GND in your case. I think it should work, but I'm still quite new to this stuff.

Also make sure you add something like 1k resistors to the base of the transistors (that replace the opto's)

# Answer
> 0 votes
L298 IC is very popular way of doing it. IN1 IN2 to control direction, open circuit and breaking (short circuit of motor terminals). EN1 for PWM speed control.

Ready made module PCB widely available.

useful info https://www.sparkfun.com/products/9670

http://forum.arduino.cc/index.php/topic,84439.0.html

Hope it helps.

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


title: Arduino Yun, node.js and serial

text:
# Question
Title: Arduino Yun, node.js and serial
I'm trying to bypass Bridge library and read serial directly from nodejs. I'm on the last sys upgrade (1.3) I have correctly installed nodes and serial module via opkg install. I have also commented out the line in the `/etc/inittab`:

```
#ttyATH0::askfirst:/bin/ash --login

```

This is my arduino code:

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

void loop() {
  Serial.println("dudee");
  delay(100);
}

```

This is my node.js code:

```
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyATH0", {
    baudrate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
}, false);

console.log("hello");

serialPort.on("open", function () {
    console.log('open');
    serialPort.on('data', function(data) {
        console.log('data received: ' + data);
    });
});

serialPort.on('error', function(err) {
    console.log('error: '+err);
});

serialPort.open();

```

If I ssh to yun and run the script I don't see any "dudee":

```
~/test# node serial.js
hello
open

```

While if I open the serial monitor I see it.

If I run the node script on my computer (changing the right serial port name) everything works nice and I see the dude..

What can it be?

# Answer
Autosolved thanks to this old forum post.

It is `Serial1` not `Serial`. In the Arduino code in the Yun `Serial` is a different object from `Serial1`. Even if it is not super well document (or at least not in the first dumb google search) here are some links that talks about `Serial1`:

https://www.arduino.cc/en/Tutorial/YunSerialTerminal http://andrea-toscano.com/arduino-yun-tcpip-to-serial1-redirect/ http://crossbar.io/iotcookbook/Arduino-Yun-Disable-Bridge/
> 2 votes

---
Tags: serial, arduino-yun
---


title: Is i2C more or less robust than GPIO?

text:
# Question
Title: Is i2C more or less robust than GPIO?
Currently using i2C to connect a RPi with an arduino. It seems i2C is quite finicky and, drops the bus immediately if there are any IO errors. Since what i am building is meant to be semi permanent, I am worried that i2C may not be the best choice.

Has anyone done any real world testing of i2C vs GPIO for RPi to arduino communication?

# Answer
> 1 votes
Here are a few things to remember:

* You should have a ground connection between the RPi and Arduino
* I2C was meant for really short distances on a printed circuit board
* Arduino runs at 5 Volt logic levels and RPi at 3.3 Volt logic levels - you need a level translator between them to make that work.

If the RPi and the Arduino are not far apart, I would say less than 1 foot (30 cm) and you have the grounds connected between the boards, then it is a software issue. I2C is meant for short distances any anything longer than a foot puts too much capaitance on the wires and starts causing unreliable communication. I would not even use it for more than a few inches unless it was on a circuit board where you control the capacitance.

I am assuming your using the Wire library on the Arduino side. On the RPi side I would use the the Adafruit I2C library for the RPi as I have had success using the library to communicate with I2C sensors listed on their site. Here is the link:

Adafruit RPi I2C Tutorial

---
Tags: pins, i2c
---


# Question
Title: How can I get two Arduinos to "talk" to each other?
I'm pretty new to this whole thing so please excuse my lack of familiarity with terminology.

I'm looking to build two "buzzers" of sorts. One will live on the ground floor and the other will live on the fourth floor. There is wireless internet as well as wired internet available to connect the two.

This is the basic idea. I might put more frills in later. Both buzzers have one button and one LED. I want it so that once a buzzer's button is pressed, the LED lights on both buzzers will light up. Then, only when buzzer two's button is pressed, will the LED lights on both buzzers turn off.

I'm pretty tied up on the two Arduinos communicating with each other. Is it possible to do something like that?

# Answer
**Wired**

Communication speed is not a factor - you only have to transmit an on/off signal. The simplest method would be to run a 4-wire cable, like a telephone cable, between the two.

The wires would be

1. GND
2. 5V (maybe)
3. Ground floor output -\> fourth floor input
4. Fourth floor output -\> ground floor input

The steps are

* Both wire 3 and 4 start LOW When ground floor button is pressed, ground floor led goes on, wire 3 is set HIGH.
* Fourth floor is monitoring wire 3, when it goes HIGH, fourth floor led goes on, and wire 4 is set HIGH
* Ground floor is monitoring wire 4, when it goes HIGH, ground floor led goes off, and wire 3 is set LOW
* Fourth floor is monitoring wire 3, when it goes LOW, fourth floor led goes off, and wire 4 is set LOW
* Ground floor is monitoring wire 4, when it goes LOW, it begins waiting for a button press again.

Wire 2 can be used for 5V (or 3.3V depending on the Arduino) so that one of the devices can be powered off the other.

**Wireless**

The other option is to attach an RF transceiver to each Arduino, something like this would be good as it has 100m line-of-site range which you might need to get through 4 floors of concrete.

**Learning**

Start off with the simple wired method shown above. When it is working, connect wire 3 and 4 into the RX and TX pins and try to communicate using the serial port. Finally, move on to the wireless transceivers.
> 3 votes

# Answer
Benefits of a networked device:

* Fairly fast because it has to be able to transfer large amounts of data
* Can be compatible and used with computers, servers, and mobile devices. You might also only have to have one Arduino (if the second one would only be acting as a bridge between the protocol and the computer)
* Why *wouldn't* you want to have a networked Arduino :)

So that rules out the protocols I2C, UART, and SPI. I find Bluetooth too hard to work with (it seems to have only a short range) using an Arduino. That leaves us with Wifi, wired network connection, and USB. USB would be best if you could run a short wire, but most USB peripherals aren't really designed to be used 100 feet away from the computer.

With ethernet and Wifi left, I'm going to advise you to go with a wired connection if possible. Benefits of keeping it wired:

* Even *faster* (with lower latiencies)
* Lower cost to interface with
* More reliable than Wifi
* No pesky Wifi passwords

**tl;dr:** Without a ton of info, **wired internet** (a.k.a. ethernet) seems to be the best choice. Other wireless options don't provide the distance you need and you (probably) can't run a wire with another protocol.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Unable to send data from Processing to Arduino through ports
I'm just beginning to use Processing along side with Arduino and need help linking the two. Just to get started, I just wanted to send a single character (eventually strings) to the Arduino and have the Arduino light up a matrix if the Arduino receives the data.

Here's my code for the Arduino (I'm using an Arduino Uno):

```
#include <Adafruit_GFX.h>   // Core graphics library
#include <RGBmatrixPanel.h> // Hardware-specific library

// Set up the matrix
#define CLK 8
#define LAT A3
#define OE  9
#define A   A0
#define B   A1
#define C   A2
RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);

int incomingByte = 0;   // for incoming serial data

void setup() {

  Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  matrix.begin();
}

void loop() {
    if(Serial.available() > 0) {
    incomingByte = Serial.read();

    // Print a white "Done!" to the matrix
    matrix.setCursor(1, 0);
    matrix.setTextSize(0);
    matrix.setTextColor(matrix.Color333(7, 7, 7));
    matrix.print("Done!");

  }
}

```

And here's the code for Processing:

```
// Example by Tom Igoe

import processing.serial.*;

// The serial port:
Serial myPort;

// List all the available serial ports:
println(Serial.list());

// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[1], 9600);

// Send a capital "A" out the serial port
myPort.write(65);

```

I run the processing sketch and then upload the code to the Arduino, but get nothing. The Arduino is using COM3 and I believe the Processing sketch is too, but that may be where I'm messing up.

If I open up the serial monitor and send some data to the Arduino that way, then the LED lights up fine, but only when I do it through that.

Any help would be appreciated. Thanks!

# Answer
> 1 votes
When you open a serial connection to Arduino Uno the atmega328 microcontroller is usually reset(this depends if the OS is configured to toggle the DTR serial control signal on/off when a port is opened). Just after a reset the bootloader (optiboot) runs to see if you are trying to upload a new sketch. If the bootloader doesn't receive any meaningful communication it will start your sketch after ~1 sec. All communication sent to the serial port while the bootloader is running is lost.

When you use the serial monitor you are too slow to notice the 1 second where the board won't respond to your commands. But the processing sketch is another story.

The easiest fix will be to insert a delay after you open the serial port and before you send any data.

```
// Wait 1.2 sec
int start = millis();
while (millis() - start < 1200);

```

---

If you would rather use a hardware fix you can connect a 10uF capacitor between RESET and GND pins that will prevent the board from being reset by the usb to serial converter.

---
Tags: arduino-uno, serial, uploading, led
---


title: How to use two Sonar's

text:
# Question
Title: How to use two Sonar's
I'm using a single sonar, but I want to use two sonar to know another distance.

Here is how I use my single sonar:

```
    #include <NewPing.h>

    #define TRIGGER_PIN  9
    #define ECHO_PIN  10
    #define MAX_DISTANCE  100 // in CM
    ...
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
    ...
    delay(100);
    unsigned int uS = sonar.ping();
    int cm = uS / US_ROUNDTRIP_CM;

```

But I Want to use a second one to calculate another distance, how to?

```
#define TRIGGER_PIN_2  11
#define ECHO_PIN_2  12
...
new NewPing sonar(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE);
...
???

```

Thanks in advance

**EDIT:**

Maybe this one, I'll try this when I will get my second sonar

```
#define SONAR_NUM     2
#define MAX_DISTANCE 200
...
NewPing sonar[SONAR_NUM] = {
  NewPing(9, 10, MAX_DISTANCE),
  NewPing(11, 12, MAX_DISTANCE)
};
...
delay(100);
unsigned int uS1 = sonar[0].ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar[1].ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

```

# Answer
> Maybe this one, I'll try this when I will get my second sonar

*Ding ding ding!* Yeah, this would be one way to do that. That creates an *array* so you can reference the sonar with `sonar[i]`, where `i` is either 0 or 1 for the first or second number.

For only two sensors, it might be easier just to do something like this:

```
NewPing sonar1(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

```

Then you can run the other code like this:

```
delay(100);
unsigned int uS1 = sonar1.ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar2.ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

```

A little less code to read, whichever one you want.

The reason you can do this is you can replace the `sonar` with whatever you wanted (following C++ variable rules like no spaces, etc.). You could call it `Arduino_Sonar` if you wanted to.

The array is basically a simple way of grouping variables together easily. It's not convenient to declare 500 differently name variables; I can just do `int numbers[500];` to declare them. An array might be more useful if you're expanding your circuit, but either is correct.
> 5 votes

---
Tags: arduino-uno
---


# Question
Title: Unstable reading from pushbutton on digital pin
I use the Pin 7 to get the status of a push button. I put 10Kohm R on the - .

The status is unstable because arduino says thet I push it but it is not true...

```
int button = 7;
...
// var for reading pushbutton value
int buttonState = 0;
...
buttonState = digitalRead(button);
  if(buttonState == HIGH)
  {
    myFunction();
  }

```

**EDIT :**

ARDUINO PIN 7 \<---\> R 10Kohm \<--\> \[switch\] \<---\> VCC

# Answer
> 10 votes
At the moment, your resistor isn't doing anything useful. When your switch is open, the pin is still 'floating', which means it's ending up with random stray readings from nearby electromagnetic fields.

You basically need two connections coming from your Arduino pin. One goes through a resistor straight to ground. The other goes through your switch straight to +5V.

In that case, the resistor is acting as a pull-down, because it holds your pin at Ground whenever the switch is open. You could swap over the ground and +5V, and it the resistor would function as a pull-up instead.

This question deals with the same kind of issue:

# Answer
> 7 votes
Note that you can also activate the internal pull-up resistor on the pin by first making it an input, then setting it to HIGH.

```
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);

```

### EDIT:

Based on info from Craig (in the comments below) it's simpler to use the new pinMode INPUT\_PULLUP:

```
pinMode(pin, INPUT_PULLUP);

```

Then wire the switch directly to ground.

This is the simplest way to wire a pushbutton to an arduino (no resistor needed) but **do** you need an extra line of code.

Also, the pin will read as HIGH when not pressed, and LOW when pressed (which might seem counter-intuitive)

---
Tags: arduino-uno
---


# Question
Title: Arduino uno + XBee Shield Not transmitting when under battery power?
I have a few Arduino's along with XBee Shields communicating with one another.

The problem I'm having is that, when all the Arduinos+XBee Shields are powered via USB(PC) they seem to work fine and all transmissions get through to one another. But, when I use them with 9Volt batteries(fairly new batteries) the whole thing crashes and I never receive responses back from the battery powered ones.

I'm wondering if this is really a power issue? wouldn't a 9volt be enough to power a single arduino(uno)+xbee shield?

# Answer
> 1 votes
Using a multimeter you can confirm your theory by looking for a voltage drop on the power connections to the XBee and into the UNO.

9V batteries don't store much charge, nominally 563mAh according to wikipedia. It is possible that the fairly new batteries are not that new after all.

Depending on the XBee, power consumption varies. 40mA for a normal XBee (ZigBee), 200mA for pro, and 309mA when transmitting for the new XBee WiFi. If the battery is low, the high current draw plus internal battery resistance may drop the 9V output to below the 7V needed for the UNO's voltage regulator to function correctly.

# Answer
> 0 votes
The usb port on your computer can supply about 500mA of current. If geometrikal is correct about the 563mAh and you are using an XBee pro or a higher current draw radio, you could easily be hitting the current limit of the battery. Another aspect of this is the internal resistance of the battery. I'll let you read about it, but it is another current limiting factor. All of this boils down to once you are drawing more current than the battery can provide the voltage drops. Once it gets down to below what the Arduino board can regulate the microcontroller will reset.

# Answer
> 0 votes
Is space an issue? Have you considered using 6 AA batteries? From what I've read basically the current provided by a battery is determined by it's size so C is bigger than AA which is bigger than AAA.

The 9volt battery is from what I understand made up of 6 AAAA cells and therefore has a much lower maximum current. about 563mAh rather than about 1500mAh depending upon the type you choose.

---
Tags: arduino-uno, shields, power, xbee
---


# Question
Title: Arduino gets stuck: battery powered, wireless, dc motor drive
I have a Arduino Mega 2560 connected to

1. L293D Motor Driver IC connected to two small size dc motors.
2. MPU-9150 using i2c
3. Xbee v1.1 arduino shield by seeed
4. Li-po battery, 7.4 volts, 2200 mah.

All components are tested separately, they all are working fine, the sensor readings showing data on serial monitor, the l293 drives the motors, xbee sends wireless serial data on pc, and li-po is also working fine.

I have checked the wiring alot of times. It all seems to be correct.

The problem arises when i connect all of them together, since I am using a single power source, I power the l293d with the Li-po and the Arduino also with the Li-po.

1. When the L293D is powered using Li-po and it starts drawing current from the battery, the serial monitor/arduino gets stuck. It doesnt show sensor readings anymore, while the dc motors start spinning. And they continue to spin, until I break connection with the battery.
2. Without the l293d powered, the sensor readings are working fine, everything is going normal, as it should, but as soon as the l293d is connected, arduino is stuck..

I have searched alot of forums for this, found some info, perhaps something to do analog and digital ground? mpu-9150 is digital ground. So that is why it stops the arduino mega as the l293d starts drawing current. All hell breaks loose.

Can anybody please help me with this? it is giving me headaches ever since!

# Answer
My guess is that your motors are drawing too much current and the voltage from your battery is dropping too low for the voltage regulator on the Arduino. Looking at the data sheet, the L293D will provide up to 600-mA for up to 2 motors at a time. That's up to 1.2 amps, a whole lot of current. I would suggest trying to power your arduino from a separate 9 volt battery as an experiment.
> 2 votes

---
Tags: serial, sensors, current
---


# Question
Title: MCU Type ATmega16U2 not avaliable in Eclipse AVR Plugin
I am following this guide. Now I want to create the Create the "ArduinoCore library". But when I am creating a new project, I can not select ATmega16U2 as MCU type.

But my Arduino Due R3-E and UNO SMD R3 both use ATmega16U2.

What shall I do O\_o???

# Answer
> 5 votes
The `ATmega16U2` on those boards isn't intended to be programmable by the end-user. It's only there to help convert from USB to TTL serial, which lets your computer communicate with the board's main microcontroller. It replaces the FTDI chip which was used on some older boards.

In the case of the Uno, the main microcontroller is the `ATmega328`. For the Due, it's the `AT91SAM3X8E`. If you want to program them from the Arduino IDE, you can usually just select the board by name from the drop-down menu.

---
Tags: arduino-uno, arduino-due, eclipse
---


# Question
Title: 9 DoF Sensor Accelerometer Readings Inconsistent
I have the following sensor stick: https://www.sparkfun.com/products/10724

It has an accelerometer, gyroscope, and magnetometer.

I have connected it to an arduino and am reading the accelerometer values while the sensor is completely flat and the values jump all over the place:

ie 0 2 3 7 -5 12 35 -3 ...

This is how I am reading them:

```
void Accel_Init()
{
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x2D);  // Power register
  Wire.write(0x08);  // Measurement mode
  Wire.endTransmission();
  delay(5);
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x31);  // Data format register
  Wire.write(0x08);  // Set to full resolution
  Wire.endTransmission();
  delay(5);

  // Because our main loop runs at 50Hz we adjust the output data rate to 50Hz (25Hz bandwidth)
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x2C);  // Rate
  Wire.write(0x09);  // Set to 50Hz, normal operation
  Wire.endTransmission();
  delay(5);
}

// Reads x, y and z accelerometer registers
void Read_Accel()
{
  int i = 0;
  byte buff[6];

  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x32);  // Send address to read from
  Wire.endTransmission();

  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.requestFrom(ACCEL_ADDRESS, 6);  // Request 6 bytes
  while(Wire.available())  // ((Wire.available())&&(i<6))
  {
    buff[i] = Wire.read();  // Read one byte
    i++;
  }
  Wire.endTransmission();

  if (i == 6)  // All bytes received?
  {
    // No multiply by -1 for coordinate system transformation here, because of double negation:
    // We want the gravity vector, which is negated acceleration vector.
    accel[0] = (((int) buff[3]) << 8) | buff[2];  // X axis (internal sensor y axis)
    accel[1] = (((int) buff[1]) << 8) | buff[0];  // Y axis (internal sensor x axis)
    accel[2] = (((int) buff[5]) << 8) | buff[4];  // Z axis (internal sensor z axis)
  }
}

```

Am I doing something wrong that these values aren't the same?

# Answer
In 'FULL\_RES' mode the number you get is amount of 4mg units.

So 1 is 4mg, 2 is 8mg, -4 = -32mg.

Also note that your current code doesn't interpret the first bit (so the 13th from the right) as the sign bit, so you'll never get negative values. (Question related to this)

PS I think it is actually more like 3.9mg.
> 2 votes

---
Tags: arduino-uno, i2c, accelerometer
---


title: Leonardo: disable TX- and RX-LED

text:
# Question
Title: Leonardo: disable TX- and RX-LED
I have the (more or less) Leonardo-compatible board Olimexino-32u4. Both, the TX- and RX-LED are permanently on. To reduce power-consumption, I want to disable them **by software**. What is the reliable way to do it?

# Answer
> 3 votes
Try adding this to your setup routine:

```
TXLED0;
RXLED0;

```

These macros (and their cousins TXLED1, RXLED1) are used to control the TX an RX LED's on Leonardo. They are defined in https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/variants/leonardo/pins\_arduino.h#L95-L98

---

If that doesn't work you can try the solutions suggested here: http://forum.arduino.cc/index.php?topic=145262.0

# Answer
> 7 votes
Reading the answer from Gerben I realised the core of the issue: The TX/RX LED's on the Leonardo are wired PIN-LED-5V(common anode), whereas on the Olimexino-32U4 they are wired PIN-LED-GND(common cathode). So the two boards will need inverse signals for the same visual output.

Compare:
http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic\_3b.pdf
https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4\_rev\_A3.pdf

---

The most elegant solution will be to add a new board type (the code below is for IDE 1.0.x):

* In your sketchbook create a folder 'hardware' and inside that 'olimexino'. In the olimexino folder create a file boards.txt with this content:

```
olimexino32u4.name=Olimexino-32U4
olimexino32u4.upload.protocol=avr109
olimexino32u4.upload.maximum_size=28672
olimexino32u4.upload.speed=57600
olimexino32u4.upload.disable_flushing=true
olimexino32u4.bootloader.low_fuses=0xff
olimexino32u4.bootloader.high_fuses=0xd8
olimexino32u4.bootloader.extended_fuses=0xcb
olimexino32u4.bootloader.path=caterina
olimexino32u4.bootloader.file=Caterina-Leonardo.hex
olimexino32u4.bootloader.unlock_bits=0x3F
olimexino32u4.bootloader.lock_bits=0x2F
olimexino32u4.build.mcu=atmega32u4
olimexino32u4.build.f_cpu=16000000L
olimexino32u4.build.vid=0x2341
olimexino32u4.build.pid=0x8036
olimexino32u4.build.core=arduino:arduino
olimexino32u4.build.variant=olimexino32u4

```
* Create another folder 'variants' inside the olimexino folder.
* Inside that, create the folder 'olimexino32u4'.
* Now copy 'arduino/hardware/arduino/variants/leonardo/pins\_arduino.h' to that folder
* Open the copy for editing - the path should be 'sketchbook/hardware/olimexino/variants/olimexino32u4/pins\_arduino.h'.
* Change the section that deals with TXLED and RXLED by swapping the macros that end in 1 with those that end in 0. It should look like this:

```
#define TX_RX_LED_INIT  DDRD |= (1<<5), DDRB |= (1<<0)
#define TXLED1          PORTD |= (1<<5)
#define TXLED0          PORTD &= ~(1<<5)
#define RXLED1          PORTB |= (1<<0)
#define RXLED0          PORTB &= ~(1<<0)

```

I don't own the board so I can't test the solution. I hope that it solves your problem - just choose 'Olimexino-32U4' from the Tools-\>Board menu.

# Answer
> 1 votes
The TXled is connected to physical pin 22, or PD5. RXled is connected to pin 8, or PB0. They are connected to the cathode of the led, so they have to be HIGH to turn **off** the leds.

To turn them HIGH use:

```
PORTD |= (1<<PORTD5);
PORTB |= (1<<PORTB0);

```

Not sure what the firmware does, and if it sets the leds back to low every once and a while. So in addition I would suggest also setting those pins to inputs.

```
DDRD &= ~(1<<DDD5);
DDRB &= ~(1<<DDB0);

```

---
Tags: arduino-leonardo
---


title: Arduino Mega - get mac adress

text:
# Question
Title: Arduino Mega - get mac adress
I am new on Arduino, and I am trying to use the Ethernet shield...

but it need:

* IP adress
* MAC adress

IP adress is easy to get... but not MAC..

how can I get my arduino MAC adress?

# Answer
> 3 votes
A MAC address must be unique throughout the environment in which it operates, but apart from that is largely arbitrary. Typically the problem is solved by selling 3-octet prefixes (called OUI's) to manufacturers, who then uniquely assign the remaining 3 octets to individual device units they manufacturer.

However, if you are unable to discovery a globally unique address assigned to your device by its manufacturer, and know that its traffic will be confined to a local network, you can use a privately assigned (ie, "made up") address with the **Locally Administered** bit set. An address of the form

```
02-xx-xx-xx-xx-xx-xx

```

or any other with the 2's bit of the first octet set will satisfy this criteria as long as you guarantee that it is unique in your system.

Be especially careful not to set the 1's bit of the first octet - if you do so, traffic will be marked as broadcast and so given wider distribution/attention than needed, wasting network capacity and processor time of connected devices.

# Answer
> 1 votes
Arduino doesn't have a MAC address, your Ethernet adapter shield however will. The MAC address is likely printed on the interface and is constructed from 12 hexadecimal numbers, usually grouped 2 hex digits at a time.

If it isn't printed on the box or the shield, then the only way to find out is to connect it to your network, configure a valid IP address on the shield and try to connect to it (eg. ping to the address) from your PC) Then you can list MAC addresses from your PC with `arp -a`.

Or when using dynamic addresses and DHCP, you can find the mac address in you DHCP server (probably your home router).

Either way, you need a sketch on your Arduino to configure an IP address.

# Answer
> 1 votes
> Current Ethernet shields come with a sticker indicating the MAC address you should use with them.

(source)

---
Tags: ethernet
---


title: Arduino amplifier

text:
# Question
Title: Arduino amplifier
I want to drive my model trains (märklin) with my arduino UNO, it requires 32 watt (`0-12/24v, 2A MAX(changes)`) This is Direct current

How can I amplify the output of the arduino to get my 32 watt?

# Answer
You certainly can. For relatively small amplifications, you can use transistors. MOSFETs are similar and work well for larger solid state amplification. If all you need is to turn power on or off (no switching faster than ~20Hz) a relay is you best bet, but most standard ones take more power than a raw arduino output can provide so you have to buy one for this purpose. They are all easy to use, for the most part just plug in ground, power, signal, and signal out. You can look up any of these for more details on use, it should not be hard to find.

The easiest pre-built solution is something like this relay board: http://www.sainsmart.com/arduino-compatibles-1/relay/arduino-pro-mini.html
> 1 votes

# Answer
This company, among others, has a range of drivers, meeting your volt/current/PWM speed control requirements, with good documentation, manual and use examples. http://www.pololu.com/category/11/brushed-dc-motor-drivers
> 0 votes

---
Tags: arduino-uno, voltage-level
---


# Question
Title: Moving an item on a pole, can an Arduino work for my project?
I'm a computer programmer, but I've never done anything with Arduino. I'd like to build something that holds a polisher (this one, in specific: http://www.homedepot.com/p/BLACK-DECKER-6-in-Random-Orbit-Waxer-Polisher-WP900/202516385) on a metal pole, and moves the polisher up and down (vertically) on the pole at varying speeds (I'd like to use arduino to control the motor/speed)?

Is this the sort of thing Arduino would be able to do? If so, can anyone point me to any motors that would work? If not, any tips on where else I should look?

# Answer
> 2 votes
I am also a software guy by profession. I've always liked tinkering with electronics, and have recently gotten into Arduino. It is an excellent platform for developing hybrid hardware/software solutions for problems like this. It is very easy to use, both hardware and software.

There is a large ecosystem of add-ons called "Shields" that just plug in. You can probably find a motor control shield that will do exactly what you want.

Your biggest challenge, I think, is going to be mechanical. How will you hold the polisher in position, and make a mechanism that will raise and lower it?

Off the top of my head what I come up with is a U shaped metal bar with a threaded rod in the opening of the U. You'd build a "sled" that would grip the bar and would have teeth that would grip the threaded rod. Then your would have a motor on the end of the assembly that would turn the threaded rod to move the sled up and down on the bar. You'd attach the polisher to the sled. You'd probably need a spring or rubber holder so that the polisher would press gently on the surface being polished but with some freedom of motion.

---
Tags: motor, hardware
---


# Question
Title: Help with wiring? Fritzing example inside
I am trying to prep my wiring for a 8x8 Led Matrix w/ Bluetooth according to the following instructable:

http://www.instructables.com/id/Arduino-SPI-7-Bi-color-LED-Matrix-Scrolling-Text-D/?ALLSTEPS

Instead of soldering everything together I'd much rather use a breadboard. I'm new to wiring, breadboards, and Arduino's in general. I was wondering if anyone could look over my sketch and see that the connections I've made are valid.

I'm basing my wiring off this image (See original instructable for higher resolution):

I realize the bluetooth module isn't the same. I'm just using this as a reference. The wires leading off the top of the board will be going to the LED Driver module.

EDIT: Thanks for the feedback guys. I have decided to go with the Innogear HC-05 module. I've adjusted the wiring according to that model. As per the suggestions, I've switched my power and ground rail and eliminated the resistors and ground for TX communication. (I've still kept a ground for the BT). Here's my new attempt:

# Answer
> 2 votes
I am the author for the Instructable ethanx94's wiring is based on. It seems like the active and helpful members here have already helped iron things out.

If anyone is using the Arduino sketch downloaded from my instructable but is using ethanx94's wiring, do remember to change the SPI SS (Slave Select) pin in the sketch from 10 to 53 to reflect the correct pin used.

Look for the following line in the sketch and change the pin number 10 to 53:

```
int SPI_CS = 10;// This SPI Chip Select pin controls the MAX7219

```

```
int SPI_CS = 53;// This SPI Chip Select pin controls the MAX7219

```

# Answer
> 1 votes
Those are, in fact, the same board. When you look at this image (from Amazon)...

>

...you can see that there are really six pins, just two of them aren't soldered.

---

**Your circuit:**

* On the power rails, you have the 5V and ground switched. It'll work okay, but you're asking for trouble later on when trying to work with it and accidentally plugging a wire into the wrong rail.
* Also, from the reviews on Amazon, it says that it can be powered with 5V since the breakout board provides voltage conversion. However, no one specifically mentions the TX/RX, so I'd not risk it. This module (seems to be same chip) costs less and a reviewer specifically says that it converts voltage for both power *and* the TX/RX.
    + I'm not going to verify the resistor values, since you don't seem to need them if you get the other module I listed.
    + If you still did want to do the 5V/3.3V conversion, you should connect the power wire to the 3.3V pin, not the 5V rail on the breadboard

**tl;dr:** it seems as you just need to skip the resistors for the yellow wire and make a direction connection. I'm not 100% sure about *that specific part* but there was another one that a reviewer specified that this was okay.

Note: I cannot comment on the other wires for the shields, but at a quick glance it looks good.

---
Tags: led, bluetooth, wires
---


title: MakeyMakey + Arduino

text:
# Question
Title: MakeyMakey + Arduino
I am trying to use the MakeyMakey with the Arduino (not as an Arduino) and then use a USB to TTL module to send the keys pressed to the Arduino. Is this possible? Do I have to reprogram?

# Answer
> 0 votes
one possibility is to use HOST SHIELD http://www.circuitsathome.com/products-page/arduino-shields

Arduino is now as host Makey is keyboard

---
Tags: arduino-uno
---


# Question
Title: Can I use an external power supply and still communicate with my computer over Serial?
I read the following online: If you plug in both USB power (say from a pc) and external power via the 2.1mm jack, the Arduino chooses power source automatically.

If the external 2.1mm DC is providing greater than 6.6V, the Arduino will take power from it instead of the USB.

Firstly, is this accurate?

Secondly, my real question: If I am powering my Arduino via external DC, can I still communicate with my Raspberry Pi using serial via the USB?

# Answer
Yes you can. It still leaves the data/ground lines intact, it just doesn't bridge the 5V line.

Arduino Uno Schematic v.3:

The `USBVCC` is directly from the 5V on the USB jack (well, technically there's a fuse there). It then goes through a transistor (`T1`) that only allows power through when there is no power coming from the 5V regulator (that regulates the VIN voltage).

*The USB jack:*

You can see pin 1 of the USB jack (5V) goes through the fuse to `USBVCC`. The next ones `D+`/`D-` are the data lines that go through resistors to the ATMEGA16U (used for USB to UART). The last one just ties into ground.
> 10 votes

---
Tags: serial, power
---


# Question
Title: Sending MPU6050 data over serial to Java/C# Program
I am using a MPU6050 Accelerometer/Gyro breakout (GY-521) to retrieve data and send it to a java program. I have tried several ways, but I couldn't find a way to send the float values calculated from the Arduino over Serial. Could you please let me know a good way of serial communication with Arduino and a Java Program? Thanks in advance.

***UPDATE***:

Thank you for your comments and replies. What I have tried is the I2Cdev library code. I could work with it without any issue. Code is in this link. I also could run the processing code to get a visual output. But the problem I have i that I'm not able to send the accelerometer and gyro data to a Java/C# program and process it from there. I tried sending an array of FIFO bytes from the Arduino and convert it from the C# code and processing code, but it didn't give me correct results. Now what i did was, just to send a string of values and receive it from the C# program. But I don't know whether it's good method. I would be glad if you could help me in this. Thanks again.

**Arduino**

```
#ifdef OUTPUT_TEAPOT
        // display quaternion values in InvenSense Teapot demo format:
        teapotPacket[2] = fifoBuffer[0];
        teapotPacket[3] = fifoBuffer[1];
        teapotPacket[4] = fifoBuffer[4];
        teapotPacket[5] = fifoBuffer[5];
        teapotPacket[6] = fifoBuffer[8];
        teapotPacket[7] = fifoBuffer[9];
        teapotPacket[8] = fifoBuffer[12];
        teapotPacket[9] = fifoBuffer[13];
        Serial.write(teapotPacket, 14); //Serial.write(buf, len)
        teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
    #endif

    #ifdef OUTPUT_ACCEL_STR_RAW
        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        String accelGyroRaw = "STX,";
        accelGyroRaw += ax;
        accelGyroRaw += ',';
        accelGyroRaw += ay;
        accelGyroRaw += ',';
        accelGyroRaw += az;
        accelGyroRaw += ',';
        accelGyroRaw += gx;
        accelGyroRaw += ',';
        accelGyroRaw += gy;
        accelGyroRaw += ',';
        accelGyroRaw += gz;
        accelGyroRaw += ',';
        accelGyroRaw += "ETX";

        Serial.println(accelGyroRaw);

    #endif

```

**C# Code**

```
class Program
{
    static SerialPort port = new SerialPort("COM7", 115200);
    //static int serialCount = 0;
    //static int aligned = 0;
    //static char[] teapotPacket = new char[14];
    //static float[] q = new float[4];

    static void Main(string[] args)
    {

        Console.WriteLine("****** Serial Console Read ********");
        port.Open();
        port.DataReceived += port_DataReceived;

        Console.Read();
    }

    static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        string s = port.ReadLine();
        string[] accelGyroVals = s.Split(',');
        string[] accl = new string[3];
        string[] gyro = new string[3];

        if (accelGyroVals[0] == "STX" && accelGyroVals[accelGyroVals.Length - 1] == "ETX\r")
        {
            accl[0] = accelGyroVals[1];
            accl[1] = accelGyroVals[2];
            accl[2] = accelGyroVals[3];

            gyro[0] = accelGyroVals[4];
            gyro[1] = accelGyroVals[5];
            gyro[2] = accelGyroVals[6];

            Console.WriteLine("a : " + accl[0] + " , " + accl[1] + " , " + accl[2] + "\t g : " + gyro[0] + " , " + gyro[1] + " , " + gyro[2]);
        }

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        if (port.IsOpen)
        {
            port.Close();
        }
    }
}

```

Sorry for this for lengthy code and if my question is unclear. It's my first time to work with an IMU. Thank you.

# Answer
> 1 votes
You may find RXTX java library helpful.

You can format the data (float as calculated at Arduino side) in any mannner that you desire. RXTX library will send the data. It will then up to the Java program (non Arduino side, like PC, etc.) how to interpret the data and extract the values.

http://playground.arduino.cc/interfacing/java

Hope this helps

---
Tags: serial, programming, arduino-mega, mpu6050
---


# Question
Title: Problem with interpretting and using the IMU data
I am using MPU6050 IMU for getting accelerometer and gyro data. I could read the data using the code from the I2Cdev library here, but the problem I have is that I can't use this data in a meaningful manner. As an example I want to define the motion of an object in x,y,z axis using accelerometer data. Although I get a set of values, I can't understand how to use it.

If I could convert these values to ms<sup>-2</sup> units, I hope I would be able to achieve this

Could you provide me some advice, code or reference to work on this?

I also tried the code here to get the raw values.

# Answer
You may want to take a look of freeimu library which take care of all needed processing and present filtered and data-fused data (not just raw data) in easy to use roll, pitch and yaw format.

http://www.varesano.net/projects/hardware/FreeIMU

see demo video in which the on screen data mirror physical motion of the sensor http://www.youtube.com/watch?feature=player\_embedded&v=rFvX3vZJHTQ

hope this helps
> 1 votes

---
Tags: arduino-mega, accelerometer, mpu6050, gyroscope
---


# Question
Title: How do I connect Arduino to a Bluegiga112?
I am a new user of Arduino (I have a Arduino Due) and also I am a new user of BLE112 (Bluegiga module 112)

My teacher told me to make the BLE112 advertisable and furthermore he told me to look for information about UART@115K. (The Ble112 he gave me came with wires already soldered to the selected pins: I'm assuming I only need to use those.)

```
PIN NUMBER [PIN NAME] for BLE112

    2         AVDD                    (Supply voltage 2-3.6V)
    3         AVDD                    (Supply voltage 2-3.6V)
    4        [P2_2]  DC- Debug clock  (DIGITAL I/O)
    5        [P2_1]  DD- Debug data   (DIGITAL I/O)
    9        VDD_USB                  (Supply voltage 2-3.6V)
    20        DVDD                    (Supply voltage 2-3.6V)
    23       [P0_5]  RXD(Rx)          (DIGITAL I/O)
    24       [P0_4]  TXD(TX)          (DIGITAL I/O)
    25       [P0_3]  RTS              (DIGITAL I/O)
    26       [P0_2]  CTS              (DIGITAL I/O)
    29        RESET
    30         GND

```

I put:

```
BLE pins [2,3,9,20]    to     3.3v pin of Arduino
BLE pin  [30]          to     GND pin of Arduino

```

Then I found a picture (attached at the bottom of this post) that describes that I should put CTS of BLE on RTS of Arduino and vice versa. Where is the CTS on an Arduino board? I think I have to program one of the Digital pins.

I tried some other connections. I put:

```
BLE pin 26(CTS)   to    Arduino random digital pin 32, and
BLE pin 25(RTS)         Arduino random digital pin 34.

BLE pin 24(TX)          Arduino RX pin 0
BLE pin 23(RX)          Arduino TX pin 1

```

I didn't connect `DC(Debug clock)`, `DD(Debug data)` and `Reset` on the BLE112.

So then I found some more info on the web that if I use USART than I should use a wake up pin which is by the default `P0_0`(??) more about that in this PDF. (Search `wake_up`)

Now I should mention sleep mode Ble112 (there are three kinds of it) and I believe that the one I am after is MODE 3 (that means that it consumes the minimum (power) of them all)

I found some example named UART@115K

> UART@115k This example configures the BLE112 or BLE113 Bluetooth Smart module to expose the BGAPI protocol over UART interface with the following settings: 115200 bps, 8n1 and hardware flow control enabled. The power mode 3 is enabled in this example and the wake-up pin is configured to P0\_0 pin (P0\_0 button on DKBLE112 and DKBLE113). When the power mode 3 is enabled the device will not be able to receive commands or data over UART unless the wake-up pin is asserted.
>
> The example uses UART in the pin configuration channel 1 and alternate 1, which is the configuration used in the DKBLE112 and DKBLE113 development kits. If you try this example with DKBLE112 or DKBLE113 make sure the UART interface is enabled and the device is NOT powered with a CR2032 battery as it’s not able to power up the level shifter or UART to USB converter.
>
> This is also the factory default configuration for BLE112 and BLE113 Bluetooth Smart Modules.

*Source: https://bluegiga.zendesk.com/entries/22412436*

# Answer
> 2 votes
The most popular way to establish communication between an Arduino (I've used a Duemilanove) and a BLE module (I've used BLE113 that's on a DKBLE113) is through UART.

UART is a two wire interface (don't forget the common GND) with one RX and one TX. You can use the SoftwareSerial library to define your communication object on the Arduino. In contrast, the BLE113 uses four. The additional two are RTS and CTS (Request To Send and Clear To Send).

However, you can configure the UART in two ways using *hardware.xml*:

1. Go to the \<*usart* \> tag and set *flow = "false"*. This "disengages" the RTS and CTS allowing a traditional two wire interface.
2. Had you set *flow = "true"*, you need to connect the RTS and CTS as well, which I had a big problem with, though the two are both digital.

Further, in *hardware.xml*, you need to disable sleep mode by including \<*sleep enable="false" /*\> within the \<*hardware*\> tag. This will solve all your problems. If you intend to use sleep mode, you need to skip the previous step and instead govern the module's mode through the P0\_0 pin. Moreover, there are additional definitions to be included in *hardware.xml*, which are documented by BG. These work nicely for the BLE112 too.

In my exercise, I'd established communication at 9600 baud. It worked the same way when I increased it to 115200 baud (this is a plus in the BLE113).

# Answer
> 0 votes
To communicate with the Arduino, it is only necessary to connect the RX and TX pins between the module and the Arduino.

Source: http://www.mkroll.mobi/?page\_id=386

# Answer
> 0 votes
I would connect TX and RX to one of the 3 extra serial ports on the Due. Pins 0 and 1 are used for the USB-Serial communication

# Answer
> 0 votes
Well I found another way how to make it work, you just need to put CTS from BLE on GND, and RTS open "in the air" and that's it!

You can see these on this link: https://bluegiga.zendesk.com/entries/23143152--REFERENCE-Using-or-bypassing-flow-control-with-UART-communication

---
Tags: pins, arduino-due, bluetooth
---


# Question
Title: How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?
I am working on Fall Detection in humans. A system that would raise alarm when a person falls. For this I plan to use acceleration to see if it is a fall and orientation change to reduce false positives. I was trying to get angle of orientation using gyroscope,accelerometer and magnetometer. According to what I have googled I shouldn't use gyroscope alone as when we integrate to get angle the result is not accurate and I should use sensor fusion and filter using kalman filter or complementary filter. I can't use accelerometer as during a fall the acceleration won't be only from gravity. I am a newbie so I don't know how to proceed. Correct me if I have understood anything wrong till now.

# Answer
> 1 votes
The magnetometer will be very difficult to use because you have no idea what the local magnetic field will look like around the user.

The gyroscope can help you keep track of angular orientation data during accelerations, but unless you know exactly how this is going to be attached to the human it will not help because you cannot orient the relative angles to the subject. A person can fall with or without rotating in the air as well, so I don't see it helping much anyway.

Kalman filters are great, but overkill; you are not doing inertial navigation over long distances, so don't bother. Simple averaging will suffice.

The accelerometer should be able to detect falls by itself. The only way it will ever "Zero out" is in freefall, and if that zeroing is long enough and then followed by a very hard acceleration against the direction of gravity (the crash) you can call it a fall. Unless the person has some kind of engine to produce thrust, or is going so fast air resistance is a factor, there will be no accelerations in the air. Simplely calibrating of the threshold for being in freefall, the time necessary to call it a fall, and the necessary strength of the following crash should be able to detect falls or jumps with almost no false positives.

For instance if you want to track short falls where the object is never fully off the ground, a large dip in acceleration data will still be seen, so just set the "zero" threshold high.

# Answer
> 0 votes
Such system, some even has airbag, has been around in university/research/papers for many years. Presumably, falling means a marked change in 'data values'. One can easily log some data (accel and gyro) by falling on bed and plot the values.

May you find some inspiration in followings

http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0CEMQFjAC&url=http%3A%2F%2Fcourses.daiict.ac.in%2Fmod%2Fresource%2Fview.php%3Fid%3D2430%26redirect%3D1&ei=Ls\_WU5-cOob\_8QW3v4KoCA&usg=AFQjCNEDUyJKTNYFCi71rX13RMlxoHL8kg&bvm=bv.71778758,d.dGc

https://www.google.com/search?q=human+fall+detection+system&safe=off&tbm=vid&source=lnms&sa=X&ei=ps3WU6jGMYyE8gWxo4LYCA&ved=0CAoQ\_AUoAw&biw=1577&bih=800&dpr=1#q=elderly+fall+detection+airbag&safe=off

Hope it helps

---
Tags: accelerometer, mpu6050, gyroscope
---


# Question
Title: How do I proceed with a fall detection sensor?
I am working on a human fall detection system using accelerometer and gyroscope which raises alarm in case of a fall. In all the papers I have read people have used net acceleration magnitude and compared it with a threshold and coupled it with change in orientation to detect fall. My question is would it be better to use acceleration in z-axis(normal to earth's surface) and compare it to threshold as compared to net acceleration as it might reduce false positives as net acceleration can exceed threshold in case of running but that won't happen if i take only acceleration in z-axis. Is my approach right?

How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?

# Answer
> 1 votes
Find the derivative of acceleration over time, also known as **jerk**. Falling will have a specific jerk pattern, whereas normal shaking and banging will have a completely differrent pattern.

---
Tags: accelerometer, mpu6050, gyroscope
---


title: Arduino Control over the internet

text:
# Question
Title: Arduino Control over the internet
I am really interested in IoT (enthusiastic noob) and I would like to use the arduino board. Here are the steps according to me, with my queries:

* User goes to example.com/arduino\_switch
* Interacts with an HTML form to toggle an action
* Sends the data over the Internet (This is the part I have problem understanding)
* Arduino receives the data point (how can we do this? polling a url or can we actively send it)
* performs the action (easy to do for me)

Any and all help will be appreciated, even if its just pointing me to the right resources.

# Answer
> 2 votes
kiwiron has a great answer, but I have a few things to add:

* **You don't have to risk security...** you can create a VPN to your network *or* you could just stay inside local LAN. It's just if you want to access it from outside
* If you can't get a static IP for your network from your ISP, you can use something like No-IP to give you a name like `example.no-ip.biz` that's easier to remember and it will change the IP when your IP changes. I've used them before...
* A Raspberry Pi might be a good partner in crime to work with the HTTPS connection with a web server like Nginx and with PHP to run a script. I personally like the Arduino better for interfacing with the actual components since it is 5V and has 40 mA per pin, but it's possible that you could use the GPIO pins on a Pi for your server. This might be a little cheaper since you can remove the ethernet shield and replace that with USB.
* For the approach of polling a web server, it might be better to have the web server send a GET request to the Arduino and then the Arduino can respond ASAP.

For this, you might want to learn the basics of HTTP headers and try to figure out what goes on behind the scenes.

> (how can we do this? polling a url or can we actively send it)

Assuming you're using the Arduino directly, here's roughly what would happen:

* The client would request the Arduino for the content for the homepage using HTTP requests
* The Arduino would send the content and close the connection
* In the HTML there's a little attribute to the form that tells it to send the data via post to `response.php`. The client hits "submit" and it sends the data via POST to that URL.
* The Arduino sees that it's sending data to that URL and reads the data and then process it accordingly. The socket is closed.

# Answer
> 3 votes
You have two choices:

1. The Arduino regularly communicates with an external web server, sending data and asking if there is anything to do. This is the way Mitsubishi heatpumps can be controlled from the web. The advantage is that your internet connection does not need to publish a web server. Drawback is that the communication is slow (being dependent on the polling interval), plus the need for a web server to talk to. For instance, to control your Mitsubishi heatpump, you need to create an account on one of their servers for the purpose.
2. The Arduino exposes a web interface that is then exposed to the internet. This needs configuration of your internet router and preferably a static IP address on the internet. Security is a problem, and I'm not sure that even the Due can do HTTPS plus some form of authentication. I used this method, but fronted my Arduino with an old laptop running Linux and Apache web server. The laptop does the authentication and HTTPS processing. Advantage is near real-time control; disadvantage is the amount of hardware and configuration required.

---
Tags: arduino-due
---


title: Measure square wave frequency

text:
# Question
Title: Measure square wave frequency
I'm working with the Arduino Due ans I used the following code:

```
// period of pulse accumulation and serial output, milliseconds
#define MainPeriod 100
long previousMillis = 0; // will store last time of the cycle end
volatile unsigned long duration=0; // accumulates pulse width
volatile unsigned int pulsecount=0;
volatile unsigned long previousMicros=0;

void setup()
{
  Serial.begin(19200);
  attachInterrupt(6, myinthandler, RISING);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= MainPeriod)
  {
    previousMillis = currentMillis;
    // need to bufferize to avoid glitches
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    float Freq = 1e6 / float(_duration);
    Freq *= _pulsecount; // calculate F
    // output time and frequency data to RS232
    Serial.print(currentMillis);
    Serial.print(" "); // separator!
    Serial.print(Freq);
    Serial.print(" ");
    Serial.print(_pulsecount);
    Serial.print(" ");
    Serial.println(_duration);
  }
}

void myinthandler() // interrupt handler
{
  unsigned long currentMicros = micros();
  duration += currentMicros - previousMicros;
  previousMicros = currentMicros;
  pulsecount++;
}

```

to measure the frequency.

I can measure frequencies higher than 1.5kHz accurately, but I can't seem to measure lower frequencies.

How can I measure lower frequencies, say 400Hz and above?

Thanks.

# Answer
> 1 votes
It seems you have a problem of concurrent access to `duration` and `pulsecount` variables which are inter-related; with your code, it is possible that (and I guarantee that it will):

1. `loop()` reads `duration` value (in line `unsigned long _duration = _duration;`) but gets interrupted before executing the next line
2. `myinthandler()` changes both `duration` and `pulsecount` (it cannot be interrupted as it is already triggered by an interrupt)
3. `loop()` proceeds to where it was interrupted (after `myinthandler()` returns) and executes line `unsigned long _pulsecount = pulsecount;`: the values in `_duration` and `_pulsecount` do not match anymore!

To protect the access to `pulsecount` and `duration` variables, you have to disable interrupts inside `loop()` just for the time you get their values:

```
void loop() {
    ...
    // Disable interrupts while we get and reset duration and pulsecount
    cli();
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    // Now we can re-enable interrupts again
    sei();
    ...
}

```

---
Tags: programming, arduino-due
---


title: Connecting Arduino Android Wirelessy

text:
# Question
Title: Connecting Arduino Android Wirelessy
I am working with Arduino and Android. I am interested in connecting Arduino (Mega 2560 ADK) to my Android tablet (Nexus 7) wirelessly. The chepaest option is via bluetooth but the communication in not reliable. Now I would like to connect it via WiFi. But I don't want to use WiFi shield on my Arduino.

As Arduino can send the information to my laptop via serial USB connection will it be possible to put this information on my home WiFi network and get it on my Android device by connecting it to the same WiFi network?

# Answer
Yes, if the laptop and tablet are on the same network communication will be possible. One way to implement this would be to have a client/server setup that communicates over TCP/IP.

The laptop can act as a TCP/IP server and also communicate through the serial interface to your arduino. Many languages will be able to do this, Java, C/C++, Python, whatever you're comfortable with.

The android tablet can then connect to the TCP/IP server as a client and send and receive data through your WiFi. Have a look at the android documentation.

This would a simple solution but for a more permanent solution you could also setup a web server on your laptop, look into the apache webserver. Your tablet would be able to communicate with the web server through http requests. The web server can then start further scripts to send data to the arduino or maintain a serial connection depending on your implementation.
> 0 votes

---
Tags: wifi, android
---


# Question
Title: Is it bad coding practice to design a buffer using pointers?
I coded a ring buffer for my Arduino to buffer data from either the SPI or TWI ports. In the .h file I used a pointer for the buffer:

```
typedef uint8_t *ring_buffer_t;
typedef uint8_t ring_count_t;
typedef uint8_t ring_index_t;
typedef uint8_t ring_size_t;

typedef struct ring_t
{
    ring_buffer_t buffer;
    ring_count_t  count;
    ring_index_t  head;
    ring_index_t  tail;
    ring_size_t   size;
}rint_t;

int ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size);

// other function prototypes to add and remove from the ring buffer

```

There is more code to handle adding and removing from the buffer, but I am simplifying here. Then in my .c file I have:

```
#include<string.h>

void ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size)
{
    r->buffer = buffer;
    r->size   = size;
    r->head   = 0;
    r->tail   = 0;
    r->count  = 0;

    // clear out the buffer memset cheaper by 12 bytes rather than for loop
    memset((void *)r->buffer, 0, r->size);
}

```

Then somewhere in code where the ring buffer is going to be used:

```
In SPI.h ...
#define MAX_BUFFER_SIZE 32
ring_t  rx_ring;
uint8_t spi_rx_buffer[MAX_BUFFER_SIZE];

#define MAX_BUFFER_SIZE 32
ring_t  tx_ring;
uint8_t spi_tx_buffer[MAX_BUFFER_SIZE];

In SPI.c ...
void spi_init( ... )
{
    ring_init(&rx_ring, spi_rx_buffer, MAX_BUFFER_SIZE);
    ring_init(&tx_ring, spi_tx_buffer, MAX_BUFFER_SIZE);

    // initialize other spi parameters
}

```

Are there any issues with my code that are obvious that I am not seeing? I ask because I ran the code and it works, but I feel I am doing something wrong. I can code in C and remember something about malloc() for dynamic memory allocation, just not sure if what I am doing qualifies. Or should this work creating a buffer of some defined size?

Thanks for any help or ideas.

EDIT: 07/27/2014 Added code to try and make what I am trying to do clear. Let me know, thanks.

# Answer
> 1 votes
Don't bother with `malloc` unless you need to. If you explicitly define your buffer before hand then you can use `avr-size` to check your SRAM usage.

Also the C compiler automatically adds code to initialise global variables to 0, so you don't need ring\_init if your define the array explicitly. See https://stackoverflow.com/questions/2218254/variable-initialization-in-c for initialisation comments. Even if buffer was filled with non-zeros it wouldn't matter because it should be written to before being read from.

If you change the ring buffer from chars to ints, etc. you will have to change `memset`, as it assumes chars.

Will MAX\_BUFFER\_SIZE change? If not, you could put the buffer in `ring_t`.

# Answer
> 0 votes
Not enough info. You have a struct ring\_t that has a pointer to an array of uint8\_t's. In your ring\_init method, your code assumes that the pointer points to valid memory. If you have not explicitly pointed the pointer to a block of memory, either stack memory or heap memory, then yes, there is a problem.

You COULD malloc the ring buffer, or you could create it as a global variable. If you've only got one ring buffer it's probably just as well to make the buffer a global and set the pointer in your setup method.

# Answer
> 0 votes
Simple answer: No, it isn't bad practice at all. I write with pointers all the time. Pointer referencing usually compiles to more efficient code than does array referencing.

But: It looks like you've confused a pointer with the thing it is supposed to point to. The member you call 'buffer' is declared as pointer to unsigned byte. It doesn't appear to get initialized anywhere; it should be initialized with the address of an array of unsigned bytes (at least) as large as your ring buffer needs to be. I don't see this in anywhere in your code.

As others have described, the buffer could be allocated at run time with malloc() (but it's best not to save malloc() & free() for things you *have to* create and destroy on the fly; or direct the compiler to allocate it before your program gets control, with something like:

```
#define RINGBUFSIZE 32

uint8_t ring_buffer_memory[RINGBUFSIZE];

```

and initialize your pointer to it with:

```
r->buffer = ring_buffer_memory;

```

This will initialize your pointer to the first of (in this case) 32 bytes of zeroed memory reserved for the ring buffer. In your code, it's quite likely the pointer contains `0`, thus pointing to memory location zero and is definitely not what you mean to do.

A word on variable names - adopt a convention for naming your variables that help a future reader (probably you!) understand/remember what that variable is for. In this case I'd probably use `ringBuf` for the array, and `pRingBuf` for its pointer. As a new reader of this code, I'd find it pretty inconvenient to have to have to remember that `buffer` is really a pointer (and what the heck was the buffer called!?).

---
Tags: programming, pointer, memory-usage
---


title: Why does arduino work on usb power?

text:
# Question
Title: Why does arduino work on usb power?
The arduino website states that the operating voltage of an arduino is 7-12V.

Why does the arduino work powered on just usb then? As usb only outputs 5V and 500ma.

Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?

# Answer
> 3 votes
> The arduino website states that the operating voltage of an arduino is 7-12V.

That's when it goes through the voltage regulator. It's a *linear regulator*, meaning it wastes a lot of power as heat. The regulator outputs 5V that's given to the MCU. The USB voltage bypasses the regulator and goes to a fuse before going to the common 5V for the board. If less than 7V is given to the regulator, it will produce less than 5V.

> Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?

Usually, yes. A 9V supply would give you more than 500ma, giving you flexibility to add higher current components like motors and lots of LEDs. It will make no difference if you have a single LED connected.

---
Tags: power, voltage-level, electricity, electronics
---


title: Exoskeleton Motor Control Code

text:
# Question
Title: Exoskeleton Motor Control Code
Background:

I have been working on an exoskeleton project with a group of friends, and I need help. I made another post on the robotics.stackexchange site for the drive system: https://robotics.stackexchange.com/questions/4323/exoskeleton-drive-system-help. You can also check out our first prototype on youtube: https://www.youtube.com/watch?v=NL\_aCwJSRiE&feature=youtu.be

The device is going to be controlled by an iPad that we created via bluetooth. We are using the adafruit bluefruitLE

We are attempting to control 4 motors (2 knee motors and 2 hip motors) from an Arduino Mega. We will be using 2 Roboclaw 2x60A motor controllers. We are trying to get the motors to mimic the graph (see attached).

The graph is in degrees per percent cycle (a gait cycle). We are using 50 gait cycles per minute for tests but we hope to make it adjustable.
We can change percent cycle to time in milliseconds using dimensional analysis (ie) 50 cycles/min = 8.333x10^-4 cycles/ms —-\> 1/8.333x10^-4 cycles/ms is approx. 1200 ms/cycle. So if you multiply the cycle times 1200 you get millisecond for a certain percent of the cycle (ie) 0.5cycles(50 percent of cycle) * 1200ms/cycle = 600 ms.

We will have a position feedback system incorporated in the drive system but because it is a prototype and I wanted to make the code as versatile as posible I created a function: getDegrees(int jointNum), so if I change the position feedback system I only have to change the getDegrees method.

In order to mimic the graph we broke the graph up into sections. Each section represents a different velocity. We are going to run a correction algorithm so far we have just done the P in PID, we have used a modifier of 1.5. Then we saved the value that the section ended on so next gait cycle when it runs that section the algorithm will start off closer to the target value.

My question:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually. While the device is running we need to be able to constantly check for a bluetooth message from the iPad. The bluetooth messages come in via SPI from the adafruit bluefruitLE.

What I have done so far:

I have been able to run a single joint by using a while statement (ie)

```
int i = 0;
void loop(){
targetAngle = nextAngle[i]; //nextAngle is an array of points so nextAngle[0] through nextAngle[1] represents one section of the graph.
i++
if (getDegrees(1)< targetAngle){
double deg = getDegrees(1);
while (deg<targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}else{
double deg = getDegrees(1);
while (deg>targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}
}
}

```

The main problem with that code is its like using the delay() function instead of millis() is that it stops the program while its executing the code, and I cannot run multiple motors and check for bluetooth messages.

Major Challenges:

The drive commands must be based off of angle and not time. It is ok if we tell it do 50 cycles per minute and it does 52 or 48 but its not okay if it only does 97% of the motion.

Possible solutions I have come up:

Using one arduino for each joint, and making them all slaves of a master arduino and the master arduino would act as the middle man sort of between the joints, making sure that they are synced up. That way each arduino could use code similar to what I have already tried and confirmed to work. But I would prefer to run it all from one arduino.

Conclusion:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.

Is this the right forum for this question? Or is it more of a Stack Overflow or Robotics question?

Any help will be greatly appreciated,

-- Joel

# Answer
As your question "to sync the movement of the 4 joints while running a correction algorithm on each joint individually."

**Referring to the first part of your question**, **sync** the movement, assume your are doing this at either commercial or university project level, **popular practice** is to use 'hard real time preemptive operating system".

RTOS, real time operating system, is a piece of system software that coordinates execution of your multi thread user software at **precise and predictable** time accuracy in order of millisecond.

RTOS involve money and learning time. You may want to continue using the simpler system that you already having now and work in just one joint, hence, no issue of syncing multiple joints. Once you reach some maturity on single joint, then, expand to syncing 4 joints.

RTOS can be commercial with full support or free of charge. Some are dual mode. Same software may either be free or if you choose, can buy commercial full support. There are simple and full-scale implementations where functionality, complexity, learning time and software cost (commercial or free) varies by huge extend. You will then be more able to choose when you done the above single joint system.

Introduction http://en.wikipedia.org/wiki/RTOS

There are also real time 'executive' (smaller and less functions). For example, ucos II (older and simple version) is used by many people.

Hope it helps
> 2 votes

# Answer
Here's what I came up with:

* You have a certain percent of the gain cycle equal one "step" (step may be a bad term in this situation, but I'm using it because of stepper motors).
* You have a **blocking** function that will move the motors and control all the P(ID) logic
    + Before this function is called, the main code will use a variable to store the desired time to do the next "step."
    + It will have a loop with "substeps." So it would look kinda like this:

```
void function nextStep(int var1, int var2) {
    //Read sensors and put into variables
    until(condition == true) { //Condition to see if the motors are at the right degree
        //Adjust motors not in the right place
        delayAndCheckBT(10); //Look at the bottom for this function
    }
}

```

You could also have it accept a few percent of variance as tolerance so it's not shakey, but that's more of the PID control than anything. You'll have to make sure that many 'steps' doesn't make the PID controller unstable.

* When that code is done, the main function will check to see if the desired time for the next step has passed (or if it's now). If it's passed/now, then it will execute. Otherwise, it will not execute the next step and continue executing the main loop.

Great? No. The problem is you need to check for bluetooth! To do this, I've made two functions:

```
void checkBT() {
    //Checks BT. Make sure this is non blocking: if you need to, set a few global variables
    //Note this code will get called a LOT, so don't implement any delays or loops: inside here: use millis().
}
void delayAndCheckBT(int timeToWait) {
    unsigned long finishTime = millis() + timeToWait;
    while (millis()<finishTime) {
        checkBT();
    }
}

```
> 1 votes

---
Tags: programming, motor, sketch, system-design, algorithm
---


title: arduino boot loader problem

text:
# Question
Title: arduino boot loader problem
I am using atmega 328pu instead of atmega328p-pu. I am trying to upload the bootloader using AVR pocket programmer.

I have changed signature from `0x1e 0×95 0x0F` to `0x1e 0×95 0×14`.

*(Relevant link)*

```
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

```

# Answer
> (Note for the Arduino Uno: you'll need to add a 10 uF capacitor between reset and ground.)

From http://arduino.cc/en/Tutorial/ArduinoISP
> 2 votes

# Answer
It sounds as if you are using the Arduino IDE to "Upload using Programmer". If so; in the preferences enable Verbose output for upload. From this you should see all of the avrdude output. Not just the error message. Hopefully with this you will see signature of the chip you actually read. You will also see the full and exact avrdude.exe command that is being executed. Note the path/filename of the avrdude.conf, to ensure it is the one you changed.

Using this you can attempt it manually, and tweak it. Try adding the -F to it. Or execute the equivalent to :

```
avrdude -b 19200 -p atmega644p -C avrdude.conf -c stk500v1 -P COM4 -n

```

where the "-n" is "Do not write anything to the device." just read the signature.

I prefer to use a GUI in front of avrdude. Yuki's GUI is a good example. Just need to point it to the EXE and have a copy of the conf file in the same directory.

---

I should mention the Arduino way of doing this, is to create a new boards.txt file with this chip and add (not change) the avrdude.conf file. This will allow programing either from selecting the correct board. but that is another subject.
> 1 votes

# Answer
This sounds like the programmer is not seeing the ATMega328 MCU, or the Arduino IDE is not seeing the programmer. Changing the signature won't be of any help as the IDE (or AVRDude) is not seeing the ATmega328.

I would suggest that you double-check your connections, and set the options in the IDE to verbose output - then repost the info here.
> 1 votes

---
Tags: arduino-uno, electronics, arduino-duemilanove
---


# Question
Title: Can anyone tell me the best books for studying UAV?
It's kind of hard to get full guide from the internet. I just wanna buy a book for UAV guide. I gotta make DIY drones. I'd appreciat it if you recommend good books.

# Answer
Not a book, but try the following course from EdX, the online MOOC: https://www.edx.org/course/tumx/tumx-autonavx-autonomous-navigation-1658
> 0 votes

---
Tags: arduino-uno
---


title: IR controlled light dimmer

text:
# Question
Title: IR controlled light dimmer
I am doing a project on Arduino controlled light dimmer circuit...

I have a separate circuit for zero crossing detector and IR receiver but when I am combining both of them in arduino then my IR receiver stops working and zero crossing interrupt is not detected...

Here is my code:

```
#include <IRremote.h>
int RECEIVE_PIN = 8;
int AC_LOAD = 3;
int dimming;

IRrecv irrecv(RECEIVE_PIN);
decode_results results;

void setup()
{
    Serial.begin(9600);
    irrecv.enableIRIn();
    pinMode(AC_LOAD, OUTPUT);
    attachInterrupt(0, zero_crosss_int, RISING);
}

void zero_crosss_int()
{
    int dimtime = 75*dimming;
    delayMicroseconds(dimtime);    // Off cycle
    digitalWrite(AC_LOAD, HIGH);   // triac firing
    delayMicroseconds(10);         // triac On propogation delay
    digitalWrite(AC_LOAD, LOW);    // triac Off
}

void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.print("0x");
        Serial.println(
        results.value, HEX);
        delay(50);

        if(results.value==0xE13DDA28)
            dimming = 120;

        if(results.value==0xAD586662)
            dimming = 80;

        if(results.value==0x273009C4)
            dimming = 20;

        irrecv.resume();
    }
}

```

Can anyone help me with this????

# Answer
> 1 votes
What you've described (without source code and/or a circuit diagram) sounds like you'll probably be using interrupts at least for the zero crossing detection. And probably the IR receiver too. The IR receiver is going to be your problem since the zero crossing is a very quick flag set and you're out of the interrupt.

On the other hand, the IR detection is going to take time, and if you're doing THAT in an interrupt you're going to be missing dozens of crossings.

To mix the two you can leave the zero crossing in it's own interrupt, but you're probably better off handling the IR in the loop via a state machine.

Since you say that neither are working, I'm going to hazard a guess and you're using the same interrupt or badly implemented them (possibly a timer and interrupt clash) and until you post some code people here aren't going to be able to help you any more than that.

# Answer
> 0 votes
One important problem in your code is concurrent access to `dimming` variable. That may not be the only problem you have though.

Indeed, `deeming` is accessed for writing in your `loop()`, but it can be simultaneously read by `zero_crosss_int()` function which is executed in interruption mode because it was registered as such with `attachInterrupt()`.

Since `deeeming` is an `int` (2 bytes on AVR MCU), it cannot be read or written in just one clock-cycle (AVR is an 8-bit technology). Hence it is perfectly possible that `loop()` gets interrupted by `zero_crosss_int()` just in the middle of writing `dimming`, eg in:

```
dimming = 120;

```

Note that, in theory, concurrent acces in your case should not be an issue as long as `dimming` is never greater than 255.

## How do you protect access to `dimming` variable?

You can do the following:

```
int dimming() {
    cli();
    int temp = dimming;
    sei();
}

void dimming(int value) {
    cli();
    dimming = value;
    sei();
}

```

And replace any direct access to the `dimming` variable in your code with a call to one of these functions above.

## Will that fix your problem?

Maybe not unfortunately, as it is probable that mixing IRremote.h with your code brings other conflicts.

But at least, this will solve a dormant bug in your code, a complex bug that may catch you some day.

# Answer
> 0 votes
It seems that the jaydeep might have been building my circuit and used the provided code: http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step4/Arduino-controlled-light-dimmer-The-software/ so obviously this problem has my interest. With regard to the 'dimming' variable, that will not go beyond 128 so I might as well have used 'byte' to define it. The IR remote library is I presume that of Ken Shirrif and that one uses the Timer2 interrupt. In principle, combining those two interrupts shouldnt necessarily cause a problem as I have done so as well (in using the timer interrupt rather than 'delay to trigger the TRIAC). But in that case the entire timer interrupt was handled within the period of the mains wavelength (100 or 83 ms depending on frequency).

I don’t think the access to the 'dimming' variable -as jfpoilpret mentions- is the problem (though he makes some sound remarks), as that will just remain as is for a specific light level.

The problem -as is also suggested above- might well be in the fact that the IR receive takes too long.

So... disregarding interrupt priority for a moment, if the code is hanging around in the timer interrupt routine and there is a zerocrossing, that won't be detected, or, if the code is just doing a zero crossing detection, the timer is screwed up.

In comes interrupt priority: The external interrupt has the highest priority (other than reset). So.. when the IR receive routine is busy in the Timer service routine and a zerocrossing arrives, it will be taken out of that routine, zerocrossing will be handled and ideally, it should continue with the timer routine again. However, your remote has no idea what is going on in the Arduino and some of the code sent will be missed.

all of this shouldn’t need to be a problem if the external interrupt was fast, but as most of the waiting is actually done within this interrupt, it could take up to almost 10mS/8.3mS (when 'dimming' approaches 128).

Solution? Well, I can't say much about the Timer2 interrupts in Ken's library, But on 'my side' of the software, what could be done is to shorten the external interrupt by removing the delays and use (yet another) timer interrupt. Ken uses Timer2, so this would have to be timer1. So, whenever there is a zerocross, there is no waiting in a delay, but it will be handled by timer1 An example is given in Step 6 of my instructable. There is no guarantee this will work but there is a good chance

Let me just point out that the basic program I supplied was just given as an example, It uses much computer time in waiting and therefore isn’t the best to combine with other actions of the processor.

---
Tags: programming, arduino-due
---


# Question
Title: file directory for saving .cpp & .h for the Arduino IDE for short #include statement
I am trying to write a class/function that I think I will be using often in my Arduino IDE, I know the code but where should i save the file so that the IDE picks it up without a full directory address in the #include line, as you may guess I'm a little new to this....

# Answer
If you think you will be reusing this code frequently, you might want to make a library as suggested by Joachim. Your library can then be added to any sketch you write using a `#include` statement.

The arduino website has a nice guide on writing libraries, check it out here.

If you would just like to include your header file in a sketch without writing a library, placing the header file in the same directory as your sketch should compile if you use `#include "header_file_name.h"`.
> 1 votes

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


title: Simply Button Problem (Teensy 2.0)

text:
# Question
Title: Simply Button Problem (Teensy 2.0)
I am getting back into doing some hardware stuff after a fairly long time away and am having a hard time getting back into it. I have a Teensy 2.0 and am trying to run a basic sketch that when a button is pressed will output 0, but my button is always High. I think that I miswired something but my breadboard looks like all the tutorials so I'm just confused as to what is going on and would appreciate any help.

```
const int pinBtnUp = 0;
const int pinLEDOutput = 11;

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

  //Setup the pin modes.
  pinMode( pinLEDOutput, OUTPUT );
  //Special for the Teensy is the INPUT_PULLUP
  //It enables a pullup resitor on the pin.
  pinMode( pinBtnUp, INPUT_PULLUP );

}

void loop()
{
  Serial.println(digitalRead(pinBtnUp));
}

```

# Answer
> 2 votes
You would need to place your button over the "valley" in the centre of the breadboard, separating teh top 2 and bottom 2 legs of the button.

Currently the wire connecting the button to Pin 0 on your teensy is also connected to your pullup resistor on the breadboard, as it is in the same row.

To help troubleshoot this kind of thing I always find a digital multimeter very useful.

# Answer
> 2 votes
You should post a higher quality version next time.

## Wiring:

First of all, the button looks like it's not all the way in. Fix that first.

Also, from your picture, it looks like the green wire isn't in the right row:

I can't tell for sure. Also, like mentioned before, you to put the button over the gap between the two sides of the breadboard.

Also, you have a pullup resistor in your circuit *and* you enable it on the Arduino. And your physical pullup resistor isn't connected to your signal line. And you short your signal line to ground. All of this is incorrect wiring...

If utilizing the internal pullup resistor (like you are in your code), all you should need to do for a circuit is like this:

Just be sure to connect the 5V rail to 5V and the green wire to your digital pin.

## Code:

That's all fine. When doing logic with a button, be sure to *debounce* it.

---
Tags: button
---


title: What is this component? (range finder)

text:
# Question
Title: What is this component? (range finder)
I've taken apart an old range finder (see photo here). It uses a circular, seemingly gold-plated, two-wire sensor that I'd like to re-use in an Arduino project. I'm looking for a datasheet of the sensor and/or a circuit-diagram. Any help is welcome.

# Answer
The big circular parts likely is ultrasonic transducer as used in instant camera.

http://www.uoxray.uoregon.edu/polamod/

https://www.google.com/?gws\_rd=ssl#q=polaroid+ultrasonic+ranging+module&revid=399558007&safe=off

Working principle is same as modern unit, easily available at a few US dollars. The transducer does NOT work by itself, needs the associate PCB to work.
> 1 votes

---
Tags: sensors
---


# Question
Title: Need a sensor to make ball roll away from pet but which sensor?
Having recently entered the world of Arduino I am seeking to make, as my first project, a ball that will sense my dogs approach and roll away.

I can handle the rolling part but I have been unable to find a sensor that will work when fully embedded in the ball (so the dog cannot bite or swallow it). This means no ultrasound or infra red or normal proximity sensor will do.

My best bet - an inductive proximity sensor (with a metal object attached to dog's collar) is only effective at a maximum distance of 8 cm and that is far too little. I need something that activates at say 1 foot.

Any ideas anyone?

# Answer
Perhaps an RFID tag on your dogs collar and a reader inside the ball will work. You will just have to find a reader and tag combination that can work from the range you need, I think some RFID can work from over 1ft. EDIT: You will need active tags (battery powered) to get over a foot range.

PIR sensors detect heat given off by humans and animals, so they make work through the ball. (not totally sure though).

Edit: i think PIR that is capable of detecting small animals may be your best bet you would just have to calibrate the range of detection some how
> 1 votes

# Answer
Interesting. You may want to consider using strong,small, modern rare earth, low cost (silver color) magnetic that can work up to 1 foot, depending on size and shape of magnetic. Test different size/shape mag with simple mechanical compass to check the distance.

You may want to use one of those popular sensor board with

a) MPUxxxx (3D accel to sensor gravity in 3D to know which way is up and down) b) 3D magnetic sensor

Both sensors are 3D and you know which direction the dog is coming (direction and mag strength, changed from background earth magnetic field when dog is coming, gives distance) and which 3D orientation of the ball is and hence to calculate which way to move a weight inside the ball to make the roll.

Biological disclaimer, no idea if dog health may be affected, positively or negatively (people sells human magnetic collar with health claim), by constant, 24 hours, magnetic collar.

Hope it helps
> 0 votes

# Answer
Idea 1:

Put a transceiver in the dogs collar, and one in the ball. Monitor the RSSI (received signal strength). If it goes above a threshold, roll away. Adjust the threshold to set the correct distance.

Idea 2:

Put an accelerometer inside the ball. Whenever it detects a knock (dog's paw etc) roll away for a few seconds.
> 0 votes

# Answer
Other than the answers above/below, you also could try infra-red lights and photosensitive transistors. However, that has some troubles, such as not working properly in the sunlight, or the material that the ball is made of blocking the light, and therefore not working.

AVOID MAGNETS! You could get your dog stuck in some metal, like a fridge. To get one working in such distance, you would need an awfully powered magnet, which could be strong enough to permanently impact circuitry in close range, such as a home theater which sits close to the ground.

By the way, how are you going to fit it all in a ball that is bite-sized? i'm actually interested in that. Aren't you worried of the dog munching it and breaking/swallowing circuits?
> 0 votes

---
Tags: sensors
---


title: Raspberry pi -Arduino bridge

text:
# Question
Title: Raspberry pi -Arduino bridge
I am building a small wireless controlled robot using the Arduino and the raspberry pi. It works by the user wirelessly connecting through to the raspberry Pi (using vnc or some other form wirelessly) and using the user inputs to send a command to the Arduino which controls the motorised wheels. SO for example if the user presses the up button, a 'W" command is sent from the Raspberry Pi to the Arduino which then reads it and pushes the wheels forward.

I was looking to use one of the new Arduino-Raspberry Pi bridges to connect the two to make it easier to use, but I am not too familiar on how they work. Had a few question such as:

1) How exactly do they work (connection wise)?

2) is it possible to write one python code in the raspberry pi that when run can load the specific ino code into arduino?

3) which bridge would be the most suited for my project? (eg: Arduberry, alamode, gertduino, etc?)

Sorry really new to the raspberry pi and need to find a solution soon so any help would be awesome.

Cheers

# Answer
> 1) How exactly do they work (connection wise)?

Physically they all sit on the GPIO sockets of the Pi, sitting on top of the pi. The Gertduino and AlaMode seem to have the same form factor as the Pi which makes them a little more appealing to me but I guess then is personal choice.

Communication appears to differ but it will use Serial, SPI or I2C. I would imagine that you'd be able to choose an alternate one but not read enough about them to know for sure. Serial appears to be fairly simple, and it would be easy to debug, however you might struggle if you wanted to receive data on the Pi without the communication being initiated by the Pi. I2C would overcome this as you can run it in multi-master mode.

> 2) is it possible to write one python code in the raspberry pi that when run can load the specific ino code into arduino?

As you can call external programs with python I would say that even if you have to resort to this mechanism then it would be possible. You can turn on the debugging in the Arduino IDE to see what it actually does, then either script it or make the calls from your python program.

> 3) which bridge would be the most suited for my project? (eg: Arduberry, alamode, gertduino, etc?)

I'd go for either the gertduino or alamode purely on looks particularly the matched form factor.
> 3 votes

# Answer
Have you thought about using the Raspberry Pi to control the robot directly, instead of adding the complexity of having the Pi talk to the Arduino?

Python allows you to control the GPIO pins of the Pi, and as long as you connect a suitable motor driver (to protect your Pi), you should be fine.

If you want to connect the Pi to the Arduino, then you could also look at doing this using Serial communications and wouldn't need the complexity of a bridge - just need a logic-level converter to convert the 5V of the Arduino to the 3.3v of the Pi
> 0 votes

---
Tags: arduino-mega
---