title: Arduino error in code

text:
# Question
Title: Arduino error in code
i'm making a project and i came across the follwing error. Whan i'm trying to compile and upload the code i'm getting those errors:

```
ShiftRegisterTest1.ino:In function 'int* return_pins(int)'
displays.ino:9: error: expected primary-expression before '{' token
displays.ino:9: error: expected `;' before '{' token
displays.ino:12: error: expected primary-expression before '{' token
displays.ino:12: error: expected `;' before '{' token
displays.ino:15: error: expected primary-expression before '{' token
displays.ino:15: error: expected `;' before '{' token
displays.ino:18: error: expected primary-expression before '{' token
displays.ino:18: error: expected `;' before '{' token
displays.ino:21: error: expected primary-expression before '{' token
displays.ino:21: error: expected `;' before '{' token
displays.ino:24: error: expected primary-expression before '{' token
displays.ino:24: error: expected `;' before '{' token
displays.ino:27: error: expected primary-expression before '{' token
displays.ino:27: error: expected `;' before '{' token
displays.ino:30: error: expected primary-expression before '{' token
displays.ino:30: error: expected `;' before '{' token
displays.ino:33: error: expected primary-expression before '{' token
displays.ino:33: error: expected `;' before '{' token
displays.ino:36: error: expected primary-expression before '{' token
displays.ino:36: error: expected `;' before '{' token
displays.ino:39: error: expected primary-expression before '{' token
displays.ino:39: error: expected `;' before '{' token
displays.ino:42: error: expected primary-expression before '{' token
displays.ino:42: error: expected `;' before '{' token
displays.ino:45: error: expected primary-expression before '{' token
displays.ino:45: error: expected `;' before '{' token
displays.ino:48: error: expected primary-expression before '{' token
displays.ino:48: error: expected `;' before '{' token
displays.ino:51: error: expected primary-expression before '{' token
displays.ino:51: error: expected `;' before '{' token
displays.ino:56: error: expected primary-expression before '{' token
displays.ino:56: error: expected `;' before '{' token
Error compiling

```

I don't really understand why since the code (see below) should be working.

```
int * return_pins(int get_number)
{
static int rp[8];
switch(get_number)
{
            //DP, A, B, C, D, E, F, G
    case 48: //0
        rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};
        break;
    case 49: //1
        rp[8] = {0, 0, 1, 1, 0, 0, 0, 0};
        break;
    case 50: //2
        rp[8] = {0, 1, 1, 0, 1, 1, 0, 1};
        break;
    case 51: //3
        rp[8] = {0, 1, 1, 1, 1, 0, 0, 1};
        break;
    case 52: //4
        rp[8] = {0, 0, 1, 1, 0, 0, 1, 1};
        break;
    case 53: //5
        rp[8] = {0, 1, 0, 1, 1, 0, 1, 1};
        break;
    case 54: //6
        rp[8] = {0, 1, 0, 1, 1, 0, 1, 1};
        break;
    case 55: //7
        rp[8] = {0, 1, 1, 1, 0, 0, 0, 0};
        break;
    case 56: //8
        rp[8] = {0, 1, 1, 1, 1, 1, 1, 1};
        break;
    case 57: //9
        rp[8] = {0, 1, 1, 1, 1, 0, 1, 1};
        break;
    case 65: //A
        rp[8] = {0, 1, 1, 1, 0, 1, 1, 1};
        break;
    case 70: //F
        rp[8] = {0, 1, 0, 0, 0, 1, 1, 1};
        break;
    case 69: //E
        rp[8] = {0, 1, 0, 0, 1, 1, 1, 1};
        break;
    case 80: //P
        rp[8] = {0, 1, 1, 0, 0, 1, 1, 1};
        break;
    case 72: //H
        rp[8] = {0, 0, 1, 1, 0, 1, 1, 0};
        break;
            //DP, A, B, C, D, E, F, G
    case 45: //-
    default:
    rp[8] = {0, 0, 0, 0, 0, 0, 0, 1};
    break;
}
return rp;
}

```

What this code does is to basicaly get an `int` ad input and based on this number it returns an `int array`. It's a very simple code which is called inside the `loop()` method which is located on an other file.

**Also i'm using Atmel Studio 6 instead of the original Arduino IDE but i dont think it has to do something with the problem :/**

# Answer
As `fuenfundachtzig` said this cannot be done in this version of C++ Arduino uses. A replacement for this method is to set the number for each place.

For example:

```
case 48:
    //rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};
    rp[0] = 0;
    rp[1] = 1;
    rp[2] = 1;
    rp[3] = 1;
    rp[4] = 1;
    rp[5] = 1;
    rp[6] = 1;
    rp[7] = 0;
    break;

```

This works the same however it takes more space but i dont this there is a problem.
> 1 votes

# Answer
What you try here:

```
rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};

```

is only valid in C++11. (Before that you can initialize an array like this only upon initialization.)

Besides, as pointed out by Pete Becker, you need to declare `rp` as an array rather than a single `int`.
> 2 votes

# Answer
Have you tried compiling without the "static" keyword. I think the compiler is complaining because it sees multiple statements trying to make an assignment to a static variable. Even if your logic is such that only one of the assignments will ever be executed the compiler doesn't know that.
> 0 votes

---
Tags: arduino-uno, programming, sketch, c
---


title: 2 digit number to 2x 1 digit

text:
# Question
Title: 2 digit number to 2x 1 digit
Suppose I have a number with 2 digits, 42. It is an integer, received from my RTC

Now for my 7 segment displays, I will need 2 separate numbers:

* 4 on display 1.
* 2 on display 2.

How do I slice this number in 2?

# Answer
> 2 votes
Numbers retrieved from an rtc are usually returned as a char or integer.

On this basis, you want

```
ones_column = bytefromrtc % 10;
tens_column = (bytefromrtc / 10) % 10;
hundreds_column = (bytefromrtc / 100) % 10;

```

the `%` operator returns the modulus - if you divide 42 by 10, the answer is 4, with a remainder of 2. % returns the remainder, in this example, 2.

To do the tens column, first get rid of the last digit by dividing by 10, then do the modulus as above. Since bytefromrtc is not a float, if you divide it, you lose the remainder - 42 / 10 = 4, not 4.2.

If the output is a word, or integer, or long integer, the method is exactly the same, except for the number of digits you can get out.

---
Tags: display
---


# Question
Title: Stuck in a small confusion about Infrared leds and receivers?
I have a very simple idea I want to implement. I am making a home automation using an Arduino Uno. I am familiar with Arduino programming but the problem is what kind of IR receiver I need to buy if i want my TV remote (or similar) to communicate with my Arduino.

Can you suggest me any example (low cost, and available in India)?

# Answer
Element14 has an India based store, and they carry these IR devices. Here is one for 66 rupees: http://in.element14.com/vishay-semiconductor/tsop38238/ir-receiver-45m-38khz-th/dp/2395954?MER=MER-BPR-4PPM-SP-VSHY-OD&

You may want to do research into what the carrier frequency of your remote is also. Most are generally around 35 - 40khz, and the receiver I provided a link to is 38khz. It should work, but if you want to be safe I suggest you look it up. Or, if you have an old TV lying around, you can pull one out of that.

Hope this helps.
> 1 votes

---
Tags: arduino-uno, ir
---


title: The code of ISR executes twice

text:
# Question
Title: The code of ISR executes twice
i am using Arduino Mega.. ANd this is the code:

```
void bump(void);

void setup()
{
    pinMode(19,INPUT);
    attachInterrupt(4,bump,HIGH);
    pinMode(13,OUTPUT);
}

void loop()
{

}

void bump()
{
   for(float i = 0; i < 90000; i++){
   digitalWrite(13,HIGH);
   }
   for(float i = 0; i < 10000; i++){
   digitalWrite(13,LOW);
   }

}

```

Although i give +5 V to it once, the LED will blink twice...! What is the solution?

# Answer
> 1 votes
After wondering over it for quite a long time, I finally came to the conclusion, that the interrupt should be made to trigger at RISING edge, **if I want it to go into ISR the moment it gets HIGH.**

Hence the setup line was change to

```
attachInterrupt(4,bump,RISING);

```

And the cod e works well.
I suppose that is because, when it receives a HIGH signal, than the period for which it receives HIGH is a bit long, during which it adds another interrupt into the queue, and so the ISR is executed once again.

---
Tags: isr
---


# Question
Title: Is it harmful to write to unused bits in PORT registers?
Background: I'm looking at writing a library to drive an LED matrix panel (one of these:http://www.adafruit.com/product/607) from my newly acquired Arduino Due. My background is C++ programming, not electronics.

I'm planning to experiment with various optimisations of the code for memory and speed, but one constant is that I would like to be able to send the data to the matrix with single memory writes to port registers without having to use masking operations to leave certain bits unaffected. As I need to send 6 bits of data with a clock signal, I figured this could be easy with an 8 bit write to one byte of a port register. The 8th bit/pin could be used as the latch or some other used line.

Looking at the nice pinout diagram that someone has kindly put together (http://forum.arduino.cc/index.php/topic,132130.0.html), I was pretty shocked to discover that my plans weren't going to be as easy as I would have liked. There are only two circumstances where there are whole bytes of port registers that connect to digital pins (Port A byte 1 and Port D byte 0). All other bytes have "holes" in them, for example Port C byte 0 has no connection for bit 0, but has bits 1-7;

While two complete bytes is enough (I actually only need to use 13 pins to control the display, plus ground connections), the pins of the available two are spread out in a way that would make it a little awkward for me to make a stripboard shield as I intended due to the pins on the Arduino boards not being evenly spaced (why is that?) and I'm guessing that since most of the digital pins in Port A byte 1 are used for communication pins (including RX0 and TX0) I would lose my ability to print to the debug log. As a result, I've ruled out using those port registers.

That leaves me with bytes 0 and 1 of Port C. There are just enough pins available with those bytes and they are grouped nicely on the double connector at the bottom of the board (Digital pins 33-40 and 48-51), however some bits in those bytes are not mapped to Arduino IO pins.

Would it be bad if I were to write to bits of a port register that do not have Arduino IO pins assigned to them? Would the answer depend on whether I had set those bits to be inputs or outputs using the Output Write Enable Registers? I'm assuming that these bits are used for IO pins on the SAM3X8E chip but just not made available to the Arduino boards.

# Answer
If the pins have no connection to the outside world (i.e., they don't have any actual pin associated with them on the SAM3X chip) then writing to the PORT (or indeed any other register associated with them) will have no effect whatsoever.

If they have a pin but that pin is not connected to anything, then there will be little effect. There may be slightly increase current draw as the pin switches on/off, or you enable/disable the internal pullup resistor, but that's all.

If the pin exists and is connected to something on the board - maybe a button or LED, then you will basically be providing an output to that item. If it's an LED it will flash. However, if it's a button, and you provide an output opposite of its active state (i.e., provide a HIGH when it normally connects to ground when you press it) and that button lacks any current limiting resistance, then you could risk burning out that IO pin if the button gets pressed.

If the pin just goes straight to a header, then as long as nothing gets connected to that header then there will be no effect other than as detailed in the "pin present on the chip but not connected".
> 2 votes

---
Tags: arduino-due
---


title: time error in controlling a clock

text:
# Question
Title: time error in controlling a clock
I have designed and 3d printed a clock.

I am controlling the clock using a Arduino sketch running on a Attiny2313. The stepper motor I am using is a 12v 1:12 ratio stepper. The total number of steps per revolution are 288.

The problem I am facing is that I am unable to get the time right. I have got the steps per revolution of the minute ring bang on, but some how the motor gains 10/11 minutes every 24 hours.

I have used a lot of the code from the stepper motor library. I am not using the stepper motor library as the code gets larger than what can fit into the 2k attiny memory.

Any help is appreciated.

```
int number_of_steps = 288;
int motor_pin_1 = 9;
int motor_pin_2 = 10;
int motor_pin_3 = 11;
int motor_pin_4 = 12;
int ledpin = 13;
int delayTime = 4;
int buttonPin = 4;
int buttonState = 0;
int enablepin = 8;
int whatspeed = 40;
int last_step_time =0;
int step_number = 0;
[color=red]int blinkDelay = 939; [/color]
int step_delay = 60L * 1000L / number_of_steps / whatspeed;
int step_direction = 0;
void setup() {

 pinMode(motor_pin_1, OUTPUT);
 pinMode(motor_pin_2, OUTPUT);
 pinMode(motor_pin_3, OUTPUT);
 pinMode(motor_pin_4, OUTPUT);
 pinMode(buttonPin,INPUT);
 pinMode(ledpin, OUTPUT);
 pinMode(enablepin,OUTPUT);

}

void loop() {
 buttonState = digitalRead(buttonPin);
 if (buttonState ==HIGH){
   enablemotor();
   movestep(20);
   digitalWrite(ledpin,HIGH);
 }
 else{
   digitalWrite(ledpin,LOW);

   for (int xx = 0; xx<59;xx ++){

     enablemotor();
     movestep(42);
     //delay(100);
     motoroff();
     blinkk();
   }
   enablemotor();
   movestep(89);//85;

   motoroff();
   blinkk();
  //delay(3000);
 }
}

void enablemotor(){
 digitalWrite(enablepin,HIGH);
}

void movestep(int steps_to_move){
 int steps_left = abs(steps_to_move);

 if (steps_to_move > 0) {
   step_direction = 1;
 }
 if (steps_to_move < 0) {
   step_direction = 0;
 }

 while(steps_left > 0) {
   // if (millis() - last_step_time >= step_delay ) {
   //last_step_time = millis();
   if ( step_direction == 1 ){
     step_number++;
     delay(step_delay);
     if (step_number == number_of_steps) {
       step_number = 0;
     }
   }
   else {
     if (step_number ==0){
       step_number = number_of_steps;
     }
     step_number--;
   }
   steps_left--;

   stepmotor(step_number % 4);

   //}
 }
}

void stepmotor(int thisStep){

 switch (thisStep) {
 case 0:    // 1010
   digitalWrite(motor_pin_1, HIGH);
   digitalWrite(motor_pin_2, LOW);
   digitalWrite(motor_pin_3, HIGH);
   digitalWrite(motor_pin_4, LOW);
   break;
 case 1:    // 0110
   digitalWrite(motor_pin_1, LOW);
   digitalWrite(motor_pin_2, HIGH);
   digitalWrite(motor_pin_3, HIGH);
   digitalWrite(motor_pin_4, LOW);
   break;
 case 2:    //0101
   digitalWrite(motor_pin_1, LOW);
   digitalWrite(motor_pin_2, HIGH);
   digitalWrite(motor_pin_3, LOW);
   digitalWrite(motor_pin_4, HIGH);
   break;
 case 3:    //1001
   digitalWrite(motor_pin_1, HIGH);
   digitalWrite(motor_pin_2, LOW);
   digitalWrite(motor_pin_3, LOW);
   digitalWrite(motor_pin_4, HIGH);
   break;
 }

}

void blinkk(){
 for (int i = 0 ; i<30;i++){
   buttonState = digitalRead(buttonPin);
   if (buttonState ==HIGH){
     break;
   }
   else{
     digitalWrite(ledpin, HIGH);   // set the LED on
     delay(blinkDelay);  // 968           // wait for a second
     digitalWrite(ledpin, LOW);    // set the LED off
     delay(blinkDelay); //968
   }
 }
}

void motoroff(){
 digitalWrite(enablepin,LOW);
 digitalWrite(motor_pin_1, LOW);
 digitalWrite(motor_pin_2, LOW);
 digitalWrite(motor_pin_3, LOW);
 digitalWrite(motor_pin_4, LOW);

```

# Answer
> 1 votes
It is very difficult to accurately control timings with `delay()`, because you have to account for the time needed to execute the rest of the code, including interrupts. You can easily have better accuracy by using `millis()` like this:

```
static unsigned long last_step_time;
unsigned long now = millis();
if (now - last_step_time >= step_delay) {
    do_one_step();
    last_step_time += step_delay;
}

```

This is almost what you have commented out in your own code, except that `millis()` should be called only once per iteration, hence the `now` variable.

This may still have less than perfect accuracy due to your clock source. If your Arduino is clocked from a quartz you should be able to get decent timing accuracy. If it is clocked from a ceramic oscillator you are out of luck. In any case, you can always improve the accuracy by calibrating your clock: you measure its drift and correct for it in software. Then you have only to worry about thermal fluctuations of the clock frequency, which should not be an issue with a quarts.

For best accuracy, you can use either an RTC or a watch crystal connected directly to your ATmega chip. This last solution is only possible if you go for a bare microcontroller, without the Arduino board. See this answer for more details about this option, as well as the way to correct for the drift in software.

# Answer
> 0 votes
You should consider using hardware timers (`millis()` uses this, see answer of edgarBonnet.

Or you might want to use a Real Time (Calendar) Clock chip, which often has even better accuracy (some even adjust to temperature).

Also a possibility is using a GPS module, and using the GPS time which should be extremely accurate and will not drift (since it's synchronized).

Post on AVR timer precision (hardware timers): http://www.seanet.com/~karllunt/interval.html

RTC (Real Time Clock) example: http://www.instructables.com/id/Real-Time-Clock-DS1302/

GPS example: http://blog.arduino.cc/2014/01/06/simple-arduino-micro-gps-clock-project-arduinomicromonday/

---
Tags: motor, attiny, oscillator-clock
---


title: Nano destroyed?

text:
# Question
Title: Nano destroyed?
Board: OE Gravitech Nano Is it possible to destroy the board if there are a voltage on a Analog pin while the board is not powered? I have a application that use a analog (speed) voltage 0-4,9 from a GPS module, this worked very nice for a hour of 10, after that the voltage seems to be not constant available. Maybe the user have powered off the Arduino while driving the machine.

Regards, Rien

# Answer
> 2 votes
Assuming you're talking about the device with this schematic (or similar), the "analog" pins go directly to Atmel AVR I/O pins with no series resistance, so yes, it's quite possible to damage the microcontroller. Add some series resistance of a few K and you'll have a better chance of the part surviving such an event.

The voltage on any pin should not, under any circumstances exceed Vcc+ 0.5V as the datasheet specifies, however it's usually okay under non-operational conditions if the current is limited to much less than the 40mA. A 4.7K resistor would limit the current to less than 1mA with a 5V input.

---
Tags: gps
---


title: Multiplexing help for relay and pwm

text:
# Question
Title: Multiplexing help for relay and pwm
I have to control with an Arduino UNO and xbee shield:

* 9 5V relay
* 9 RGB LED

What kind of multiplexing can you advice me? Do I have to use external power supply (like 12V DC external from arduino or from vcc)? Is there any kind of already ready-to-use shield?

### EDIT

I'm planning to use a 8 relays shield plus one single relay

# Answer
You can use shift registers to control the relays. This will only use 3 pins and allow you to use the xbee.

For the RGB LEDs you can use the TLC5940 to control 16 channels, so you will need two, giving you 32 channels. This is a PWM chip with serial interface.

Considering you will be using the board linked. It is driven by transistors, so you can use the shift registers.

For the power supply, if you will be operating all of the relays at the same time it will draw about 650 mA (9x72mA), you will need a separate 5V power supply for the relay board, as I believe drawing that much current will heat the board and regulator a lot. If one at a time it will not draw too much, so its possible you can run it all off the Arduino.

A forum post of someone running 360 relays with shift registers.
> 2 votes

---
Tags: pwm, relay, multiplexer
---


title: Best Header for Arduino Nano

text:
# Question
Title: Best Header for Arduino Nano
I would like to be able to create permanent projects with my arduino Nano but be able to remove the nano in order to use it in other projects. The arduino Nano has 30 pins so I would be looking for some kind of female 30 pin header. Most of the headers that I found like that are too narrow because they are for IC's. Any ideas?

# Answer
The Nano boards that I have used all have pins on 0.1" (2.54mm) spacing. There are single-row female connectors that are designed to accept 0.025" square pins. One example is Samtec 32 position female header but there are *many* others.

Note that these female headers are available to accept either 0.018" round or 0.025" square pins. My great preference is for the 0.018" round pins but those are less common in hobby circles.

The really huge advantage of the smaller round pins is that you can safely insert them into solderless breadboards without damaging the contacts in the breadboard. But you would want to standardize on one style or the other.
> 8 votes

# Answer
I use the female headers from the original Nano manufacturer: http://gravitech.us/2015feheanas.html
> 3 votes

# Answer
You've already got a lot of really good answers here but I thought I would offer another product suggestion. I purchased some of the 12 pin versions of these https://www.pololu.com/product/1031 for some recent projects.
> 1 votes

---
Tags: pins, arduino-nano, system-design
---


title: Multiple interrupt lines connection

text:
# Question
Title: Multiple interrupt lines connection
In my project I need to connect more then 10 I2C sensors(MPU-6050) to Arduino Mega and an interrupt line for each sensor is essential. Since the Arduino Mega only has several interrupt slots (digital 2, 3, 21,29,19,18), how can it be achieved? Is that using a multiplexer every time I switch sensors and also switching interrupt lines solve the problem?

The code I'm using is Jeff Rowberg's MPU-6050 DMP example, which means interrupt line is essential and important, also very sensitive (a wrong change can cause sudden stop)..

```
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg

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

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

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

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

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

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
//MPU6050 mpu;
MPU6050 mpu(0x69); // <-- use for AD0 high

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Arduino
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #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);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

```

# Answer
One possible solution is to use a "global" interrupt pin which all the sensors use, and also normal GPIO pins to work out which interrupt has occurred.

Feed the interrupt signals into a multiple-input OR gate (if they are active HIGH) or a multuple-input AND gate (if they are active LOW). The output of that AND gate goes to a single INT pin. Each interrupt signal also goes to a normal IO pin. When the interrupt pin triggers the ISR can then look at the IO pins to determine which of the interrupt signals that triggered the interrupt.

For fastest operation use IO pins that are on the same port and use direct register reading for that port to see which bits are on and which are off.
> 2 votes

# Answer
Just FYI, the interrupt is not essential. If you can write efficient code you can read an MPU(DMP) without it (UNO, been there, done that). But that is only for one MPU. I doubt if an UNO can keep up with 10, no idea about the faster processors. In any case, even with interrupts, I doubt if an UNO could keep up with 10. Keep googling and you will find a note how to change the sampling rate to slow the MPU down.

The code you referenced provides AHRS (Attitude Heading Reference System) - I would be real curious to see what projects needs 10 of those :) Sounds like fun.
> 0 votes

---
Tags: arduino-uno, arduino-mega, i2c, interrupt, mpu6050
---


# Question
Title: XBEE coordinator WITH or WITHOUT Arduino?
I am building a wireless system that has got an Arduino with a XBEE as the 'end user' and I need to acquire data/control that Arduino from a PC graphical interface. As far as I'm aware there are two options to obtain the communication:

1. I could use another Arduino with XBEE (coordinator) that is connected to my PC (serial) to control the 'end user'. The code is stored in this Arduino which works as a bypass between PC and XBEE.
2. I could simply use a XBEE without Arduino (coordinator) connected to my PC to control the 'end user'. The code should be stored within the PC or the XBEE to establish communication and control data transmission to different end users (???)

As I am new to the Arduino world, would you please direct me to the best/easiest solution to obtain such thing?

# Answer
> 1 votes
If you want just to control and receive data from your end user, option 2 is easy to implement.

You can use any programming language that supports serial communication such as python, node.js, etc.

What you have to is to note how your coordinator is recognized by your operating system (in windows as com1 port, unix-like as ttyACM or similar) and open it from your preferred language.

After that, you establish a protocol that should be agreed with your Arduino. For example. Suppose you want to collect data from end user, so, you send a message from the coordinator connected in your PC with a code #data through the serial. When the Arduino receives it, it decodes the message and return something like #d125 where it says it is sending the data and the value is 125 (supposing integer values).

Making sure you already have configured the XBees in the same network by setting Same PAN id and cross setting the destination address of each one so they send packates to each other.

I am supposing you are using AT transparent mode where they just send whatever comes in the serial interface, in this mode they work basically sending chunks of bytes and it is up to you to establish a protocol to provide a good flow of data. In this mode there is no guarantee that your packet will reach the destination. In order to fully extend the XBee usage, you'd need the API mode where all the transmission checks are done.

But for you purpose, AT mode seems enough.

---
Tags: arduino-uno, serial, xbee, communication
---


# Question
Title: How can I best control various high power LEDs without using PWM
I want to be able to dim various high powered (20mA) LEDs in an array (8X12 LEDs). I do not need individual control, but would like to be able to dim each row (or two rows together) so that I can create gradients.

An important caveat is that I can't use pulse width modulation (PWM) as there should be no flashing whatsoever, even if it is invisible to humans.

**How can I best achieve this?** (I do not care about energy efficiency)

The fist thing I found which seemed to be the right solution in the beginning is using digital potentiometers as explained in this tutorial. However they only support low currents so I can't use one channel for 8 or 16 LEDs. Maybe I could use various digipots in parallel with one Arduino, each powering 1 LED per channel? But that sounds overcomplicated and a nightmare to wire up. Is there a more elegant solution?

# Answer
> 1 votes
The figure below illustrates a method of current control. It shows four LEDs in a 2x2 arrangement; one would adapt the number of LEDs in series or parallel in accord with how one's array is wired, what voltages are available, LED current requirements, transistor power limitations, etc. *\[Edit: See transistor-power example calculation at end.\]*

Each separately-controlled group of LEDs would need one such circuit. Each circuit needs one control voltage (eg, from a DAC or a digital potentiometer voltage divider circuit) and needs one transistor per series chain.

**Circuit Operation:**

Suppose the following conditions hold.

* Q1 and Q2 are equivalent transistors and Vbe is 0.7 V typ. (one diode drop)
* D1, D2, D3, D4 are equivalent LEDs
* Resistors R1, R2 are small and equal (eg 1–30Ω)
* V1 is some fixed DC voltage, eg about 1 V
* V \> 2\*Vf \+ Vbe \+ VR where Vf = typical forward voltage of D1...4

Under these conditions, V1 will drive current into the bases of Q1 and Q2, causing transistor-amplified current to flow through R1 and R2 and maintain the condition V1 = Vbe \+ VR1 = Vbe \+ VR2.

Here is a concrete example: Suppose we want 23 mA through each LED and that R1=R2=17Ω. VR = IR = 0.023 mA · 17 Ω = 0.391 V. If Vbe is about 0.7 V, then we set V1 = 0.7 + 0.391 V or about 1.09 V to get 23 mA through each LED. More generally, to get current I through the LEDs we solve V1 = Vbe \+ VR = 0.7 + IR = 0.7 + I·17.

**Base current:**

The amount of current required from the V1 voltage source depends on transistor hFE or β. Eg, if β is about 100 and ILED is 20 mA then each transistor will need about 20/100 mA or about 200 μA of base drive. This amount of current probably could be delivered by a voltage divider based on an AD5206 (the digital potentiometer chip that's used in the SPIDigitalPot tutorial mentioned in the question).

**Power Dissipation:**

The AD5206 digital potentiometer datasheet shows an absolute maximum rating for Package Power Dissipation of (TJMAX-TA)/θJA. If ambient TA is 25℃ and θJA is 70°C/W (as for a SOIC package) this gives (150-25)/70 = 1.8 W max package power. However, it would be reasonable to limit dissipation to under half a watt. In the 10 KΩ version of the AD5206, that means a little less than 2.9 mA maximum per channel. \[I = √(0.5 W /(6 channels * 10000Ω)).\] If several low-beta transistors are used to drive several strings of LEDs, 2.8 mA might be marginal.

**Voltage-divider Linearity:**

Only a small fraction of the current through a voltage divider can be drawn off without upsetting the division ratio. A unity gain buffer amplifier \[as in the following figure\] can be used to increase linearity of voltage-divider output by providing a high-impedance connection to the divider.

(In the figure above, R1 and R2 are not related to R1 and R2 of the previous figure. Here, R2 represents a digitally-variable resistor. Choose R1 and R3 so that V1's range is from slightly below Vbe to slightly above Vbe \+ ImaxR, where Imax is the maximum LED current desired. For example: Suppose V=5 V, that R2's total resistance is 10 KΩ, that R is 15Ω, that Vbe is 0.7 V, and Imax is 25 mA. Let RT = R1+R2+R3. Now R3/RT = Vbe/V = 0.7/5 = 0.14, and R1/RT = (V - Vbe \- ImaxR)/V = (5 - 0.7 - 0.025·15)/5 = 3.925/5 = 0.785. Thus R1+R3 = 0.925·RT, whence 0.075·RT = R2 = 10 KΩ, giving RT = 133 KΩ, R1 = 105 KΩ, and R3 = 19 KΩ. With these R1 and R2 values, each digital pot step should give a change in LED current of 25/256 mA, or about 98 μA.)

*\[Edit: When V1 is set to less than VBE, no current will flow through the LEDs. That is, to turn off the controlled LEDs, set V1 to VBE or less.\]*

**PWM with RC filter:**

It may be worthwhile to experiment with using a PWM-driven low pass RC filter to supply V1, possibly avoiding need for buffer amplifiers and digital potentiometers. See eg “Arduino’s AnalogWrite – Converting PWM to a Voltage” by Scott Daniels at provideyourown.com, and also see the filter-calculation page it refers to. You might need an oscilloscope to verify the design and its quality of results, and might need to use several RC filter stages in a row to adequately filter out ripple, but it can be done, at the cost of slower response to control changes.

**Transistor-power example calculations:**

Letting VCE, ICE, VBE, and IBE represent collector-to-emitter and base-to-emitter voltages and currents, transistor power dissipation is VCE·ICE+VBE·IBE. Because VBE·IBE is likely to be sub-milliwatt, we ignore it in following, taking P ≅ VCE·ICE.

In the LED-driving circuit, VCE = V – VLEDs – Vsense, where VLEDs is the series voltage across the chain of LEDs the transistor controls, and Vsense is the voltage across the sense resistor (ie, across R1 or R2 in the top figure).

In general, it is a good idea to keep Vsense small (under a volt) to allow a wider compliance range – ie, so that LED current is the same over a wider range of variation of supply voltage V. Thus, the approximation VCE ≅ V – VLEDs is reasonable.

Here is a concrete example: Suppose we have eight LEDs in series, and they are white LEDs with about 3.6 V forward drop at 20 mA. \[LEDs of different colors may have different drops; eg see LED color chart at oksolar.com.\] Then VLEDs = 8·3.6 V = 28.8 V. We need V(BR)CEO \> V \> VLEDs \+ VBE \+ Vsense, where V(BR)CEO = collector-emitter breakdown voltage (which is 40 V min. for 2N3904 or 2N2222). Allowing a volt for Vsense and 0.7 V for VBE we have V \> 28.8 + 0.7 + 1 = 30.5 V. Let's suppose V=32 V. Then P \< (32–28.8)·0.020 W = 64 mW. Thus a small general purpose NPN transistor will work, for example a 2N3904 (rated at 350 mW to 1 W, depending on package, before derating for ambient and heatsinking) or a 2N2222 (similarly rated).

For a second example, suppose VLEDs = 8·1.7 V = 13.6 V (for, eg, eight infrared LEDs at 50 mA) and V=32 V. Then P ≅ (32–13.6)·0.050 W = 920 mW, so a larger (and heatsinked) transistor would be needed. Or, V could be decreased, say to 16 V, giving P ≅ (16–13.6)·0.050 W = 120 mW, allowing use of a small transistor.

For a third example, suppose eight LEDs are paralleled (rather than seriesed), that VLEDs = 2.0 V at 20 mA, that Vsense is about 0.4 V at desired operating point, and that V=5 V. The transistor will need to drop 5-2-0.4 V = 2.6 V at 160 mA, which is 416 mW, probably large enough to require a heatsink. \[Note: if LEDs are placed in parallel and driven by a single transistor, some of them probably will be dimmer than others; “current hogging” may occur in some of the LEDs, making them brighter than the others. However, many cheap flashlights connect LEDs in parallel without individual current control.\]

---
Tags: led, potentiometer
---


title: Proportional water flow control

text:
# Question
Title: Proportional water flow control
I've been looking at water flow control with Arduino and I'm finding a huge difficulty in managing to do an 'analog' control on water flow. The mainstream solution seems to be the well known solenoid valve, however those seem to be binary (full flow, no flow), and I'm looking for a more variable answer.

Is it possible to get middlegrounds with solenoids? Maybe actuating them with less voltage or amperage will cause it to partially actuate? If not, does anyone know of embedded solutions using servos or steppers maybe?

# Answer
> 7 votes
> Is it possible to get middle grounds with solenoids?

No. The solenoid will be all or nothing. If you have used a magnet, you have seen that the force decreases rapidly with distance. As you move something closer, it will typically snap to a magnet at one point. The same thing happens in a solenoid valve: once you apply enough voltage to start motion, the motion will complete.

Side note: that is actually a common trick to saving much power with solenoid valve. You might apply 12 V to actuate, but then you can reduce the voltage very low (maybe 2 V or lower) and the valve will still say actuated.

So if you want flow, you need a flow control valve. A common 1/4 turn ball valve will provide the fractional flow you seek. You should be able to hook a servo or gear motor to that.

A typical ball valve will not provide a constant change of flow with angle. That means the change in flow between the first 5 degrees opening will be large while the last 5 degrees of motion will have little effect. If the application is not critical, that would be fine.

If you want more precise flow control, valves are made with a particular cutout in the ball that makes the flow control more linear. You can get a commercial type valve with motor attached in cost range of 100 $US. For hooking up to an Arduino, a Belimo flow valve (one example vendor) only seems appropriately named

These are commercial type valves used to control water in heater systems and such. They take a 0 - 10 V input signal as control and will rotate the vale. The keyword search is "motorized flow control valve" and that will find you many. These are not exotic, you will find many in all sorts of sizes. You may even find from a local plumbing supplier where you can pick one up at will call.

# Answer
> 1 votes
Do you use a pump to circulate the water flow, if so maybe you have a better result with a variable pump speed (PWM), in state of a variable valve opening.

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


# Question
Title: Activate a DC motor for a fixed amount of time
I have a single simple DC motor that upon a condition I wish to let it run for 3 minute. How can I do it in Arduino? a simple addition to the code will be great help.

As I use Adafruit motor shield this is my current code:

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

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
IOvalue = 1000

if (IOvalue = 1000) {

 //this is the motor I wish to run for 3 min
   myMotor->setSpeed(25);
   myMotor->run(FORWARD);
   delay(100);
 }
}

```

Thanks a lot

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

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
boolean motorRunning = false;
unsigned long motorStartMillis;
unsigned long motorRunMillis = 180000;

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
  IOvalue = 1000

  if (IOvalue = 1000) {
    //this is the motor I wish to run for 3 min
    myMotor->setSpeed(25);
    myMotor->run(FORWARD);
    motorStartMillis = millis();
    motorRunning = true;
  }

  // check if motor is running and time-to-run has elapsed
  if( motorRunning && (millis()-motorStartMillis > motorRunMillis) )
  {
    myMotor->setSpeed(0);
    myMotor->run(RELEASE);
    motorRunning = false;
  }
}

```
> 1 votes

# Answer
```
long int currentMillis;
void setup() {
    pinMode(motorPin, OUTPUT);
    digitalWrite(motorPin, LOW);
}
void loop() {
    if(condition is met){
        startOfMotor = millis();
        while(millis() != (startOfMotor+180000)){
            digitalWrite(motorPin, HIGH);
        }
    digitalWrite(motorPin, LOW);
    }
}

```

This `motorPin` is the pin to which the motor is connected. `millis()` gets the milliseconds after the board is started. 3 min = 180 seconds = 180000 ms.
> -1 votes

---
Tags: motor
---


# Question
Title: Need a simple accelerometer visualization example!
I'm doing a project using the ADXL335 accelerometer from SparkFun. The actual project I'm using P5 and it's working great. I'm running workshops in parallel and want to demo the chip in real-time but am currently out of time to build something from scratch. I'm desperate for a simple processing (or something else) sketch that takes my x, y, z values being printed to the serial port from Arduino and visualizes them in some way. Can anyone point me to anything that won't need a lot of coding time and effort just now?

Thank you! Claudia

# Answer
> -1 votes
A simple and fast solution would be implement a chart using a JavaScript library called Chart.js. it is simple and you can visualize your data in realtime.

Try node.js to make the back-end by communicating via serial (serialport package is good) and send the data using socket.io.

It is simple and you can set everything in less than 2 hours.

Chart.js

I recently made some video tutorials about this and you see them here. The audio is in Portuguese but you can just skip and go directly to coding sections.

---
Tags: accelerometer, processing-lang
---


# Question
Title: Do I have to use an external power supply when connecting an ultrasonic sensor to Arduino?
This might be a very stupid question but please bear with me. So I am using an HC-SR04 Ultrasonic sensor model (5 V) and I want to connect it to Arduino Uno. Do I have to use an external power supply for the ultrasonic sensor (just like with the motors) in order to connect it to the Arduino? Or can I just use the 5 V pin?

# Answer
From the question I assume you power your Arduino via USB in which case you don't need an external supply. The HC-SR04 draws 15 mA with is far below the specifications for USB. I did this myself some time ago:
> 1 votes

---
Tags: arduino-uno
---


title: Powering Arduino with car batteries

text:
# Question
Title: Powering Arduino with car batteries
Presumably, one powers an Arduino board with car batteries for long-term operation away from the power grid.

How can this be done, and what are the most (1) economic, and (2) reliable ways to do this? Specifically, do any additional risks to short the board with an extraneous discharge exist?

# Answer
Use a switching regulator such as the LM2596. You can get a ready board from eBay for about US$1.

Just set the output voltage to 5 V and feed the Vcc input of Arduino; this bypasses the onboard regulator.

The benefit is that unlike the linear onboard regulator, a switching regulator is very efficient which means less consumption and less generated heat on the regulator. An additional benefit is that it can withstand a higher input voltage (about 35 V for the specified regulator), just in case the circuit is used in a vehicle that has 24 V batteries.

The regulator has already several protections like for short circuiting, overheating, etc.
> 18 votes

# Answer
I'm a big fan of USB car chargers for things like this, or USB buck converter boards that you get from ebay.
> 3 votes

# Answer
There is also the higher-end Akafugu breadboard power supply - takes input from 7V all the way to 35V, but costs 11$ apiece in the bargain.

Akafugu
> 2 votes

# Answer
"Practical Arduino book" has a very interesting circuit for this purpose: http://www.practicalarduino.com/projects/vehicle-telemetry-platform

Here is how I've recreated it:

It uses LM2940CT and huge electrolytic cap - even if supply voltage drops, you'll have about a second to shut down your Arduino gracefully (close files on SD properly, and so on).

"Arduino Cookbook" (2nd ed.) has a chapter with examples on how to reduce Arduino's power consumption to absolute minimum - have a look at it, too.
> 2 votes

# Answer
Two more options - battery pack with convenient pre-made screw holes for Arduino, Raspberry.PI, and Beagle Board:

Smart Power Base

Kicking it up a notch - using a cordless drill's 18V battery. The project is meant for R.PI, but it would work just as well on Arduino, as the power supply is USB

Portable PI Power
> 2 votes

# Answer
Standard car batteries are 12.6 volts there are 6 2.1V cells. AGM batteries (i.e. Optima batteries, some interstates, and many other brands make AGM), in my experience with AGM batteries they are around 12.8 volts (I do not know the technical voltage). Without the car running you do not need to worry about voltage spikes **AS LONG AS THE WIRES TO AND FROM THE BATTERY ARE SHORT**. When the car is running the serpentine belt turns the alternator which is an AC generator. The alternator is connected to a rectifier to change it back to DC and the unit has a voltage regulator. When the car is running the alternator runs the electrical system and charges the battery. When you connect to the battery while the car is running you are actually connected to the alternator. When connected to the alternator there is a ton of electrical noise, voltage spikes, etc.

I have always had success connecting straight from the battery to the Arduino through its barrel jack connector, I have not tried any analog read function when the car is running. On the Arduino website it recommends 7-12V, however the limits (as listed on the Arduino website below the recommended) are 6-20. I have actually experienced problems with lower input voltages. If you feel uncomfortable just buy a 5 volt regulator and power through the usb.
> 1 votes

---
Tags: power, battery
---


title: Turn on led by phone and phone contacts

text:
# Question
Title: Turn on led by phone and phone contacts
I would like ask for help. Can you give me an advice how to create (contacts) nubers who can turn on led.

```
#include <GSM.h>
#define PINNUMBER ""
GSM gsmAccess;
GSMVoiceCall vcs;
char numtel[20];

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

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("Receive Voice Call");

boolean notConnected = true;

while (notConnected)
{
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
  notConnected = false;
else
{
  Serial.println("Not connected");
  delay(1000);
}
}

vcs.hangCall();

Serial.println("Waiting for a call");
}

void loop()
{

switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL:

  break;

case RECEIVINGCALL:

  Serial.println("RECEIVING CALL");

  vcs.retrieveCallingNumber(numtel, 20);

  digitalWrite(13, HIGH);

  vcs.answerCall();
  vcs.hangCall();
  digitalWrite(13, LOW);

  break;

  }
  delay(1000);
  }

```

# Answer
> 1 votes
So, `retrieveCallingNumber` is documented in here. It "retrieves the calling number, and stores it" in a character array passed as second argument.

The simplest solution to check if this number is among the allowed ones is to construct a string from this and compare it against a predefined string for equality. (If you have more than one allowed number, repeat for all.)

Something like this:

```
vcs.retrieveCallingNumber(numtel, 20);
String s = String(numtel);
if (s == "allowed number goes here") {
    // toggle LED etc.
}

```

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


# Question
Title: Arduino Java SerialEvent not being called (Rasberry PI) XPOST from stack overflow
I am following a simple example found here (example one), to have an Arduino connected to a Raspberry Pi and read some data from the Arduino on the Pi in Java.

The issue is that the SerialEvent method is never called, which implies that no data is coming in. However, when I open the Serial Monitor I can see that data is being read correctly.

The correct serial port is being used as well.

Here is the Java code.

```
//This class:
// - Starts up the communication with the Arduino.
// - Reads the data coming in from the Arduino and
//   converts that data in to a useful form.
// - Closes communication with the Arduino.

//Code builds upon this great example:
//http://www.csc.kth.se/utbildning/kth/kurser/DH2400/interak06/SerialWork.java
//The addition being the conversion from incoming characters to numbers.

//Load Libraries
import java.io.*;
import java.util.TooManyListenersException;

//Load RXTX Library
import gnu.io.*;

class ArduinoComm implements SerialPortEventListener
{

   //Used to in the process of converting the read in characters-
   //-first in to a string and then into a number.
   String rawStr="";

   //Declare serial port variable
   SerialPort mySerialPort;

   //Declare input steam
   InputStream in;

   boolean stop=false;

   public void start(String portName,int baudRate)
   {

      stop=false;
      try
      {
         //Finds and opens the port
         CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
         mySerialPort = (SerialPort)portId.open("my_java_serial" + portName, 2000);
         System.out.println("Serial port found and opened");

         //configure the port
         try
         {
            mySerialPort.setSerialPortParams(baudRate,
            mySerialPort.DATABITS_8,
            mySerialPort.STOPBITS_1,
            mySerialPort.PARITY_NONE);
            System.out.println("Serial port params set: "+baudRate);
         }
         catch (UnsupportedCommOperationException e)
         {
            System.out.println("Probably an unsupported Speed");
         }

         //establish stream for reading from the port
         try
         {
            in = mySerialPort.getInputStream();
         }
         catch (IOException e)
         {
            System.out.println("couldn't get streams");
         }

         // we could read from "in" in a separate thread, but the API gives us events
         try
         {
            mySerialPort.addEventListener(this);
            mySerialPort.notifyOnDataAvailable(true);
            System.out.println("Event listener added");
         }
         catch (TooManyListenersException e)
         {
            System.out.println("couldn't add listener");
         }
      }
      catch (Exception e)
      {
         System.out.println("Port in Use: "+e);
      }
   }

   //Used to close the serial port
   public void closeSerialPort()
   {
      try
      {
         in.close();
         stop=true;
         mySerialPort.close();
         System.out.println("Serial port closed");

      }
      catch (Exception e)
      {
      System.out.println(e);
      }
   }

   //Reads the incoming data packets from Arduino.
   public void serialEvent(SerialPortEvent event)
   {

      //Reads in data while data is available
      while (event.getEventType()== SerialPortEvent.DATA_AVAILABLE && stop==false)
      {
         try
         {
            //-------------------------------------------------------------------

            //Read in the available character
            char ch = (char)in.read();

            //If the read character is a letter this means that we have found an identifier.
            if (Character.isLetter(ch)==true && rawStr!="")
            {
               //Convert the string containing all the characters since the last identifier into an integer
               int value = Integer.parseInt(rawStr);

               if (ch=='A')
               {
                  System.out.println("Value A is: "+value);
               }

               if (ch=='B')
               {
                  System.out.println("Value B is: "+value);
               }

               //Reset rawStr ready for the next reading
               rawStr = ("");
            }
            else
            {
               //Add incoming characters to a string.
               //Only add characters to the string if they are digits.
               //When the arduino starts up the first characters it sends through are S-t-a-r-t-
               //and so to avoid adding these characters we only add characters if they are digits.

               if (Character.isDigit(ch))
               {
                  rawStr = ( rawStr + Character.toString(ch));
               }
               else
               {
                  System.out.print(ch);
               }
            }
         }
         catch (IOException e)
         {
         }
      }
   }

}

```

And here is the Arduino Sketch

```
//Arduino code for Part 01

//First we will define the values to be sent
//Note: The java code to go with this example reads-
//-in integers so values will have to be sent as integers
int valueA = 21;
int valueB = 534;

void setup()
{
   Serial.begin(115200);
   Serial.println("Start");
}

void loop()
{

   //We send the value coupled with an identifier character
   //that both marks the end of the value and what the value is.

   Serial.print(valueA);
   Serial.print("A");

   Serial.print(valueB);
   Serial.print("B");

   //A delay to slow the program down to human pace.
   delay(500);

}

```

I have read that changing `Serial.print()` to `Serial.write()` is the new way to do this, but changing this had no result.

# Answer
So the reason for no events being triggered was due to the program exiting and ending before it had the chance to.

To solve this i added a thread with a loop inside it inside the main thread.

```
public static void main(String[] args) throws Exception {
 ArduinoComm = new ArduinoComm ();
 main.start("/dev/ttyUSB0",115200);
 Thread t=new Thread() {
 public void run() {
 try {
 //Messy implementation but it works for this demo purpose
    while(true){
      //optional sleep
      thread.Sleep(500);
    }
 } catch (InterruptedException ie) {}
 }
 };
 t.start();
 System.out.println("Started");
 }

```

Bit of an oversight on my part.
> 1 votes

---
Tags: serial, programming
---


title: Making my own libraries

text:
# Question
Title: Making my own libraries
Does anyone know of a site or book where you can learn how to create, or for first reed, libraries. Because I think the libraries I use are sometimes unnecessary complicated, or have similar features, for example Wire and OneWire.

I think, these make my sketch unnecessary big, when I need both of them.

# Answer
> 3 votes
Arduino has a library tutorial here: http://www.arduino.cc/en/Hacking/LibraryTutorial

and a formal specification here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

these explain the specifics to making arduino libraries, like the propeties files, the keywords file, and the directory structure. Most of that is unnecessary though.

Anyway, there are not many differences between the actual code in an arduino library and the normal code you write for arduino sktech. The only major ones being that

* The arduino preprocessor doesn't generate function declarations - you have to make your own header file
* You can't use setup or loop

Other than that, its just normal c++ code that exposes a particular interface and provides an implementation. If you want the library to work well for a lot of users, you will need to put in the extra work to make it run on all the different arduino hardware variants.

Making libraries for c++ often involves creating .a, .so, .dll etc. files of compiled code that new programs can link against, but arduino compiles everything from source for every sketch so you don't need to worry about that here.

# Answer
> 1 votes
To address your query about libraries making sketch code too big...

I have recently completed (or rather, am in the process of completing) my first library, SevenSegmentSL1255. I too was concerned about the growing size of the library, as I incorporated more and more ideas. So I decided to plan for a "Lite" version, SevenSegSL1255Lite, so that the casual user would not feel to overwhelmed and also to reduce the memory footprint, for simple sketches.

However, after reading the Arduino page on the build process, I discovered that the whole library is not necessarily included in all sketches:

> The .c and .cpp files of the target are compiled and output with .o extensions to this directory, as is the main sketch file and any other .c or .cpp files in the sketch and any .c or .cpp files in any libraries which are #included in the sketch.
>
> These .o files are then linked together into a static library and the main sketch file is linked against this library. *Only the parts of the library needed for your sketch are included in the final .hex file, reducing the size of most sketches.*

So you see, from a memory footprint point of view, no matter how big the library may be, the resultant compiled sketch can still be quite small, depending on the amount of the library that is called for the sketch. From my point of view, this makes the "Lite" version of my library now somewhat redundant. Although, the argument for a simpler, more user friendly library may still exist.

As an aside, the resources that I used in creating the library are listed below:

---
Tags: programming, library
---


# Question
Title: How to discard same string received at Arduino
I don't want the same string to be printed again and again. I'm getting the data into an Excel sheet.

```
byte readValue1=0;
byte readValue2=0;
int add=0;
int row=0;
int Zigbee1=0,Zigbee2=0,Zigbee3=0;
void setup() {
    Serial.begin(9600);
        Serial.println("CLEARDATA");
        Serial.println("LABEL,Time,Zigbee,a1,a2,a3,a4,a5,a6,a7");
        row++;
}

void loop(){
  String a1,a2,a3;
  String c1,c2,c3;
  int b;

  if (Serial.available()>21){
        if(Serial.read() == 0x7E) {
            for(int i=0; i<10; i++){
                byte discard = Serial.read();
            }
                        add = Serial.read();
                       if(add == 33)
                        {
                        a1 = func1();
                        if(a1==c1){
                          b=0;
                        }
                        else
                        {
                          b = a1.length();
                        }
                        if(b != 0)
                       {
                        Zigbee=1;
                        Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                        Serial.print(","); Serial.println(a1);
                        row++;
                        }
                        }
                      else if(add == 48)
                        {
                        a2 = func1();
                        b = a2.length();
                        if(b != 0)
                      {
                        Zigbee=2;
                        if(a2!=c2){
                       Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                       Serial.print(","); Serial.println(a2);
                        }
                        c2=a2;
                       row++;
                        }
                        }

                       else if(add == 69)
                        {
                          a3 = func1();
                          b = a3.length();
                          if(b != 0)
                         {
                          Zigbee=3;
                          Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                          Serial.print(","); Serial.println(a3);
                          row++;
                    }
                        }
}
}
}

```

# Answer
> 0 votes
i solved it out by using comparing the received bits in that frame.. here is my code..

```
                   if(add == 33)
                    {
                    a1 = func1();
                    b = a1.length();
                    if(b != 0)
                   {
                    Zigbee=1;
                    if(a1!=c1)
                    {
                    Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                    Serial.print(","); Serial.println(a1);
                    }
                    c1=a1;
                    row++;
                    }
                    }
                  else if(add == 48)
                    {
                    a2 = func1();
                    b = a2.length();
                    if(b != 0)
                  {
                    Zigbee=2;
                    if(a2!=c2){
                   Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                   Serial.print(","); Serial.println(a2);
                    }
                    c2=a2;
                   row++;
                    }
                    }

                   else if(add == 69)
                    {
                      a3 = func1();
                      b = a3.length();
                      if(b != 0)
                     {
                      Zigbee=3;
                      if(a3!=c3)
                     {
                      Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                      Serial.print(","); Serial.println(a3);
                     }
                     c3=a3;
                     row++;
                }
                    }

```

# Answer
> 0 votes
Only print the string when he has changed?

```
String previousString = "";
String newString = "";

if(newString != previousString){
   println(newString);
   previousString = newString;
}

```

I'm not sure if it's applicable in your situation, just the first thing that came to my mind. You (kinda) should make a function of it, so that you don't have to copy/paste it all the time and it'll look way better.

EDIT:

A fuction could be made like so:

```
String previousString = ""; //Put this above your setup code (global variables)

void NoSpamString(String input){ //Put this block before the setup
   if(input != previousString){
      println(input);
      previousString = input;
   }
}

```

You can then use: `NoSpamString("text");` to print a line withouth spamming it.

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno wiring and code with Parallax PMB-688
I'm new to Arduino GPS and am wondering if I could be pointed in the right direction regarding code and wiring when hooking up my Parallax PMB-688 to an Arduino Uno

# Answer
> 1 votes
The following link was suggested in the comments by user PhillyNJ. Adding it here as a community wiki answer:

---
Tags: arduino-uno, programming, wires, tinygps
---


title: How to upgrade Arduino UnoR3 clock

text:
# Question
Title: How to upgrade Arduino UnoR3 clock
A little background:

I need to generate a 40KHz frequency as accurately as possible.

(One of my other posts is here: Stable frequency generation)

My code is solid- I'm using an Uno R3 and generating the most accurate frequency I can at this point. The only way to get a more accurate frequency is to upgrade the ceramic resonator to a crystal oscillator.

So, my over-arching question is: How do I actually upgrade the ceramic resonator to a crystal oscillator?

Things I'm considering are:

Is it worth it to actually upgrade my Uno R3 - and is it even possible? Is there a clone that drives the ATMega328p with a crystal oscillator that I could use instead? Is there simply just a better model for this application?

# Answer
> 1 votes
It's really easy to take an ATmega328 chip and wire it up on it's own. There are even instructions on the Arduino site on how to do it. Take a look at http://www.arduino.cc/en/Main/Standalone .

You could even pull the 328 out of the Uno, add the crystal and a few caps and then program it with the Uno board. I've done this a few times myself and it worked just fine for my needs.

# Answer
> 0 votes
Looking at the Arduino R3 reference design, it should have a crystal! But in practice it seems that the manufacturers are cutting corners and using a resonator because it is cheaper. I don't like your chances of fitting an xtal instead of a resonator. Unless you are a soldering expert and have suitable facilities, the most likely outcome is a dead board.

If your board has the MCU chip in a socket, you could bend the xtal pins so they don't go into the socket and solder a xtal and a couple capacitors to them. Not exactly a production line solution, but it will be fine if you just want a one-off - and anyone reasonably at home with a soldering iron could do it.

Freetronics (an Australian company) make a R3 compatable with xtals for both processors. These are very well made (I own two), and have a prototyping area as well. Downside is the higher cost. See http://www.freetronics.com.au/products/eleven#.VT3F-PCo1BA

---
Tags: arduino-uno, timing, oscillator-clock
---


title: calculating the input current

text:
# Question
Title: calculating the input current
I have been a bit confused about calculating the input current, so I'd be much obliged if someone could help.

Let's say that we have a potentiometer connected with an analog input as shown below. In a middle position the resistance of the potentiometer is spitted to R1 and R2.

How can I calculate the current in A0? How much will be the current value if (R1=0, R2=Rmax), (R1=Rmax, R2=0), (R1 and R2 !=0,Rmax)?

```
 5V --------
           |
           R1
           |
 A0 --------
           |
           R2
           |
          GND

```

# Answer
> 1 votes
When reading an analog voltage an analog pin has a very high resistance - usually very very much higher than the resistance of any potentiometer used, and input current to A0 can be regarded as zero for practical purposes.

For practical purposes the current drain from the supply will be that which flows from 5V to ground via R1 & R2.
I = V/R = 5V/(R1 + R2)

As for a potentiometer the sum of R1 + R2 is constant, the position of the pot-wiper makes no difference to current draw.

eg 10k pot. I\_supply = V/r = 5V/10K = 0.5 mA.
An I\_A0 ~= 0

---

The upper value of a potentiometer which should be used for an analog input is covered by the uC (microcontroller) data sheet. The key parameter is uC input bias currents flowing in the potentiometer and causing **small** voltages which affect the analog reading. A rule of thumb is to keep such voltages under about one LSB (least significant bit) of the ADC.

# Answer
> 1 votes
The input current of the ADC is low enough not to change the potentiometer's characteristic (which won't be perfectly straight, anyway).

The only requirement is that the impedance of the potentiometer (according to Thévénin equal to R1 parallel to R2) shouldn't be greater than 10 kΩ. That's because otherwise it takes too long for the ADC's capacitor to get charged.

---
Tags: current
---


title: ATMega I/O maximum current

text:
# Question
Title: ATMega I/O maximum current
According to the ATmega328P datasheet, the total current from **all I/O pins** must not exceed 200mA.

Let's say that an Output pin sources 30mA and an Input pin sinks 10mA. The total current should be 30+10=40mA or 30-10=20mA?

# Answer
> 4 votes
Neither. First, inputs don't draw current. Whether you're sourcing current or draining it, it will always be an output pin.

The 200 mA rule is probably determined by the bonding wires for the Vcc and ground pins on the die. That means that all outputs which are sourcing current shouldn't source more than 200 mA combined, as this current will have to enter the device through the Vcc pin.
Likewise all outputs sinking current shouldn't sink more than 200 mA combined, as this current will drain through the ground pin.

# Answer
> 0 votes
Usually you sum the magnitudes of the currents - so
|+30| + |-10| = 30 + 10 = 40 mA in your example.

Predictably but unfortunately. the principle of **TANSTAAFL** usually applies in such matters :-).

Such limitations are often (but not solely) dissipation based.
A low level output pin is dissipating ~= (Vo\_low) x I low and
a high level pin dissipates (Vdd-Vo\_high) x I\_high.
For low currents versus I\_pin\_max, Voutlow is ~= 0 and Vouthigh is ~= Vdd.
As currents approach design capacities Voutlow starts to rise and Vouthigh starts to fall (due to the internal 'switch' not being able to handle the current) and dissipation rises.

**IF** you pulled a high pin fully low or a low pin fully high then
at 5V and 200 mA IC dissipation = 1 Watt.
Under that sort of abuse other bad things may happen.

There MAY be some specialist cases where you can treat **SOME** high and low currents as semi independent but this would need a good understanding of the IC and probably still lies outside specification.

---
Tags: current
---


# Question
Title: Connect the output of an Arduino to the input from another Arduino
I'm making a project and i'm trying to send bits from an Arduino to another Arduino with the digital pins. So my setup are 2 Arduino's connected with a jumper. I connected the grounds and they have both a different power supply. Now I tried this set-up and as soon as I connect the output pin to the input pin from the other Arduino the voltage lowers from 5V to 2.6V so we can't detect our bits. Anybody an idea how to solve this problem?

Thanks in advance!

Kind regards, Manu

# Answer
As you are trying to communicate with two arduinos I will suggest you to use some sort of standard communication protocol such as Two wire interface or I2c. There is the Wire.h library you can use and it has also a reference on the main Arduino site. If you have different necessity and want to carry on with you're methods you need to specify in more depth the connections you have made. As for now I can guess that the output is being connected to ground or some sort of load and that might be the reason you are seeing a drop out of voltage. But it might be also the case that you're output pin is changing so fast that the multimeter is not capable of reading the high state correctly
> 2 votes

# Answer
As Harry mentioned better to use some communication lines like UART or I2C or SPI. If you dont have them available then use digital i/os but make sure their pull up and pull down resistors are correctly configured. If it is input just set as pull up and for output set as output pin. Regards, Pathik
> 1 votes

# Answer
I would suggest sticking a transistor in between - use a layout like http://en.wikipedia.org/wiki/Transistor#/media/File:Transistor\_Simple\_Circuit\_Diagram\_with\_NPN\_Labels.svg (from the wiki page on transistor).

Note that Vout should be connected to the input pin on one arduino, and Vin should connect, via a resistor, to the output pin on the other arduino.

Just to confirm, the labels are reversed from what you will expect them to be.

The 2 resistors can be anything \> 1kOhm.

This still depends on the common ground.

Note that common ground may not be a good idea if they are generated from the same power source - I've found ground from two USB ports on the same laptop to be at different levels, so current will flow out from one port, and in the other, probably damaging the laptop, if the two grounds are connected.
> 0 votes

# Answer
First of all, I cannot say if your protocol will work or not since I don't have the details. However, switching protocols will give you the same result. Also, you do not need a transistor for this usage.

The solution is to connect the grounds of the different power sources. Since voltage is relative, having the grounds disconnected will lead one device to think that the voltage is higher/lower than the other one thinks (they have different reference point).
> 0 votes

# Answer
Are you sure one pins is configured as input? If one would be output high and the other output low you basically get a short circuit: from Vcc through the top FET of the high output, through the wire to the other Arduino, and into the lower FET of the low output, and back to ground.
If the short circuit were perfect the voltage would drop to zero, but both FETs have a non-zero resistance, which makes them a voltage divider.

One way to protect your Arduino against this (such a short circuit does damage the I/O circuits!) is to place a 1 kΩ series resistor between the pins. Since an input pin won't draw any current there won't be a voltage drop across the resistor either.

I wouldn't use Harry's I2C, because it's probably too complicated for your needs. (I don't know what data you want to exchange). A simple connection is the UART: one transmit line and one receive line. It's true that the UART is used for the USB communication, but that connection goes via a set of resistors, so that another controller using the bus should be able to override the USB's signals.

If you have a long distance between the Arduino's you'll want RS232 level shifters.
> 0 votes

---
Tags: communication
---


# Question
Title: What is the best way to define an I/O pin?
I read definitions like

```
const int ledPin = 9;

```

and also

```
#define ledPin 9

```

I know that a definition like

```
int ledPin = 9;

```

is a bad practice if you're not going to change it (which you usually won't), though I've see this several times in Arduino programs. Which one of the other two is preferred?

# Answer
> 7 votes
`#define ledPin 9` is preferred. By doing `int ledPin = 9;` you will be allocating an `int` memory whose value is used every time you use `ledPin`. `#define` is different in the sense it doesn't allocate memory. there is no memory called `ledPin`. Before compiling all "ledPin"s in the code(other than strings) are replaced by `9`. So basically

```
digitalWrite(ledPin);

```

becomes

```
digitalWrite(9);

```

Advantages of `#define` : Saves memory and since all `ledPin` are replaced by `9` **before execution**, it saves processor time.

Doesn't really matter in small codes...

# Answer
> 6 votes
Strictly speaking, the `#define` approach will use slightly less memory. The difference is usually tiny though. If you need to reduce memory usage, then other optimisations would probably be far more effective.

An argument in favour of using `const int` is **type safety**. Wherever you refer to that pin number by variable, you know exactly what data type you're getting. It might be promoted/converted implicitly or explicitly by the code which uses it, but it should behave in very clear ways.

By contrast, the value in a `#define` is open to interpretation. The vast majority of the time, it probably won't cause you any problems at all. You just need to be a little careful if you have code which makes assumptions about the type or size of the value.

Personally, I almost always prefer type safety unless I have a very serious need to save memory.

# Answer
> 4 votes
Probably the best way would be
`const uint8_t LED_PIN = 9; // may require to #include <stdint.h>`
or
`const byte LED_PIN = 9; // with no include necessary`
`const unsigned char LED_PIN = 9; // similarly`
The name is in caps as per general practice in C++ (and others) to name constants. This should not use any RAM in itself, and use about 1 byte of program memory per use.
However, there *might* be problems when the number is higher than 127 and is sign-extended while getting promoted to larger signed integers (not entirely sure on this), although that is unlikely to happen with pin numbers.

# Answer
> -1 votes
Not only will

```
const int ledPin = 9;

```

take up RAM, but in this case, will use more RAM than necessary as `digitalWrite(uint8_t, uint8_t)` only needs one-byte arguments, and an int is usually two bytes (compiler-dependent, but typical). Note that you can give the literal an explicit type in the #define:

```
#define ledPin ((int)9)

```

though in a context such as a function argument where a specific type is required (because the function was properly prototyped!) it would either be implicitly cast or get an error message if the types don't match.

---
Tags: programming
---


# Question
Title: Do I need Kalman Filter after I read DMP data on MPU6050?
In my project I need to use as noiseless as possible data from a MPU6050, I do have some nice DMP data, what will happen if I apply Kalman filter above it? Will I get more noiseless data? Or will it become unreliable anymore? Are there any benefits to do that ?

# Answer
The DMP data from the MPU6050 is already filtered, and while I have not expirimented with the DMP data much myself I believe it is pretty clean. If there is a calibration process you can do to improve it, that is probably worth expirimenting with, but you should not filter the values a second time.

You should figure out what your application's noise tolerance actually is before worrying about different filters. There are potential benefits to your own filter, I think knowing exactly how it performs in edge cases and being able to calibrating it to your specific problem could be beneficial; However, it could also end up being worse than the DMP. Don't forget that filter calculations can generally take a few milliseconds for an arduino to run that you don't have to worry about with the DMP.

If you do work on your own filter, you will need to turn off the DMP and filter the raw values. Look into complementary, mahoney, and madgwick filters as well as kalman, which is quite computationally expensive. Using an existing library or an implementation from an open source quadcopter project is probably most efficient. The math associated with kalman filters and 3d rotations gets very complicated very quickly.
> 2 votes

---
Tags: i2c, mpu6050
---


title: Serial LED control

text:
# Question
Title: Serial LED control
Hell0!

I run in small problem. I am try to control LED's by serial port.So I am expect to send "1" and two LED's will start to blink or send "0" and only one LED is constantly lighted up. At first I thought that do-wile will work, Arduino will run do loop while value sent by serial port is "1" or "0". However at first I sent "0" and one LED are lighted, after I send "1" and two LED's are blinking. But when I send "0" again, LED's keeps blinking. What should I change in my code?

```
const int ledPin2=2;
const int ledPin3=3;
const int ledPin4=4;

void setup()
{

  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);

 Serial.begin(9600);
}

void loop()
{
  while (Serial.available()==0);

  int serialVal = Serial.read()-'0';

  do
   {
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4,HIGH);
    } while(serialVal==0);

  do
    {
      digitalWrite(ledPin4,LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);

      delay(100);

      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin2, LOW);

      delay(100);

  }while (serialVal==1);
};

```

# Answer
I don't think you understand how your code is being executed. I would recommend trying the following.

```
const int ledPin2=2;
const int ledPin3=3;
const int ledPin4=4;
int serialVal;

void setup()
{

  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);

 Serial.begin(9600);
}

void loop()
{
  // If data is available, then read it!
  if (serial.available() > 0)
  {
      serialVal = serial.read()-'0';
  }

  // If serial val is 1, turn on LEd4, turn off Led3
  if (serialVal == '1')
  {
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4,HIGH);
  }

  // If serial val is 0,
  // turn on LED2. Turn off Led3
  // delay for 100ms
  // turn of LED2, turn on LED3
  // delay for 100 ms
  if (serialVal == '0')
  {
      digitalWrite(ledPin4,LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);

      delay(100);

      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin2, LOW);

      delay(100);
  }

}

```

The reason why your code doesn't work, is once you are within a do while loop, you will not be allowed to exit until the condition is met. If you are not scanning for more serial values within that do while, you will get stuck there forever.

Another reason why you might be confused, is how digitalWirte operates. There is no need to loop over a digitalWrite, as the pin will stay HIGH, or LOW until you change its state. Once you digitalWrite(HIGH) that pin will stay high until it is told to go LOW.
> 1 votes

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


# Question
Title: Arduino Standalone - photo shows incorrect pin wired to MOSI
I have been building a standalone Arduino on a breadboard following the guide, Building an Arduino on a Breadboard. The guide is generally very good, however, I have yet to get the Arduino working, for a number of various reasons, be it misinterpreted, or misread instructions (the reset pull-up resistor connected to GND instead of Vcc, Tx to Tx, instead of Tx to Rx (and vice versa), to name but a few issues that I have had to resolve). However, I am sure that the following issue is not down to my careless interpretation or lack of attention.

Look at the photo taken from the webpage, Building an Arduino on a Breadboard, on the Arduino website, showing the *Sparkfun AVR programming adapter* connected to the ATmega IC.

The MOSI on the adapter is shown to be connected, via a dark green wire, to pin 16 on the ATmega chip, whereas the instructions say:

> Be sure to refer to the Arduino pin mapping for help wiring this up.
>
> * The MISO pin of your adapter will go to pin 18 or Arduino digital pin 12 of your Atmega chip.
> * The SCK pin of your adapter will go to pin 19 or Arduino digital pin 13 of your Atmega chip.
> * The RESET pin of your adapter will go to pin 1 of your Atmega chip.
> * The MOSI pin of your adapter will go to pin 17 or Arduino digital pin 11 of your Atmega chip.

According to the pinout below, Pin 16 is SS and pin 17 is indeed MOSI.

So, to my mind, the photo is definitely wrong. Indeed I was getting avrdude errors when trying to use a USBasp to load a bootloader, when using the wiring as shown in the photo. When I correctly wired MOSI, from the adapter, to pin 17, the avrdude errors disappeared.

Am I correct in my thinking? Has anyone else attempted to build this circuit, following the instructions on the Arduino website, and come across this issue?

I am just looking for confirmation that I am right, before I contact the owner of the web page.

# Answer
I have programmed AVR microcontrollers for a while. I would follow the datasheet, instead of the guide you have.

The Atmega168 Pin Mapping shows SS on 16, MOSI 17, MISO 18, SCK 19 and you will also need to connect to RST 1
> 4 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Why does timer1 not generate correct period on CTC mode with a resolution of 5us?
I have defined my code to generate an interrupt over each 5μs on CTC mode using timer1 but the output shows a time of ~15μs.

Following the equation to set the counting number to achieve the desired time

```
(# timer counts + 1) = (target time) / (timer resolution)

```

I've got OCR1A = 79 for a desired time of 5μs using no prescaler and a source clock of 16MHz on Arduino Uno.

My code is as follows:

```
// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define LEDPIN 9

void setup()
{
    pinMode(LEDPIN, OUTPUT);
    digitalWrite(LEDPIN, HIGH);

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 79;

    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for no prescaler:
    TCCR1B |= _BV(CS10);

    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

void loop () {}

ISR(TIMER1_COMPA_vect)
{
  digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}

```

This is the output from my logic analyzer:

Is it a limitation of the Arduino or am I missing something?

My idea is to generate a PWM manually to control a servo motor using timer1 and precisely increase the period by 10μs during "on" time and get the desired angle.

After some experiments, I have discovered that my motor (MG996R) has a range from 0.6ms to 2.1ms during "on" time to move from 0 to 180 degrees.

I have tried the Arduino's Servo library but it goes far than 180 degrees (I don't know why). That's why I am building my own code for that purpose.

# Answer
> 3 votes
I got it working just analyzing time consumption of digitalWrite and digitalRead functions. They took around 13us to execute (each one), so this added up a few extra undesired microseconds to the final period.

Instead, I set up digital output using DDRD for configuring and PORTD for setting the desired output, which results in approximately 1us to set the output value (HIGH or LOW).

I changed the prescaler to 8 and the code below shows how to get a 100kHz wave output with 5us duration of "on" time using timer1 CTC mode.

```
void setup()
{
    DDRD = B00001000; // pin 3 as output
    PORTD &= ~_BV(PORTD3);   // set 3 as LOW

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 9;

    // turn on CTC (Clear Timer on Compare Match) mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for clk/8 prescaler:
    TCCR1B |= _BV(CS11);

    // Output Compare A Match Interrupt Enable
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

ISR(TIMER1_COMPA_vect)
{
  PORTD = ~PORTD;
}

```

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