title: Hall sensor noise removal

text:
# Question
Title: Hall sensor noise removal
I am using Arduino Duemilanove and a hall effect sensor to calculate the speed of a motor. When I used sensor out directly to Interrupt0, the rising edges of noise were also detected. So the speed calculation went wrong.

So now sensor is connected to A0.and a threshold is put. Pin No 13 is connected to Interrupt 0(Pin 2). I use the following code.

```
volatile byte count;
 const int analogPin = A0;
 const int digitalPin=13;
 const int threshold =20;
 unsigned int rpm;
 unsigned long starttime;

 void setup()
 {
   pinMode(digitalPin,OUTPUT);
   digitalWrite(analogPin,HIGH);
   digitalWrite(digitalPin,HIGH);
   Serial.begin(9600);
   attachInterrupt(0,sense,FALLING);
   rpm=0;
   starttime=0;
   count=0;
 }
 void loop()
 {
   int sensorValue = analogRead(analogPin);
   Serial.println(sensorValue);
   if (sensorValue < threshold)
   {
     digitalWrite(digitalPin,LOW);
     if (count>=20)
     {
       rpm=60*1000*count/(millis()-starttime);
       starttime=millis();
       count=0;
       Serial.println(rpm,DEC);
     }
   }
   else
   {
     digitalWrite(digitalPin,HIGH);
   }

 }
 void sense()
 {
  count++;
 }

```

But I get actual speed only in between. The speed changes back . I feel there is some problem with the sampling or rpm updation. Looking forward for help

# Answer
It sounds like you need a debouncing circuit.
You can do it in code, but you are then trying to execute more code in you interrupt handler. I would go for a hardware version. I don't have the circuit to hand but if you search for a 'Schmidtt Trigger' based debouncing circuit. You can implement it with 5 resistors, a capacitor, a LM386 OpAmp and a CMOS XOR IC (Inverts the signal which the inverting Schmidtt trigger inverts).

What happens is the Schmidtt trigger goes low when the input passes a certain voltage. It remains low until the voltage passes the low voltage threshold at which point it goes high. The CMOS XOR IC (I think its a 4004??) takes two inputs and inverts them. It also adds extra hysteresis which further damps the bouncing.

The values of your resistors affect the thresholds, but there are plenty of calculators on the web that will solve the values for you.

The LM386 has two channels and the CMOS usually has 4 so it becomes quite easy to debounce multiple signals.

Hope that helps.
> 1 votes

# Answer
```
       rpm=60*1000*count/(millis()-starttime);

```

Since rpm is an unsigned int (which has a maximum of 65535) you will almost certainly overflow if count is more than 1, which will give you negative numbers, or incorrect positive numbers.

Plus, outputting to serial constantly will cause the program to lock up waiting for the serial buffer to empty, which will throw out any timings you are doing.

I suggest making rpm unsigned long (or float as you seem to have done already) and only display the RPM every second or so.

---

Also see my page Using the Arduino Analog Comparator. This is a much faster way of detecting an analog signal merely passing some threshold. This only takes a few microseconds compared to 104 µS for a single analogRead. In the ISR then you just add one to a counter (which is the number of times it passes the threshold). Every second take this counter, and work out the RPM, then zero it. Make sure you make a copy of the counter in a protected way as shown on my page about Interrupts.
> 0 votes

# Answer
A possibility I am toying with for a similar problem is realizing that there will always be a delay between valid sensor readings. For example, imagine you had a maximum speed of 10 revolutions/second. That would mean that there would be a maximum of 10 sensor inputs/second or 1 interrupt every 100 msecs.

If you changed your interrupt processing logic to something like:

```
if (millis() - timeOfLastSensorReading >= 10) {
   count++;
   timeOfLastSensorReading = millis();
}

```

Then your logic would become "Only register a sensor change if at least 10 msecs has passed since the last reading".

You might have to tune the values based on your real situation ... but it might go a long way to eliminate some aspects of false readings.
> 0 votes

---
Tags: sensors, motor
---


# Question
Title: How do you make the arduino go forward,backward and stop using Infrared?
Please give me a code and diagram use makeblock i.r sensor V2.1 and makeblock remote. It should be connected to a d.c motor that works with a h-bridge.It also has to be a dual motor which combines these two codes:

1:This one for the movement

```
const int controlPin1 = 2; // connected to pin 7 on the H-bridge
const int controlPin2 = 3; // connected to pin 2 on the H-bridge
const int enablePin = 9; // connected to pin 1 on the H-bridge
const int directionSwitchPin = 4; // connected to the switch for direction
const int onOffSwitchStateSwitchPin = 5; // connected to the switch for turning the motor on and off
const int potPin = A0; // connected to the potentiometer's output

// create some variables to hold values from your inputs
int onOffSwitchState = 0; // current state of the On/Off switch
int previousOnOffSwitchState = 0; // previous position of the on/off switch
int directionSwitchState = 0; // current state of the direction switch
int previousDirectionSwitchState = 0; // previous state of the direction switch

int motorEnabled = 0; // Turns the motor on/off
int motorSpeed = 0; // speed of the motor
int motorDirection = 1; // current direction of the motor

void setup()
{
    // intialize the inputs and outputs
    pinMode(directionSwitchPin, INPUT);
    pinMode(onOffSwitchStateSwitchPin, INPUT);
    pinMode(controlPin1, OUTPUT);
    pinMode(controlPin2, OUTPUT);
    pinMode(enablePin, OUTPUT);

    // pull the enable pin LOW to start
    digitalWrite(enablePin, LOW);
}

void loop()
{
    // read the value of the on/off switch
    onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
    delay(1);

    // read the value of the direction switch
    directionSwitchState = digitalRead(directionSwitchPin);

    // read the value of the pot and divide by 4 to get
    // a value that can be used for PWM
    motorSpeed = analogRead(potPin) / 4;

    // if the on/off button changed state since the last loop()
    if (onOffSwitchState != previousOnOffSwitchState)
    {
        // change the value of motorEnabled if pressed
        if (onOffSwitchState == HIGH)
        {
            motorEnabled = !motorEnabled;
        }
    }

    // if the direction button changed state since the last loop()
    if (directionSwitchState != previousDirectionSwitchState)
    {
        // change the value of motorDirection if pressed
        if (directionSwitchState == HIGH)
        {
            motorDirection = !motorDirection;
        }
    }

    // change the direction the motor spins by talking
    // to the control pins on the H-Bridge
    if (motorDirection == 1)
    {
        digitalWrite(controlPin1, HIGH);
        digitalWrite(controlPin2, LOW);
    }
    else
    {
        digitalWrite(controlPin1, LOW);
        digitalWrite(controlPin2, HIGH);
    }

    // if the motor is supposed to be on
    if (motorEnabled == 1)
    {
        // PWM the enable pin to vary the speed
        analogWrite(enablePin, motorSpeed);
    }
    else
    { // if the motor is not supposed to be on
        //turn the motor off
        analogWrite(enablePin, 0);
    }
    // save the current On/Offswitch state as the previous
    previousDirectionSwitchState = directionSwitchState;
    // save the current switch state as the previous
    previousOnOffSwitchState = onOffSwitchState;
}

```

2: This one for the IR:

```
#include "IRremote.h"  //-----( Import needed libraries )-----
int receiver = 11; // ----- DAT pin of IR receiver to Arduino digital pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);           // create instance of 'irrecv'
decode_results results;            // create instance of 'decode_results'

void setup()    /*----( SETUP: RUNS ONCE )----*/
{
    Serial.begin(9600);  // Begin serial communication
    Serial.println("IR Receiver Raw Data + Button Decode Test");
    irrecv.enableIRIn(); // Start the receiver
}               /*--(end setup )---*/

void loop()     /*----( LOOP: RUNS CONSTANTLY )----*/
{
    if (irrecv.decode(&results)) // have we received an IR signal?
    {
        //    Serial.println(results.value);  // Uncomment to print raw decimal values
        translateIR(); // run function "translateIR"
        irrecv.resume(); // receive the next value
    }
}               /* --(end main loop )-- */

/*-----( Declare User-written Functions )-----*/
void translateIR()  // translate Makeblock remote raw values to keys
{
    switch (results.value)
    {
        case 4219133059:      Serial.println(" A ");     break;
        case 667718909:       Serial.println(" B ");     break;
        case 3478241646:      Serial.println(" C ");     break;
        case 1322193145:      Serial.println(" D ");     break;
        case 3689098103:      Serial.println(" ^ ");     break;
        // case 3478241646:      Serial.println(" E ");     break;
        case 1776008254:      Serial.println(" < ");     break;
        case 1803700378:      Serial.println(" * ");     break;
        case 3495019267:      Serial.println(" > ");     break;
        case 1943112141:      Serial.println(" 0 ");     break;

        case 3444686410:      Serial.println(" v ");     break;
        case 2806989789:      Serial.println(" F ");     break;
        case 3689098101:      Serial.println(" 1 ");     break;
        // case 3689098103:      Serial.println(" 2 ");     break;
        case 1943112142:      Serial.println(" 3 ");     break;
        case 3689098102:      Serial.println(" 4 ");     break;
        // case 3689098102:      Serial.println(" 5 ");     break;
        case 2181502997:      Serial.println(" 6 ");     break;
        case 650941290:       Serial.println(" 7 ");     break;
        case 402038415:       Serial.println(" 8 ");     break;
        case 945450753:       Serial.println(" 9 ");     break;
        default:     Serial.println(" other button   ");
    }

    delay(250);
} //END translateIR

```

# Answer
> 2 votes
You should be able to search on Google and get a library to interface with the sensor. Then you will need some motors, a motor controller, and a library to control that. Then you will need to stick it all together using your code.

What you need to do is:

* Search for your IR library and a tutorial.
* Search for a Stepper motor tutorial and library.
* Then post a question when you are stuck with that.

# Answer
> 1 votes
You need a good IR Library, or tons of low-level knowledge.

Ken Shirriff wrote the best IR library out there! Here it is.

Adafruit writes awesome tutorials too. Here's one.

---
Tags: arduino-uno
---


# Question
Title: arduino project for c programming language
i am a student from 2nd semester BCA (Bachelor in Computer Application). My group need some project for presentation from c programming language so i thought of using #ARDUINO project for our presentation . i really don't have any idea in this project so any ideas, answer, guides will be helpful to us.

# Answer
Good luck with this! Arduino is awesome. I really enjoy using it. You may find this at least a little insightful: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html.

Arduino is a small computer. It can do essentially whatever you want it to do: drive robots, fly airplanes, control motors, turn on or off TVs, get on the internet, make a home alarm, buzz a speaker, make a touch lamp, fade LEDs, play music (even with *no* music chip; just using a skillfully-written library), control HollyWood action cameras, talk to your smartphone, read your heartbeat, make a bike speedometer or odometer, read a GPS receiver, etc. Cool stuff!
> 2 votes

# Answer
I am not going to list example-projects as the possibilities with an arduino are endless. If you are looking for inspiration: take a look at websites like www.instructables.com and www.hackaday.io. Those are websites with mostly starter arduino projects that contain step-by-step guides on how they are created. I would suggest that you browse through those projects and look for something that peaks your interest and then think of your own similar project. You should however think of a project with a certain complexity as it is for your bachelor's. Most projects on instrucables lack the challenge. For getting parts: take a look at ebay. Ebay has some webshops that sell arduino's and arduino extension modules really cheap. Good luck
> 0 votes

---
Tags: programming, arduino-mega, c
---


title: Any chance of repairing Mega 2560?

text:
# Question
Title: Any chance of repairing Mega 2560?
So I decided it would be a good idea to flash a firmware onto my mega 2560 for a project. I ended up flashing the wrong side of the ICSP header (one near the usb plug/ M16U2) and killed my arduino for the most part. I'm a newb for the most part when it comes to this. I plug it in and the 'L' light is on with the 'ON' light as well. Wont show up in device manager, can't load sketches and can't get into DFU mode.(REV3 has DFU right?)

I have both a usbasp and USBtinyisp programmer and have tried 5 - 10 firmwares on both sides of the headers in hopes I can get it to work again.Literally almost tried everything I could find to get it to flash back. One guide I did find that got me somewhere was this though:

http://forum.arduino.cc/index.php?topic=96706.0

It appears to flash correctly with whatever firmware I use, but cannot pull the firmware off it to check or do the rest of what it says.My guess is that 1 or 2 of the firmware's are gone. Have erased the firmware/relfashed and tried to flash in the IDE with no luck in it working.

I did use this command to read the firmware(or lack of) on both sides of the header to get a better idea of what might be going on:

M16U2/M2560

I don't know if I'm supposed to flash one side first then the other or flashing one will be able to do both at the same time. Here is an example of how I would flash from avrdude:

```
avrdude -C avrdude.conf -P usb -p m16u2 -b 1200 -c usbasp flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m

```

With each side I would set the correct the fuses from what that file pulled up. So if anyone knows what I'm doing wrong for why it is not working I'd appreciate the help. Just don't know if I can save this or it's gonna end up in the garbage.Thanks

# Answer
> 2 votes
http://altlab.org/d/m/jpralves/recover\_atmega2560/

Change fuses/firmware depending on which side you are flashing (M2560/M16U2)

Firmwares: Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex / stk500boot\_v2\_mega2560.hex

1st command:

```
avrdude -C avrdude.conf -P usb -p m16U2 -b 57600 -c usbtiny -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m

```

2nd command:

```
avrdude -c usbtiny -p m16U2 -P usb -b 115200 -V -U flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex

```

3rd command:

```
avrdude -c usbtiny -p m16U2 -P usb -b 115200 -U lock:w:0x0F:m

```

http://pastebin.ca/3178420

---
Tags: arduino-mega, avrdude, programmer, firmware
---


# Question
Title: Reading from a KY-040 rotary encoder with Digispark
I have a rotary encoder KY-040 connected to a Digispark like this:

CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).

I did everything like the instructions here: http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/

```
#include <DigiKeyboard.h>

 int pinA = 0;  // Connected to CLK on KY-040
 int pinB = 2;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.println("Rotated: ");
     if (bCW){
       //Serial.println ("clockwise");
       DigiKeyboard.sendKeyStroke(KEY_V); //or DigiKeyboard.write("1");
     }else{
       //Serial.println("counterclockwise");
        DigiKeyboard.println("cc");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

```

I only changed the pin numbers in the code and the `Serial.println (...` to any of the following:

```
DigiKeyboard.write("1");
DigiKeyboard.println("1");
DigiKeyboard.sendKeyStroke(KEY_V);

```

All of them didn't do anything when rotating the knob...

Any ideas? Maybe the 10K resistors are too much?

# Answer
Shown below is a KY-040 test program that in my tests doesn't lose any counts and is more accurate than some other software; it picks up the counts between detents as well as those at detents. You may be able to adapt it to your DigiKeyboard ATtiny system.

```
/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

```

Since some ATtiny's only have one external-interrupt pin, it may be necessary to use two pin-change interrupts instead of two external-interrupt pins. (Six of the pins on an ATtiny45, for example, support pin-change interrupts, and only one is an external-interrupt pin.) Change PinA and PinB to appropriate pin numbers, and replace

```
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);

```

with

```
  enableInterrupt(PinA, pinChangeISR, CHANGE); // Set up pin-change interrupts
  enableInterrupt(PinB, pinChangeISR, CHANGE);

```

and add the following `#include` near the beginning:

```
#include <EnableInterrupt.h>

```

To install the .h file for use via the Arduino IDE, unpack an `EnableInterrupt` zip file (for example, `enableinterrupt-0.8.2.zip` from bintray.com/greygnome) in the directory `~/sketchbook/libraries`. I think the package works with ATtiny's as well as more-standard Arduinos.
> 4 votes

# Answer
```
 int pinA = 0;  // Connected to CLK on KY-040
 ...
   Serial.begin (9600);

```

Hardware Serial uses pins 0 and 1. I would try other pins. (Oh, it's an ATtiny - well I'm not sure about HardwareSerial on that, but it looks suspicious).

See my page about rotary encoders for more ideas.

---

> I only changed the pin numbers in the code and the Serial.println (... to any of the following:

Maybe post the code you actually used, that would be helpful. Not some code you didn't use.

---

> Maybe the 10K resistors are too much?

No, that looks fine.
> 2 votes

---
Tags: attiny, rotary-encoder
---


# Question
Title: how to change variable when a button connected to pin 2 is pressed
Hi i am writing a code where, i have to switch a variable called toggle from 0 to 1 to 0.... every time the button is pressed (the button is on a 2 pin). I am a little lost as I am new to arduino need some help. Thank you

# Answer
> 2 votes
Go here --\> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.

Those 3 are key.

Also, I wrote a buttonReader (debouncing) library here.

Sounds like you're a beginner, so check out Adafruit's tutorials here.

And lastly, I've compiled links to all my knowledge at the bottom of my article here.

# Answer
> 2 votes
What you need is to detect a *transition*. That is, either:

* It was closed and is now open.

Or:

* It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:

```
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
bool toggle;

void setup ()
  {
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    toggle = !toggle;   // toggle the variable
    delay (10);         // debounce
    }  // end of state change

  // other code here ...

  }  // end of loop

```

---

For more information see my post about switches.

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


# Question
Title: I2C 2 way communication between Arduino Uno and Arduino Mega
If I remove the transmission code from slave this works properly but I need to transmit from slave.

Here is my master code

```
#include <Wire.h>
void setup() {
  Wire.begin(3);
  Wire.onReceive(receiveEvent);
}
byte x = 0;

void loop() {
  Wire.beginTransmission(9);
  Wire.write("s");
  Wire.write(x);
  Wire.endTransmission();
  x++;
  delay(500);
}

void receiveEvent(int howMany) {
  if(Wire.available()){
    int x = Wire.read();
    Serial.println(x);
  }
}

```

Here is my slave code:

```
#include <Wire.h>
void setup() {
  Wire.begin(9);                // join i2c bus with address #9
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

void receiveEvent(int howMany) {
  if(Wire.available()){
    char c = Wire.read();
    Serial.print(c);
    if(c == 's'){
      int x = Wire.read();
      Serial.println(x);
      //transmit to master
      Wire.beginTransmission(3);
      Wire.write(1);
      Wire.endTransmission();
    } else {
      Wire.read();
    }
  }
}

```

Is it possible not to use Wire.onRequest(requestCallback); to send data to master? Kindly help.

# Answer
To join the bus as a master you cannot supply a 7-Bit slave address so your code has two slaves.

Below you will find 2 sketches that successfully sends data to a slave. I would suggest you start looking at the I2C protocol and understand there are 4 Modes:

* Master-\>Transmitter
* Master-\>Receiver
* Slave-\>Transmitter
* Slave-\>Receiver

All communications regardless of how the data is transferred requires a master. It's the master that controls the clock pulses, thats why its always the master that initiates the communcation.

The MasterReader/MasterWriter tutorials on the arduino forum should now possibly start to make a little more sense when understanding those modes.

This code shows how a master sends data to a slave, and then how it requests data from the slave. If we look at this code from the master point-of-view, you can see it essentially says, send this byte to the client (m-\>t & s-\>r), then request data from the slave (m-\>r,s-\>t)

**Master Code**

```
#include <Wire.h>

#define SLAVE_ADDRESS 0x60

void setup()
{
  Wire.begin();
  randomSeed(analogRead(3));
  Serial.begin(9600);
}

byte x = 0;

void loop()
{
  x = random(0,255);
  Serial.print("Sent: ");
  Serial.print(x, HEX);
  Serial.print("\n");
  Wire.beginTransmission(0x60);
  Wire.write(x);
  Wire.endTransmission();
  delay(500);
  Serial.println("Requesting Data");
  Wire.requestFrom(SLAVE_ADDRESS, 1);

  int bytes = Wire.available();
  Serial.print("Slave sent ");
  Serial.print(bytes);
  Serial.print(" of information\n");
  for(int i = 0; i< bytes; i++)
  {
    x = Wire.read();
    Serial.print("Slave Sent: ");
    Serial.print(x, HEX);
    Serial.print("\n");
  }
  delay(500);
}

```

**Slave Code**

```
#include <Wire.h>

#define SLAVE_ADDRESS 0x60
byte x = 0x00;
void setup()
{
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
  Serial.begin(9600);
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Serial.print("Request from Master. Sending: ");
  Serial.print(x, HEX);
  Serial.print("\n");

  Wire.write(x);
}

void receiveEvent(int bytes)
{
  if(Wire.available() != 0)
  {
    for(int i = 0; i< bytes; i++)
    {
      x = Wire.read();
      Serial.print("Received: ");
      Serial.print(x, HEX);
      Serial.print("\n");
    }
  }
}

```
> 6 votes

# Answer
I went through this problem recently. Your slave needs two functions: one for sending and the other for receiving data.

```
// function: what to do when asked for data
void requestEvent() {
Wire.write(t);
}

// what to do when receiving data from master
void receiveEvent(int howMany)
{Val = Wire.read();}

```

Here is a code that works both ways of i2c communication in a single code

Sending and receiving different types of data via I2C in Arduino
> 2 votes

# Answer
> You had:
>
> ```
>  void receiveEvent(int howMany)
>  {
>    {
>          if(Wire.available()){
>            char c = Wire.read();
>            Serial.print(c);
>            if(c == 's'){
>              int x = Wire.read();
>              Serial.println(x);
>
>              //transmit to master
>              Wire.beginTransmission(3);
>              Wire.write(1);
>              Wire.endTransmission();
>
>            }else{
>              Wire.read();
>            }
>          }
>
>        }
>
> ```

There are a number of problems with your slave code.

1. Don't do Serial prints in an ISR (interrupt service routine)
2. Don't do beginTransmission / endTransmission in a receive event.
3. Don't do any writes
4. To send data back use a requestEvent not a receiveEvent.

Better would be:

```
// add in setup()
Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

...

volatile byte what;

void receiveEvent(int howMany)
{
  if (howMany < 2)
    return;

  char c = Wire.read ();
  if (c != 's')
    return;

  what = Wire.read ();  // remember what we got
}  // end of receiveEvent

void requestEvent()
{
  Wire.write (1);  // return a response
}  // end of requestEvent

```

---

> the Wire.requestFrom has only one Wire.write. I need multiple Wire.write which is not supported so are there any workarounds?

Batch up the response and do one write:

```
void requestEvent ()
  {
  byte buf [4] = { 1, 2, 3, 4 };
  Wire.write (buf, sizeof buf);   // send response
  }  // end of requestEvent

```

---

### Reference

There are a lot of examples at I2C - Two-Wire Peripheral Interface - for Arduino
> 0 votes

---
Tags: arduino-uno, arduino-mega, i2c, avr
---


# Question
Title: Power small hobby motor using Vin pin on Arduino and 9V battery, safe?
I want to power a small motor with a 9V battery and control it with PWM using an Arduino Leonardo. I know I can power the motor separately, but this introduces the problem of needing a battery to power the motor (9V battery) and another power source to power the Arduino (another 9V battery?)

**Would it be safe** to simply power the Arduino with a 9V battery and use the Vin pin on the board (which is unregulated and outputs directly the power source powering the Arduino) to drive the motor? That way, I power everything from the 9V battery, and use a transistor to drive the motor.

Thanks a lot!

Steve.

# Answer
> 1 votes
If you use a transistor circuit as shown below, back EMF would not cause any trouble.

# Answer
> 0 votes
Yes it is OK to do that. But the thing you should consider in mind is "What is the current requirement of the motor?"

You say

> I want to motor a small motor with a 9V battery and control it with PWM

This means you have a servo motor, which might require a lot of current depending on the torque. So if you have a battery with low 'mAh', your battery will dry out very quickly. This might or might not be a problem for you depending on your requirements.

# Answer
> 0 votes
The arduino has its on voltage regulator, so feeing 9v to the arduino is not a problem. But the arduino will not drive the motor directly. You need to use a transistor big enough to hundle the amperage of your motor (e.g.tip120). The diagram above is a good indication of how to connect it. Yet the diagram is missing a diode (1n4001 or 1n4004) from the GnD to Vcc, as to avoid back voltage from the motor, which may damage your arduino.

---
Tags: motor, arduino-leonardo
---


title: Arduino "piston" device

text:
# Question
Title: Arduino "piston" device
Is there any compact piston-like devices on the market that can apply pressure safely various parts of the head? I can further expound if needed.

The ideal size would be something within the 1-2 inch length range

# Answer
It sounds like this is nothing to do with an Arduino, just a general Electrical/Mechanical engineering question that you want to control from and Arduino. I think you wan a device that when signalled by your Arduino can extend itself by up to 2 inches.

If that is right then I think what you are looking for is a Linear Actuator. There are plenty out there and some do handle the small stroke you want, but most of them appear to be 9 to 12V. This means you would require a Darlington transistor or relay to control them from an Arduino.

If you require an extremely precise stoke length then I would recommend a stepper motor with a screw axel. This would allow you much finer control over how far you pushed, but it would impose limits on what you could do and how it could be mounted.

* Can you provide more details on what you want to move?
* List item
* Is it heavy? Do you need lots of Torque?
* Are you pushing straight or do you need to push in an arc (i.e. a door)?
* What voltage supplies do you have available?
* How fast do you want it to move?
* Do you want it to move exactly the same distance every time?

The more info you can provide the better, but in answer to your original question Yes, it sounds like there might be so you plan is still on the rails.
> 1 votes

---
Tags: project
---


title: Arduino Controlling through C#

text:
# Question
Title: Arduino Controlling through C#
i would like to measure some signals from arduino and send it to a pc using USART and display the results in a c# winform application. Does anyone have such a project example ? Besides, i want to send the data in live time mode, each values should be directly transmitted and then the second measurement ( sample rate 100 kHz ) Thanks a lot

# Answer
Am I missing the point here or wouldn't the C# just have to open a Serial connection to the board and read and write to that to control the program running on the Arduino? Yes the board is connected by USB, but that's only so it can open a serial connection. To be honest I don't think you will be able to sample at that speed, you might be better looking at ICs that directly interface with GPIO and RS232/USB.
> 2 votes

---
Tags: arduino-uno, arduino-leonardo
---


title: actual use of noTone() in arduino

text:
# Question
Title: actual use of noTone() in arduino
What is the use of noTone() function as the duration for which the note must be played can be specified using the third argument of note() function.

# Answer
So that you can terminate the output prematurely, e.g. during an interrupt.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: When the Arduino is in reset mode are the digital pins high impedance?
I have an Arduino (Arduino A) hooked up to an external FRAM chip and I want to be able to pull the Arduino A's reset pin to ground to keep it in a constant reset state. Then I want to hook up another Arduino (Arduino B) up to the same lines going from Arduino A to the external FRAM chip and pull data off of the FRAM chip.

I am worried that when I hook Arduino B to the lines running between the FRAM and Arduino A that it will damage Arduino A. If the digital pins are in a high impedance state while I do this though, then it should be fine. I can't find the necessary documentation to figure this out though.

All Arduinos involved are Uno Rev 3s.

Any help would be appreciated, thanks!

# Answer
> 1 votes
From the ATMEGAxx8 datasheet...

> 11.1 Resetting the AVR
>
> ... The I/O ports of the AVR are **immediately** reset to their initial state when a reset source goes active. This does not require any clock source to be running.

(bold added)

Looking over the register descriptions for the Data Direction Registers, all bits have an initial value of `0`, corresponding to high impedance input.

...so it is safe to assume that all IO pins will be in a high impedance state a very short time after the `RESET` pin goes low.

Caveats:

1. The clamping diodes are in-circuit even when pins are in high impedance state, so current will flow if the voltage on the pin is higher than Vcc or lower than Ground (at least until the diode blows up!).
2. Some Arduino pins are connected to other things besides just the pin on the MPU. For example, digital pin 13 is connected to ground though a resistor and diode, so current will flow into it if you connect a voltage higher than the threshold for the diode. On the Uno there are also resistors on the RX and TX pins connected to the serial communications link, so current can flow there too.
3. The MISO pin can inadvertently become an output while `RESET` is held low if the Programming Enable command ($AC $53 xx yy) is transmitted over the MOSI & SCK lines. This process is described in App Note AVR910.

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


# Question
Title: Deviation of power consumption between datasheet and real world?
According to the Atmega328P-PU Datasheet (side: 589) the current consumption of the microcontroller should be around 9.5mA (at 16MHz and 5V).
But I measured 15mA. (Nick Gammon who did some pretty good power saving research(gammon.com.au/power) got the same)
There is nothing connected to the outputs. The code I ran was this:

> void setup () {}
> void loop () {}

Now I'm wondering if this is just a normal deviation (datasheet to real world) or if Atmel measured their current consumption in a state that is different from mine?

**EDIT:**

I forgot to mention.. I didn't use it with the Arduino Uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.

Now that I think about it.. Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source."

Is it possible that the oscillator needs that extra 5mA?

**EDIT2:**

Here is a screenshot of my schematic:

And a screenshot of the ATmega328P-PU Datasheet:

# Answer
> 1 votes
According to the datasheet:

> All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled.

---

That was the critical point. Trying this sketch:

```
int main ()
  {
  for (int i = 0; i < 20; i++)
    pinMode (i, INPUT_PULLUP);
  }  // end of setup

```

Note that timers are not running (your sketch would have timer 0 running):

With that sketch, even using the crystal and capacitors (I actually had a resonator) the consumption at 5 V at around 20 °C was 9.2 mA which is within spec.

Fuses:

```
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDF
EFuse = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96

```

---

If we turn pull-ups off:

```
int main ()
  {
  }  // end of setup

```

Now it consumes 14.4 mA, closer to what you measured.

---

And with your actual test sketch:

```
void setup () {}
void loop () {}

```

It consumes 15.5 mA, which is more, because Timer 0 is running (started in the `init` function). It is also close to what I had on my page about power \- 15.15 mA.

---

So, working as expected. Those pull-ups are important, to stop the input drivers consuming current.

I did mention further down in my page the importance of configuring the pins:

> Testing in SLEEP\_MODE\_PWR\_DOWN:
>
> * **All pins as outputs**, and LOW: 0.35 µA (same as before).
> * **All pins as outputs**, and HIGH: 1.86 µA.
> * **All pins as inputs, and LOW** (in other words, internal pull-ups disabled): 0.35 µA (same as before).
> * **All pins as inputs, and HIGH** (in other words, internal pull-ups enabled): 1.25 µA.

Notice the difference there of 0.9 µA when asleep. It would appear that there is an ever greater difference if the processor is awake.

# Answer
> 0 votes
Probably Atmel measured the chip consumption without any code. An empty sketch has some code in it (believe it or not). Another possibility is the remaining components like voltage regulator, usb chip are also consuming some current. Try to test in a bare minimum configuration.

---
Tags: power, current
---


title: Split RGBW hex String into integers

text:
# Question
Title: Split RGBW hex String into integers
I have a program where the Arduino receives hex Strings that represent a RGBW color (similar to css for example). My goal is to create that color by using pwm, so I need to convert that one hex string into four integer values between 0..255 to use for the pwm. Whats the best/easiest way to do this?

Example:

```
void incomingMessage(const MyMessage &message) {

    // h = hex value
    // message = e.g. (h) #112233AB
    redval = ?; // h11 => 17
    greenval = ?; // h22 => 34
    blueval = ?; // h33 = 51
    whiteval = ?; //AB = 171

    analogWrite(RED_PIN, redval);
    analogWrite(GREEN_PIN, greenval);
    analogWrite(BLUE_PIN, blueval);
    analogWrite(WHITE_PIN, whiteval);

}

```

# Answer
I don't like using the String class because it can cause memory fragmentation. This would do it by just using C-style strings:

```
byte fromhex (const char * str)
  {
  char c = str [0] - '0';
  if (c > 9)
    c -= 7;
  int result = c;
  c = str [1] - '0';
  if (c > 9)
    c -= 7;
  return (result << 4) | c;
  }

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

  const char * test = "#112233AB";

  byte redval   = fromhex (& test [1]);
  byte greenval = fromhex (& test [3]);
  byte blueval  = fromhex (& test [5]);
  byte whiteval = fromhex (& test [7]);

  Serial.println ((int) redval);
  Serial.println ((int) greenval);
  Serial.println ((int) blueval);
  Serial.println ((int) whiteval);

  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

```

Output:

```
17
34
51
171

```

That does not do any validation (that the string is indeed 9 characters long, and contain hex characters) but I'll leave that for you to do. :)
> 1 votes

# Answer
So you basically want to convert a pair of hexadecimal digits into a numeric value. You also want to extract those values from a string.

The latter can be done using the String.charAt() method. That allows you to extract individual characters from your string.

Then you need to convert those into a number. There's a number of ways that could be done.

# strtol()

The strtol() function takes three parameters - the first is a C string (NULL-terminated char array) which contains the number you want to convert, the second you can ignore, and the third is the *base* to convert from. So you could use something like:

```
char temp[3] = { char1, char2, NULL };
int val = strtol(temp, NULL, 16);

```

# Discrete functions

It's simple enough to write a function that converts a single hex digit into a value 0-15:

```
unsigned char h2d(unsigned char hex)
{
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

```

It's then simple enough to use that to make a function that takes two hex digits and converts them into a number:

```
unsigned char h2d2(unsigned char h1, unsigned char h2)
{
    return (h2d(h1)<<4) | h2d(h2);
}

```

There's as many ways of doing it as there are of skinning a cat (as the saying goes). Every way has benefits and drawbacks though. Of the two I have shown, to compare them:

* The first is "safer" as it has more error checking and can cope with other things besides hex values
* The second results in much smaller code but results with values other than hex digits are undefined.
> 0 votes

---
Tags: c++, string
---


# Question
Title: Are there any ePaper modules that are bigger than 2.7 inches for arduino
I am looking for a large ePaper Display for the Arduino. The issue is is that I cannot seem to find one any larger than 4.5 inches in size. That will be compatible with arduino. Even with a controller board.

Are there any companies that sell controller boards for these displays? Is there anyone who can manufacture these epd displays upon request?

I am looking to take this project to a pcb board after I prototype it so do I need to build my own controller? If what parts would you need? Is it easy for a designer with intermediate capability?

I can find all kinds of display like at pervasivedisplays.com and Mouser.com

The end goal is to create a Arduino based project that I can score skeet with to keep track of my average score.

# Answer
> 1 votes
I would suggest you to start the other way: find a sw stack that is known to work and check if any of the controllers/displays it already supports fits your needs. This is how I would do it.

Here is a starting point.

---
Tags: arduino-mega, display, components
---


# Question
Title: Powering arduino and 12V Fan from same supply
I have found a relatively small 12V switching power supply that I want to build into my device, using it to power both the Arduino Pro Mini and a couple of 12V cpu fans.

Am I correct in assuming that I can have the Arduino RAW pin and Fan+ on the same power supply lead? Or do I need to protect the Raw pin in any way? Also, I need to power 2x cpu fans, can this be done with one transistor or do I need one for each fan?

If I stay within the Current specs of my supply (6A) could I keep adding other 12V components on the same +lead as in the diagram below?

# Answer
Sounds fine.

You can connect the two fans in **parallel**, as long as they don't use more than 5A combined, as that is the maximum of the TIP120. Though you definitely need to attach a heatsink to the TIP120, if you are using a largish amount of current. Though in that case, I'd suggest using a MOSFET instead of a Darlington Transistor (TIP120), as MOSFETs don't heat up that much.

The diode is not needed if you use the TIP120, as there is already a diode inside the package.

Since you are using 12V as a power supply, the voltage regulator has to convert 7v into heat. Depending on the amount of current you use, this could result in the voltage regulator getting very hot. If you are only powering the ATMega328 and maybe some LEDs from the 5v line, you'll be fine. Just don't connect something like a 5v fan.
> 1 votes

# Answer
The board will take 12V, but the regulator will have to dissipate (as in heat) the excess power.

However, how much do you trust your power supply to not exceed the 12V?

The same applies to the other loads.

About max current, you should do the math for both typical case and peak case. Ex: the fan will draw much more current if for any reason it is stopped.

If you use only 1 transistor, you will get both fans to behave in the same way, because you will be using only 1 control line. Is this what you want?
> 1 votes

---
Tags: power, hardware, arduino-pro-mini, system-design, electricity
---


title: Outlet switcher using servo motor

text:
# Question
Title: Outlet switcher using servo motor
I am building a small-scale watering system to water my plants, controlled by Arduino. I have designed most of the project except for how to switch water between multiple pipes.

A little more background:

I want to be able to use a servo motor to control the amount of water that is sent to each plant (based on pot size and plant type). The motor needs to be able to switch input (a 1/2 inch pipe carrying water) to a set of outputs (similarly sized pipes all going to different plants). I am not able to find something off the shelf that does this. So, I am about to 3D print something. Is there something available that I can use instead?

# Answer
> 0 votes
As JRobert mentioned in a comment, you could use a solenoid valve, some of which you can get for about $5.

If you want to water one line at a time, get Normally Closed, one per line. Naturally, since most of them are 12v DC, you can't directly power them from your Arduino. You'll need some power transistors or some relays, and a 12v supply capable of steadily powering the solenoid.

# Answer
> 0 votes
To me it would seem simpler to use a faucet for each line, each faucet controlled by a motor. Then you can even water the plants in parallel.

Even better, why not using submersion pumps, like those used in water tanks? Here too, you can control them in parallel. The amount of time you keep a motor running is proportional tothe amount of water delivered.

---
Tags: servo
---


title: Help with Flappy Bird Sketch

text:
# Question
Title: Help with Flappy Bird Sketch
I am compiling the sketch found here. I just downloaded the .ino and .h files and opened them, so I have not modded the code at all. I keep getting the following error.

```
In file included from flappyDuino.ino:7:0:
Sprite.h:3: error: variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_1[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x78, 0x8A, 0x84, 0x8A, 0x82, 0x42, 0x82, 0x3E, 0x44, 0x41,0x38, 0xBE, 0x20, 0x41, 0x18, 0x3E, 0x07, 0xC0 };

                                                 ^
In file included from flappyDuino.ino:7:0:
Sprite.h:4: error: variable 'flappybird_frame_2' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_2[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x20, 0x8A, 0x40, 0x8A, 0x40, 0x42, 0x7C, 0x3E, 0x82, 0x41, 0x84, 0xBE, 0x88, 0x41, 0x78, 0x3E, 0x07, 0xC0 };

                                                 ^
Sprite.h:5: error: variable 'bar_bottom' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_bottom[] = { 0xFF, 0xFF, 0xFF, 0x42, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E };

                                         ^
Sprite.h:6: error: variable 'bar_top' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_top[] = { 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x42, 0xFF, 0xFF, 0xFF };

                                      ^
variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

```

I'd appreciate any help.

# Answer
The arrays need to be tagged with the keyword `const`. It is possible that the original sketch was written using an earlier version of the IDE that you are using (or a later version?) and your version requires the `const` keyword whereas the author's doesn't.

Basically any arrays that are `PROGMEM` need the word `const` adding to them. For instance, lines that start:

```
static unsigned char PROGMEM ...

```

need changing to:

```
static const unsigned char PROGMEM ...

```
> 1 votes

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


# Question
Title: Operating HB100 backpack with Arduino Due
I need to connect a speed sensor module with an Arduino Due and calculate the speed of an approaching object.

the sensor is: http://www.limpkin.fr/index.php?post/2013/08/09/Making-the-electronics-for-a-%247-USD-doppler-motion-sensor

The sensor already output a signal that its' frequency represents the speed of the object.

I would really appreciate any help understating how can it be connected and operated by the Arduino without burning it, and how can I sample its output?

If more details are needed I'll be happy to supply.

Thanks.

# Answer
> 1 votes
The articles and tutorials I've read on the subject say that the HB100 module produces a very weak signal which needs to be amplified before your Arduino can read it. They recommend building an op amp. This post on the Arduino forums, for example: http://forum.arduino.cc/index.php?topic=61989.0

BUT looking at your picture and linked article, I find that your device already includes the signal amplification and filtering you need in the backpack board. I found the store page for this module, which has a more noob-friendly explanation. From what I gather:

* VCC: provide the module with a 5v supply.
* VOUT: analog reading of the *amount* of return signal being received. My guess is you could use this with `analogRead()` to get a rough estimate of the size or distance of the object being read. If you want only the speed reading, you don't need this pin.
* FOUT: digital output of the speed that the sensor is reading. Thanks to @sachleen's link, you can use either `pulseIn()` or FreqCounter library to measure the frequency and then convert it to a MPH or KPH speed.
* GND - ground, aka common, aka `-`.

So connect VCC to 5v, GND to ground, and FOUT to an input pin on your Arduino. If you use `pulseIn()`, frequency **f** = 1 / **t**, t being the return value from `pulseIn()`. If you use the FreqCounter library, it no doubt has documentation on its usage.

---
Tags: sensors, arduino-due
---


# Question
Title: Mega pin stuck high after driving optocoupler
I have an Arduino Mega which is driving a board. On the board is a quad optocoupler (K847PH). Pins 42 - 45 of the Arduino are each attached to the Anode of a opto. The cathode goes to ground through a 50ohm resistor. I've used multiple boards and have had no issues with this part of the circuitry so far. I recently attached a new board (same circuit) and began testing. I noticed I had ~1.1V on pin 1 of the opto (Anode). After some debugging I checked the voltage coming out of the Arduino to that pin (42 on the Mega) and noticed it was 5V. I ran a new sketch to drive and hold the voltage low but the voltage remains at 5V.

```
void setup() {
  pinMode(42, OUTPUT);
  digitalWrite(42, LOW);
}

void loop() {
  digitalWrite(42, LOW);
}

```

Looking at the schematic of the Mega it appears pin 42 is directly connected to the ATMEGA1280-16AU. Is there anything I can do to fix the Mega? Should I just replace the ATMEGA1280-16AU? Is there something I can probe to check? It does appear there is \> 1Mohm of isolation between pin 42 and the 5V rail.

# Answer
> 1 votes
Re “Is there anything I can do to fix the Mega?”, if the condition persists when trying it after removing power from the Mega and discharging it, probably not. (Aside from not using that pin.)

Note, the IR LEDs in the K847PH are rated at 60 mA max each, and typically drop 1.25 volts at 50 mA current. If you drive them with 5 V through a 50Ω resistor, typical current will be 3.75/50 = 75 mA, which exceeds K847PH ratings and Mega2560 ratings (typically 40 mA max, 20 mA working). Consider using a 125Ω or more resistor, to stress the Mega pins at 30 mA or less.

(From Fig. 8 - Collector Current vs. Forward Current, in the K847PH data sheet, you might be ok with 10 to 20 mA current through the IR LEDs.)

---
Tags: arduino-mega, power, pins, hardware, debugging
---


title: 1x4 Button membrane help

text:
# Question
Title: 1x4 Button membrane help
Im trying out this membrane from Adafruit that i bought last week but i have a little issue. ITS SO SENSITIVE! i as so just touch it with my finger and it transmits!. Anyone that has worked with this membrane have the same issue? is there some sort of "fix"?

**UPDATE**

Its really simple. But one weird thing, not sure if its supposed to be like that, but by default, the buttons are on `HIGH`. i used `Serial.println(digitalRead(one));` to verify that and the output was 1.

```
int two =  8;
int one = 9;
int four = 10;
int three = 11;

void setup() {
  pinMode(one, INPUT);
  pinMode(two, INPUT);
  pinMode(three, INPUT);
  pinMode(four, INPUT);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(one) == LOW){
    Serial.println("One");
  }else if(digitalRead(two) == LOW){
    Serial.println("Two");
  }else if(digitalRead(three) == LOW){
    Serial.println("Three");
  }else if(digitalRead(four) == LOW){
    Serial.println("Four");
  }
}

```

# Answer
> 4 votes
> ```
> pinMode(one, INPUT);
>
> ```

You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You *must* enable the pullup on the pins (and connect the common to ground) if you want correct operation.

```
 pinMode(one, INPUT_PULLUP);

```

---
Tags: button
---


title: Move robot through the waypoints

text:
# Question
Title: Move robot through the waypoints
My arduino robot has two dc motors as two wheels and have mounted an IR led on it. I get current position of the robot as (x,y) coordinates in the arena using camera which is mounted at the top of the arena..

My robot communicates with PC through bluetooth. I can read current position of robot on pc with the help of camera. Robot uses arduino motor shield to drive DC motors.

Which is the best method to move robot through the waypoints for a robot with DC motors without encoders?

# Answer
> 2 votes
With the arrangement you have described I would say it's very very hard to do what you want.

* You know where the robot is
* You know where the robot has to get to
* You can easily calculate the direction the robot has to go in (simple trigonometry from school)

**But:**

You don't know what direction the robot is facing, so you don't know how to turn the robot to get it to drive in the direction you need.

So either you need some kind of *calibration* procedure whereby the computer moves the robot in different directions and watches what the IR LED does to determine what direction the robot is facing so it can move it to face the right way (tricky to do, and rather messy), or some way for the computer to visually calculate the direction of the robot.

The latter is probably the easiest. Instead of just one IR LED on the top of the robot you would need an array of IR LEDs on top of the robot forming a shape. What that shape is can be up to you, but there is one big constraint: *It must have a clear direction to it* (i.e., it must have *no rotational symmetry*. Triangles are good since they only need 3 LEDs. An equilateral triangle though wouldn't work since in three different rotations it would look the same. However, a single LED at the front of the robot, with two LEDs at the back of the robot, with the two back LEDs closer together than the distance from the front to the back, would not have any rotational symmetry.

You could then, (theoretically, assuming you have control over the camera software), get the three points from the play area and calculate the direction the robot is facing (tangent from mid-way between the two close points passing through the distant point) so you can then calculate the angle the robot would need to turn through so it is facing the direction you need it to.

Remember in math class, doing trigonometry (sin, cos, tan, pythagoras, etc) thinking "Why the hell do we need to know this stuff?!", well, now you know.

# Answer
> 0 votes
This depends if you want the hypothetical best solution, or if good enough is good enough.

If good enough is good enough, I'd take the following approach:

Work out the distance from your robot to the first waypoint; move forward. Work out how fast you're moving towards (away from) the goal. Turn left a bit, go forwards again; did things improve (less away from/more towards)? If not, turn slightly right. Keep turning this way (left or right), and going forward a bit; whenever your speed towards to the goal gets worse, change your turning direction.

This should get you to where you are going.

Then, start making improvements.

If you are moving away from the goal (distance is increasing), your rotates can be quite sharp; as your approach speed to the goal increases, make the rotates smaller.

You could also try rotating while driving - if you are driving forward, and want to turn slightly left, run your left wheel at 90% of the speed of the right.

With a bit of trial and error, you should be able to end up with a table - work out your approach speed, look up in a table (or formula) how fast your slower wheel should go - from 0% (or even 100% reverse!) if moving away from your goal, to 100% if you are going at your driving speed towards your goal. Remember that if you are turning, you will approach it more slowly than if you are going straight. And if you start to turn and things get worse, then you are turning the wrong way.

---
Tags: arduino-mega, arduino-motor-shield
---


title: Servos don't move

text:
# Question
Title: Servos don't move
I made simple code for a robotic arm, but the servos don't seem to be reacting at all. I made debug code before all the if statements, and those aren't working. I made sure my wiring was good and it is.

```
#include <Servo.h>

Servo release1;
Servo release2;
Servo updown;

int pos = 64;    // variable to store the servo position
int pos2 = 85;
int val = 0;
int val2 = 0;
int val3 = 0;

void setup()
{
    release1.attach(8);
    release2.attach(9);  // attaches the servo on pin 9 to the servo object
    updown.attach(10);
    release1.write(pos2);
    release2.write(pos2);
    updown.write(pos);
}

void loop()
{
    val = digitalRead(4);
    val2 = digitalRead(5);
    val3 = digitalRead(6);
    pos++;
    pos2++;
    if(val = LOW){
        pos = pos + 15;
    }
    if(val2 = LOW)
    {
        pos = pos - 15;
    }
    if(val3 = LOW)
    {
        pos2 = 180;
    }
    if(val3 = HIGH){
        pos2 = 0;
    }
    release1.write(pos2);
    release2.write(pos2);
    updown.write(pos);
}

```

I'm using this code and it still wont work.

```
/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=0; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

# Answer
> 1 votes
I made debug code before all the if statements, and those aren't working.

```
if(val2 = LOW)
{
  pos = pos - 15;
}
if(val3 = LOW)
{
  pos2 = 180;
}
if(val3 = HIGH){
  pos2 = 0;
}

```

That's because they are coded wrongly. Doing `val2 = LOW` **assigns** LOW to val2 and then tests it (which means it will fail the test). They should read:

```
if(val2 == LOW)
{
  pos = pos - 15;
}
if(val3 == LOW)
{
  pos2 = 180;
}
if(val3 == HIGH){
  pos2 = 0;
}

```

# Answer
> 0 votes
I tried uploading on a computer with windows 8 freshed installed and it still wont work, i tried serval differn't servo motors, looks like the arduino it self is broken.

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


# Question
Title: Arduino: how can I stop while() when bluetooth send a data?
I have learned Arduino for a month, and I want to bulid a car with 2 modes, Remote and Auto. Auto mode needs to have while() loop, so it can receive data from sensors. When I choose Auto mode via bluetooth, it keeps looping and it won't stop when I choose the Remote mode. Here's the part code:

```
char mode;

void loop()
{
    while(serial1.available())
    {
        char control = serial.read();
        if(control == 'r') mode = 'r';     // r stand for Remote Mode
        if(control == 'a') mode = 'a';     // a stand for Auto Mode

        if(mode == 'r') remoteMode(control);

        while(mode = 'a')
        {
            int IR = analogRead(A10);
            float U1cmMsec,U2cmMsec;
            long U1microsec = u1.timing();
            long U2microsec = u2.timing();
            U1cmMsec = u1.convert(U1microsec, Ultrasonic::CM);
            U2cmMsec = u2.convert(U2microsec, Ultrasonic::CM);

            robot(U1cmMsec, U2cmMsec,IR);

            /*
            Here is the code to stop while() that I don't know how
            to program.
            I have tried:

            if(serial1.read() != 'a') break;

            But it will stop while(), because it will waits for
            bluetooth send data to arduino board.
            And if I take this line off, it will keeps while() and
            nothing can stop it.
            So, what am I supposed to do?
            */
        }
    }
}

```

# Answer
> 1 votes
Your problem is with this line:

```
while(mode = 'a') {

```

What you are saying there is not what you think you are saying. You are confusing `=` (assignment) with `==` (comparison).

You are basically saying "While I assign 'a' to the variable 'mode' and 'a' is not 0 ...", which of course will always be true.

Instead you want:

```
while (mode == 'a') {

```

or, "While the variable 'mode' contains the letter 'a' ..."

Now you just need to program in some way of changing the value of `mode` within your while loop.

You can read more on while loops here:

# Answer
> 0 votes
The `while(serial1.available())` can be turned into an `if`: the loop function is already executed in a loop, as the name hints :-)

And unnest the inner `while`.

here it is at high level, which is probably easier to understand:

`void loop() {
 static char mode; /*notice the "static"*/
 if (character_available())
 update_mode();
 if (mode == 'r')
 do_one_iteration_in_remote_mode();
 else if (mode == 'a')
 do_one_iteration_in_auto_mode();
}`

Just make sure that you do not loop inside neither `do_one_iteration_in_remote_mode()` nor `do_one_iteration_in_auto_mode()`.

# Answer
> 0 votes
I have replaced both 'mode' and 'control' (they were identical) with a single variable, `btChar`. At the end of `setup()`, wait for a transmission to be received before entering the main loop.

Once the main loop begins, a while loop executes until the serial receives a new transmission. Once it is received it is read, btChar is updated and the main loop starts again.

```
char btChar;

void setup()
{
/* AT THE END OF SETUP() */

// Wait in setup for first BT transmission

    while (!serial1.available())
    { /* do nothing */ }
    btChar = serial1.read();
}

void loop()
{
    while(!serial1.available())
    {
    // Program will stay in this 'while' loop until
    //    a new BT character is recv'd

        switch(btChar)
        {
            case('a'):
            {
            // do the 'auto' stuff
                break;
            }
            case('r'):
            {
            // do the 'remote' stuff
                break;
            }
            default: // this 'block' is not essential
            {
            // you end up here if neither 'a' nor 'r' was received
            }
        }
    }
    btChar = serial1.read();
}

```

You can adapt the setup while-loop further to make sure that the main loop doesn't begin until the a correct character is received - change the line to:

```
while ((!serial1.available())&&(btChar != 'a')&&(btChar != 'r'))

```

Using a `switch-case` statement within the main while-loop is not essential, and I included it out of interest more than necessity. You can use `if` statements instead, with one for 'a' and one for 'r'. However, in the event that you have a third or fourth (or more-th) mode then a switch-case statement, in my view, looks easier to read.

---
Tags: c++, code-optimization
---


title: Arduino wire can't send char

text:
# Question
Title: Arduino wire can't send char
Hi I have problem with school project. I have 3 Arduino - 1 Transmiter with NRF; 2,3 - NRF receiver and wire slave receiver. I can't send data via "Wire" library (in code char "datar") to receiver arduino. I won't get anything, but when I want to send like `Wire.write("blablabla");` it pass. But when in char is NRF data code crashing when go to "Wire.write".

```
/*
*/
#include <Wire.h>
#include <SPI.h>
#include "RF24.h"

char datar = '';

//Konfiguracja
const uint64_t pipes[2] = {0xF1F2F3F0F7/*odbieranie*/, 0xF1F2F3F0F8/*wysylanie*/};
RF24 radio(9, 10); //Piny nrf (SPI) 9 i 10
//-- Konfiguracja

void setup() {
  Serial.begin(9600);
  Serial.println("LOL");
  Wire.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(1, pipes[0]);
  radio.openWritingPipe(pipes[1]);
  radio.setChannel(78);
  radio.setAutoAck(true);
  radio.startListening();
}

void loop() {

  int len;
  if(radio.available())
  {
  len = radio.getDynamicPayloadSize();
  radio.read(&datar, len);
  delay(5);
  Serial.println(datar);
  Wire.beginTransmission(7);
  Wire.write(&datar);
  Wire.endTran345smission();
  radio.printDetails();
  }
  delay(5);

}

```

# Answer
> 2 votes
Your problem is here:

```
char datar = '';

...

 len = radio.getDynamicPayloadSize();
 radio.read(&datar, len);

```

The variable "datar" is one byte long. You then find the payload size (presumably greater than one byte) and read into `datar` more than one byte. This overwrites other parts of memory and the program crashes. You need to make `datar` larger, eg.

```
char datar [50];

```

The exact size would depend on your maximum payload size.

# Answer
> 1 votes
The code crash because you pass an memory address to the write function if you look to the arduino doc you pass a variable to the function therefore just writing datar as argument will end your problem

# Answer
> 1 votes
I think the answer is a combination of Nick and Mathieu's answers.

Like Nick said you haven't assigned any memory to datar, so this is probably causing a crash because of buffer overrun.

Now to the call to read. Mathieu said you are passing a pointer into the function when you probably didn't mean to. But if you put Nicks change in then you **do** need to pass in a pointer to the character array. You can do this by `radio.read(datar, len);` because the character array is a character pointer.
You **do not** want to pass a pointer to a character pointer `&datar` because that would mean the function was able to move the memory that you have allocated.

Also, you need to prevent buffer overflows in the "new improved" code by checking that the value of `len` is less than or equal to the value you allocated when you declared the data buffer (i.e. 50). Because you are using a number in two places you should declare it as a constant at the top of the file.

```
const int MaxBufferSize = 50;
char datar[MaxBufferSize];
...
len = radio.getDynamicPayloadSize();
if (len > MaxBufferSize)
  len = MaxBufferSize;
radio.read(datar, len);

```

Hope that helps.

---
Tags: c++, i2c, nrf24l01+
---


title: 2.8" tft screen arduino all pins used

text:
# Question
Title: 2.8" tft screen arduino all pins used
I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: 2.8" TFT Touchscreen Prohibits Access to Unused Pins)

However, they recommend a proto screw shield (show here: http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg%3D%3D&gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&kpid=1480459155)

However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?

Thanks!

# Answer
> 1 votes
You're confusing the idea of *using* all the pins to that of *plugging into* all the pins.

Yes, your shield may well have all the pins on it which then fill all the available holes. Only some of them will actually be connected to anything on the circuit board though.

The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.

You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.

---
Tags: arduino-uno, shields
---


# Question
Title: Running Arduino code for Bluefruit LE on bare ATMega328
I need to hook up Bluefruit LE Breakout (nRF8001-based) to ATMega328 chip (to use it as wireless UART), and it seems like the library provided is for Arduino.

What I have is just bare ATMega328 (note the lack of "p"), which I am going to program (using avrispmkii directly). As I already have the MCU assembled, I do not want to change to, say, Arduino Uno to be able to use the library. Most likely, I will "play" with the Bluefruit on Arduino first to get the feel of it, but the code needs to be run on the "bare" ATMega328. The other part of the program (which prepare data to be sent from atmega) is trivial, so I will have no problem to rewrite it from C to Arduino. Porting Adafruit library from C++ to C is probably much more difficult.

Thus, one of the possible approaches is to compile the my code + Bluefruit LE code for Arduino, but upload to the ATMega328.

And this is where I need help:

How to make Arduino (command line tool is ok) to compile to the MCU I have? I guess, the result should be some kind of hex-file for flash (and eeprom?).

And, may be useful, which flags to use with avrdude, if there is anything specific for the Arduino-generated code. (I do not need any bootloaders on the chip, just the program, and I do not have UART-USB connected to atmega).

Of course, please, mention if there are better ways I overlooked, like some Arduino-compatible gcc toolchain to compile C++/C mix into avr code (avr-g++?). Or maybe there is some C-library for the component atmega needs to talk to.

UPDATE: Similar question: http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal

# Answer
> 1 votes
The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.

You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.

You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of `Upload`, choose `Upload using Programmer` (in the `Sketch` menu).

---
Tags: atmega328, adafruit, avrdude, avr-gcc, gcc
---


# Question
Title: how to create a specific buffer when there is no buffer message in the data packet?
So I'm trying to understand a read method. In this method,

```
// Read data from buffer
int SoftwareSerial::read()
{
if (!isListening())
  return -1;

// Empty buffer?
if (_receive_buffer_head == _receive_buffer_tail)
  return -1;

// Read from "head"
uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
_receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
return d;
}

```

it looks it receives buffer head. But in the write only a 1 or 0 is being sent as the data packet's header. Nothing else. So how does the arduino know how big of an buffer to create? also, there is no stop bit being transmitted, so how does it look at a buffer tail? Or is this all created regardless of the transmitter? and then, all the values just get read into the buffer, and then read again from there? Also I don't see a delay in this read method. Wouldn't that cause errors in the data flow? How is that being handled?

# Answer
That read method just retrieves bytes that have already been received from an internal buffer.

The buffer is pre-allocated to a specific size (64 bytes) and that is how many bytes can be received before you start to lose data as it gets overwritten. You have to be sure to read your data from the buffer before it overflows.

The function that actually receives each UART bit from the IO port, builds them into bytes, and stores them in the internal buffer, is this one:

```
void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {
    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);

    // Read each of the 8 bits
    for (uint8_t i=0x1; i; i <<= 1)
    {
      tunedDelay(_rx_delay_intrabit);
      DebugPulse(_DEBUG_PIN2, 1);
      uint8_t noti = ~i;
      if (rx_pin_read())
        d |= i;
      else // else clause added to ensure function timing is ~balanced
        d &= noti;
    }

    // skip the stop bit
    tunedDelay(_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN2, 1);

    if (_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
    {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    }
    else
    {
#if _DEBUG // for scope: pulse pin as overflow indictator
      DebugPulse(_DEBUG_PIN1, 1);
#endif
      _buffer_overflow = true;
    }
  }

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
  asm volatile(
    "pop r27 \n\t"
    "pop r26 \n\t"
    "pop r23 \n\t"
    "pop r22 \n\t"
    "pop r21 \n\t"
    "pop r20 \n\t"
    "pop r19 \n\t"
    "pop r18 \n\t"
    ::);
#endif
}

```

To show you how the timing of the routine works, here is a little diagram:
> 1 votes

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


# Question
Title: How to find the deferenced value of a transmit Port Register?
So I am working with the SoftwareSerial library. I'm looking at the write function and I see a \*reg value being manipulate. I want to find the value of \*reg so I traced the value by stepping into each function call.so here we go.

```
*reg = _transmitPortRegister
_transmitPortRegister = portOutputRegister(port) //I'm working with pin 1 in register D

```

Continuing...

```
#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )

const uint16_t PROGMEM port_to_output_PGM[] = {
    NOT_A_PORT,
    NOT_A_PORT,
    (uint16_t) &PORTB,
    (uint16_t) &PORTC,
    (uint16_t) &PORTD,
};

```

My first question is what is the point of (uint16\_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

Continuing on,

```
#define PORTB _SFR_IO8(0x05)
#define PORTC _SFR_IO8(0x08)
#define PORTD _SFR_IO8(0x0B)

#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)
#define __SFR_OFFSET 0x20

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

```

Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

LASTLY, the write function takes in a parameter b, which is a byte. Now in the write function, this is the code to write.

```
// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

```

In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte" and inside the if-else blocks, they're just oring \*reg with reg\_mask. How does that translate to sending a one?

Sorry for any confusion, i am glad to clarify any confusing parts of this question. Please let me know.

# Answer
> 2 votes
> My first question is what is the point of (uint16\_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

No. You're mistaking the operator. In this context `&` means *the address of*, so it is getting the address of the variable called `PORTD` and casting it to an unsigned 16-bit integer, which it's then storing in the array.

> Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

Again, we're talking addresses. The port register number is (for port D) 0x0B. Add that to 0x20 and you get 0x2B which is the address of the register in memory. Then comes the tricky bit:

```
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

```

Expand that out with 0x2B and you get:

```
(*(volatile uint8_t *)(0x2B))

```

Now, working from the inside out we have:

```
(volatile uint8_t *)(0x2B)

```

That says *this is a pointer to address 0x2B*.

Then that is de-referenced to get the value from that pointer with a `*` operator:

```
*(volatile uint8_t *)(0x2B)

```

So you end up with "The value that is in the address 0x2B"

If we then feed that back into the first part of your question, so:

```
PORTD = (*(volatile uint8_t *)(0x2B))

```

then `&PORTD` would be:

```
&(*(volatile uint8_t *)(0x2B))

```

The initial & and * cancel each other out (you can think of them as opposites - one is get the address from a value, the other get a value from an address), so you effectively end up with:

```
(volatile uint8_t *)0x2B

```

# Answer
> 1 votes
```
// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

```

> In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte" and inside the if-else blocks,

The comment is: choose **bit**

First, variable `b` is the **byte** that is being set. Now, since async serial sends the least-significant bit first, at the start of the loop of 8 iterations, it takes the low-order bit to see if it is set or not:

```
  if (b & 1) // choose bit

```

If set, it sets the output port to HIGH (by ORing in the appropriate mask to the appropriate register), otherwise it sets the port to LOW (by ANDing in the appropriate inverted mask to the appropriate register). The inverted mask would be set to every bit **but** one.

Now look at this:

```
  b >>= 1;

```

That shifts the bits right one, throwing away the low-order bit. Now what was previously the second lowest-order bit is now the low-order bit. Then the loop repeats. Now the next bit is sent. And so on for 8 bits.

Imagine we were sending 0x39 (0b00111001). For the 8 iterations of the loop we would see:

```
00111001  --> 1 sent, then "b" shifted right one
00011100  --> 0 sent, then "b" shifted right one
00001110  --> 0 sent, then "b" shifted right one
00000111  --> 1 sent, then "b" shifted right one
00000011  --> 1 sent, then "b" shifted right one
00000001  --> 1 sent, then "b" shifted right one
00000000  --> 0 sent, then "b" shifted right one
00000000  --> 0 sent, then "b" shifted right one

```

You can see that the right-most bit is sent (the low-order bit) and then `b` is shifted right (introducing zeroes at the left), until all 8 bits are sent.

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


title: Cost-effective storage for prototyping

text:
# Question
Title: Cost-effective storage for prototyping
In my project I need to add some storage space and I don't want to use an SD card, because in the "final product" the user shouldn't be able to access the data on their own.

So I was considering the options here http://playground.arduino.cc/Main/InterfacingWithHardware#Storage but many of the technologies are either outdated, for example as reads here ADESTO is discontinuing production of dataflash, or they give too little memory, like the I2C EEPROM (which is 128KByte per chip and I would rather not go through the hassle of multiplexing lots of memory chips since I'd like to have 1MByte of storage at least), or are extremely overpriced and cannot be found on retail: some sites require you to buy 2000$ worth of chips or charge you 30$ for delivery, which kind of kills the fun of prototyping something.

I know I am being picky not wanting to use an SD for the prototype, but I would like to know if you ever faced this problem and how you solved it, or if you know some alternative solution which gives a good amount of memory (~1 or 2 MBytes at least) within reasonable costs.

# Answer
> 2 votes
You may not want to hear this, but the cheapest option would be an SD card, or a micro-SD card. You could solder it into place, thus making it quite hard for the end user to take it out and plug it into a reader.

Imagine you had this micro-SD card glued onto your board (making it hard to remove in the first place):

It isn't particularly obvious what it is, unless you recognize the shape. You could cover it with a blob of plastic to hide that. Then with the SPI wires soldered to the contacts, removing would be even harder.

That gives you gigabytes of storage, a file system, the works. And all for a few dollars.

A technically sophisticated user could probably prise it loose and get at the data (although if you used strong glue this could be quite hard) but they could also get at the contents of another storage chip too.

# Answer
> 1 votes
There are plenty of serial flash products available. They are generally SPI chips (8 pin) and range in sizes up to about 64MBit (8MByte). And they're cost effective.

Here's a selection: http://www.microchip.com/pagehandler/en-us/products/memory/flashmemory/sfhome.html

There are plenty of other manufacturers as well. Your best bet is to hit your favourite online electronics store (mouser, digikey, etc) and shop around.

---
Tags: datalogging
---


title: Programming an ATMEGA2560 using FTDI

text:
# Question
Title: Programming an ATMEGA2560 using FTDI
I want to know how exactly do I program (upload arduino sketches) an ATMEGA2560 which is boot loaded with an Arduino Bootloader using a FTDI programmer and an Arduino IDE, is there any capacitors/resistors required?

# Answer
> 1 votes
If you have a bootloader, you just need to connect up four wires from the FTDI cable:

* Pin 1 (black) -\> Ground
* Pin 2 (CTS) -\> not connected
* Pin 3 (Vcc) -\> 5V
* Pin 4 (TxD) -\> Rx (Mega pin D0)
* Pin 5 (RxD) -\> Tx (Mega pin D1)
* Pin 6 (green) -\> not connected

This will not auto-reset, so you will have to press (and release) the Reset button on the board at the moment that the sketch starts to upload.

---

> How to make it auto reset?

What you *should* be able to do is connect RTS to Reset on the board, using a 0.1 µF capacitor (in series). I found in practice that this did not bring Reset low enough to trigger it - I'm not sure why, except maybe the board has a stronger pull-up resistor on /RESET than expected. That technique works for me on breadboard Arduinos.

Since it didn't work for me, I did not put it in my original answer. You could try that, and if it works, well and good.

---
Tags: arduino-mega, uploading, bootloader, ide, ftdi
---


# Question
Title: How can BMP180 measure a temperature too?
I got the following device

(sorry for imperfect focus)

and found, that it can measure not only pressure, but also a temperature too. The code was taken from common sketches for Adafruit BMP085 and they were working. I checked, that temperature value rises if I touch sensor with finger.

Simultaneously, on Bosch site for BMP180 I can't find any notes it can measure temperature, only pressure.

How can it be?

1) Bosch's BMP180 has undocumented feature to measure a temperature

2) The device on picture has additional component to measure temperature

3) The device on picture has completely different sensor, which has the name of "BMP180" just by coincidence.

4) Something else....

# Answer
If you read the data sheet (on the site you point to) you see plenty of references to temperature:

> The BMP180 is designed to be connected directly to a microcontroller of a mobile device via the I 2 C bus. The pressure and **temperature** data has to be compensated by the calibration data of the E 2 PROM of the BMP180.

and

> The BMP180 consists of a piezo-resistive sensor, an analog to digital converter and a control unit with EEPROM and a serial I2C interface. The BMP180 delivers the uncompensated value of pressure and **temperature**. The E 2 PROM has stored 176 bit of individual calibration data. This is used to compensate offset, temperature dependence and other parameters of the sensor.

And many many more.
> 3 votes

# Answer
The BMP085 Barometric Pressure/Temperature/Altitude Sensor- 5V ready page at adafruit.com says the BMP180 is a drop-in replacement for the BMP085.

The BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready page at adafruit.com says the BMP180 is completely identical to the BMP085 in terms of firmware/software/interfacing.

In addition, while Bosch's web page for the BMP085 doesn't mention temperature, the data sheet itself – the final reference, typically, for a device like this – says “Temperature measurement included” on page 2, and on page 14 refers to measuring temperature in steps of 0.1°C, and on other pages shows temperature register numbers, etc. To get the data sheet, click the Documents & Drivers tab, then the BST-BMP180-DS000-12 Datasheet link.
> 2 votes

# Answer
See, for example, Adafruit BMP085 library (it's work with BMP180 too), function

```
void Adafruit_BMP085_Unified::getTemperature(float *temp)

```

in file Adafruit\_BMP085\_u.cpp line 330
> 1 votes

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


title: Programming a motor with an RGB

text:
# Question
Title: Programming a motor with an RGB
*Please see the comments section if confused.* I am trying to turn a motor on and off once per second, and when the motor is on, the RGB turns green. When the motor is off, the RGB is red. Everything is connected to an arduino UNO.I have the motor connected to pins 0 and 1, and to the 5V and GND. The RGB is connected to pins 4, 5, and 6, and the 5V. I have two codes; one with a bunch of screwing around with a bunch of different loops and everything else I've tried, and one with the simple motor on/off code.

```
void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
////  pinMode(2,OUTPUT); //IB2
////  pinMode(3,OUTPUT); //IA2
//  pinMode(4,OUTPUT); //RGB
//  pinMode(5,OUTPUT); //RGB
//  pinMode(6,OUTPUT); //RGB
//  pinMode(A0,INPUT); //lMotor
////  pinMode(A1,INPUT); //rMotor
//  Serial.begin(9600);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);

//  int lMotor = analogRead(A0);
//  Serial.write(lMotor);
////  int lMotor = analogRead(A1);
////  Serial.write(lMotor);
//
//  if (lMotor>10)
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,HIGH);
//    digitalWrite(6,LOW);
//  }
//  else
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,LOW);
//    digitalWrite(6,HIGH);
//  }
}

```

And here's this:

```
void setup ()
{
  pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);
}

```

What do I need to do? Should I use a "while" loop? If so, how? Is my circuit put together properly? I'm using a motor relay switch to turn the motor on/off, but I'm pretty sure it's hooked up right. Any help is appreciated, even if it doesn't answer all of my questions. Thank you.

# Answer
Try this:

```
void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT); //RGB red
  pinMode(5,OUTPUT); //RGB green
  pinMode(6,OUTPUT); //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  digitalWrite(0,motorOn);
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
  delay(1000);             // wait
  motorOn = !motorOn;      // toggle the status of the motor.
}

```

The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:

```
void setup ()
{
  pinMode(0,OUTPUT);   //IB1
  pinMode(1,OUTPUT);   //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT);   //RGB red
  pinMode(5,OUTPUT);   //RGB green
  pinMode(6,OUTPUT);   //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  motorOn = false;
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(1000);             // wait
  motorOn = true;          // toggle the status of the motor.
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(750);              // wait a different time
}

void updateLEDs(){
  // This routine updates the LEDs based on status of motorOn.
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
}

```
> 3 votes

---
Tags: motor, relay, programming
---


# Question
Title: how much current does Arduino Nano draw when only using 8 digital pins?
I want to connect an Arduino Nano to an Intel Minnowboard Max (it's like a Raspberry Pi). I know Arduino can draw up to 500 mA current through the USB connection. Since I already need the USB to communicate the Arduino with the Minnowboard, it would be nice to not power the Arduino separately as well. However, I wouldn't want the current the Arduino draws from the Minnowboard to overheat Minnowboard's 2.5A 12V power supply. I only have 8 buttons connected to the digital pins of the Arduino Nano. Nano sends the state of the buttons to the Minnowboard via USB (serial). How much current is Arduino drawing in this case?

# Answer
I would guess around 50 mA, to power the processor and the USB converter. I notice that this question suggests more like 20 mA.

To be certain, you could measure it, but probably 20 to 50 mA would be a ball-park figure.
> 0 votes

---
Tags: serial, usb, arduino-nano, current
---