# Question
Title: Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?
I have a simple set of 8 push buttons wired to a Teensy 3.2 board (which uses Arduino via Teensyduino plugin). The 8 buttons are on pins 1-8 and their common ground line (one line soldered to each of them) is on the GND pin. I have code to get any one button working that works. It's currently set to make pressing the second button type "A."

I'd like to make push buttons 1 through 8 type out A,B,C...etc respectively as you press them. I've been told of two problems with my setup, the first being that copying the code for every button is a bad way to go about it and second that it's subject to bouncing issues (creates a keystroke once every 5 presses or so.) I'd also like to set this up so in the future I can write a 3rd party app that configures the keys based on the user's preference.

Adding those needs up I'm not sure where to go next. I'm beginner enough that I'm not sure how to properly incorporate the bounce class or if that's the right way to go given the needs.

Is a matrix the way to go or is there an elegant way to manual set each button and compensate for bounce? I'd really appreciate a small example if anyone has done this. Thanks~ Current code follows:

```
#define CHECK_EVERY_MS 20
#define MIN_STABLE_VALS 5

unsigned long previousMillis;
char stableVals;
char buttonPressed;

void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void  loop() {
    if ((millis() - previousMillis) > CHECK_EVERY_MS)
    {
        previousMillis += CHECK_EVERY_MS;
        if (digitalRead(2) != buttonPressed)
        {
            stableVals++;
            if (stableVals >= MIN_STABLE_VALS)
            {
                buttonPressed = !buttonPressed;
                stableVals = 0;

                if (buttonPressed)
                {
                    //Send an ASCII 'A',
                    Keyboard.write(65);
                }
            }
        }
        else
            stableVals = 0;
    }
}

```

**-------** **Edit: WORKING CODE FOLLOWS**

```
/*  jw - 3 Nov 2015 - Program for button debounce demo
Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
*/

//--------------------------------------------------------
enum { sw0=3, sw1=4, sw2=5, sw3=6, sw4=7, sw5=8, sw6=9, sw7=10}; // Switchbutton lines
enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A'},
  {0, sw1, 'B'},
  {0, sw2, 'C'},
  {0, sw3, 'D'},
  {0, sw4, 'E'},
  {0, sw5, 'F'},
  {0, sw6, 'G'},
  {0, sw7, 'H'}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
Keyboard.begin();
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char action) {
  Keyboard.write(action);
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceEnd) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (b->bounceEnd < millis()) {
    b->bounceEnd = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP);
      } else {
        doAction(b->swiNum, 'R', b->swiActR);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

```

# Answer
I'm not sure what you mean by “Is a matrix the way to go”, so will ignore that question.

Shown below is a way of using an array of structs (one of C's ways of organizing a collection of items) to keep data for several buttons, such that it's straightforward to use one subroutine to process each button the same way, using a for-loop to call the routine for each button.

Each element of the array `buttons` is a `ButtonStruct`, and each `ButtonStruct` contains five items: bounceEnd, swiNum, swiActP, swiActR, swiPrev, which respectively represent a debouncing-flag and end-time; a switch number \[ie a pin number\]; a code for action to take on a press; a code for action to take on a release; and previous state of button. (In many special cases, some of these items will be irrelevant and you can leave them out of the `ButtonStruct`.) The form `b->x` that is used in the `doButton()` routine says to access element `x` of the struct that `b` points to.

At the start of each `loop()` pass, `doButton()` is called once for each button. It first tests if debouncing was underway for the button. If so, it sees if enough time has gone by to suppose button bounce is over. If so, it reads the button's state, and if different from previous state, does an action for whichever way the button changed. (If the button state is unchanged after a debounce delay, the program supposes there was a glitch.) If debouncing was not underway, the program checks if the button state is different from most recent pass. In that case, it sets up a debounce test for the button.

The buttons are tested and debounced individually, as you can see in the sample output that is shown following the program. (This program was tested on an Uno, with four independent buttons used in the test. *Edit: Made corrections to handle 32-bit overflow, 2016.10.17*)

```
/*  jw - 3 Nov 2015 - Program for button debounce demo
Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
*/

//--------------------------------------------------------
enum { sw0=8, sw1=9, sw2=10, sw3=11}; // Switchbutton lines
enum { nSwitches=4, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceGo;   // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A','a', 0}, {0, sw1, 'B','b', 0}, {0, sw2, 'C','c', 0}, {0, sw3, 'D','d', 0}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Starting");
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char action) {
  Serial.print("Switch ");
  Serial.print(swin);
  Serial.print(code);
  Serial.print(' ');
  Serial.print(action);
  Serial.print(" at t=");
  Serial.print(millis());
  Serial.println();
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceGo) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (millis() - b->bounceGo > bounceMillis) {
    b->bounceGo = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP);
      } else {
        doAction(b->swiNum, 'R', b->swiActR);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceGo = millis();   // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

```

In the sample output below, a P line indicates a button press, detected at given `millis()` time, and an R line indicates a button release. Observe, near the end, overlaps among separate button presses and releases.

```
Starting
Switch 8P A at t=2170
Switch 8R a at t=2322
Switch 9P B at t=2789
Switch 9R b at t=2969
Switch 10P C at t=3395
Switch 10R c at t=3562
Switch 11P D at t=4087
Switch 11R d at t=4260
Switch 11P D at t=6518
Switch 10P C at t=6961
Switch 8P A at t=7070
Switch 10R c at t=7112
Switch 11R d at t=7427
Switch 8R a at t=7598
Switch 10P C at t=8502
Switch 9P B at t=8642
Switch 10R c at t=8961
Switch 9R b at t=9054
Switch 9P B at t=9954
Switch 11P D at t=10073
Switch 8P A at t=10164
Switch 8R a at t=10215
Switch 9R b at t=10315
Switch 11R d at t=10354

```
> 1 votes

---
Tags: usb, button, teensy, keyboard, debounce
---


title: Regulation of the temperature using PID

text:
# Question
Title: Regulation of the temperature using PID
I'm making a control system for the heating of a plate using a PID control.

the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature of the plate and is then used as the input in the PID control. I programmed also a signal wave square for the PWM.

but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive. and I cannot connect between the PWM and the PID.

Code of the square signal:

```
void setup()
{
  pinMode(9, OUTPUT);
}
void loop()
{
   // phase haute
   digitalWrite(9,HIGH);
   delay(30);
   // phase basse
   digitalWrite(9,LOW);
   delay(70);
   //ton+toff = 0.1;
//   ton = 0.1*Output;
}

```

Code of PID and the sensor

```
/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 3
 ********************************************************/

#include <PID_v1.h>

int val;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);

void setup()
{
  Serial.begin(9600);
  //initialize the variables we're linked to
  Input = analogRead(1);
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  float Input = mv/10;
  myPID.Compute();
  analogWrite(3,Output);
  Serial.print("input temperature is :");
  Serial.println(Input);
  delay (1000);
//  delay(1000);
  Serial.print("output is :");
  Serial.println(Output);
  delay(1000);
}

```

Thank you in advance

# Answer
A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly.

Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for.

Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input.

On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task.
> 2 votes

---
Tags: arduino-uno, pid
---


title: graph of a function Arduino

text:
# Question
Title: graph of a function Arduino
I am making a temperature circuit with arduino. is there any way to plot the value of the temperature in a graph using arduino? thank you very much in advance

# Answer
> 0 votes
Yes you can use the Plot menu command in the new Arduino 1.6.6 or you can use the Visual Micro debugger to create graphs in Visual Studio

---
Tags: arduino-uno
---


# Question
Title: What could make an LCD stop working permanently after being connected for 5 seconds to Arduino?
I was using a 20x4 LCD connected to Arduino Uno via a common I2C adapter board. Everything was working perfectly, including the LCD. I had it running like this for a couple of days without any problems.

My next step was to connect the LCD to a Nano instead in order to make the package smaller. The exact same code from the Uno was uploaded to the Nano, and I connected the wires in the exact same way. The major difference here was that I soldered the wires onto the Nano, because I didn't want to use headers. I did a continuity test for shorts and the connections seemed to be fine. There are only 4 wires between the Arduino and LCD adapter board: 5v, ground, SDA and SCL.

The Nano powers up fine, and the LCD powers up fine, but immediately the LCD shows the following:

That had never happened when I had the LCD connected to the UNO.

After that, the LCD stops working completely, even when I move it back to the UNO. It just constantly displays those 2 lines. (Adjusting the contrast makes the boxes appear or disappear).

After the first LCD seemed permanently broken like that, I tested it on a 2nd brand-new LCD. First I connected it to the same Uno with the same code, and everything was working perfectly. I re-uploaded that same code again to the Nano, just to make sure everything was in sync. Then upon connecting the 2nd LCD to the Nano, immediately it displayed those 2 lines. I disconnected it right away (within 5 seconds), and tried to put it back on the Uno, but still the display is corrupted. I've tried other sketches, but both of these displays seem to be broken and never display anything except for those 2 lines.

Even if I just connect 5v and ground to the LCD, no matter from what source, it just constantly displays those 2 lines.

Any ideas as to what could "break" an LCD so quickly like that, and if it's possible fix it?

**Edit:** As per Gerben's suggestion, I removed the I2C backpack and hooked the LCD up directly. This was the 2nd one I had broken, the one where I'm more certain of its entire (short) history. I ended up with the exact same result. Adjusting the pot only makes the boxes appear or disappear. I tried skipping the Arduino completely and giving it 5v power from an adapter, and it still has the same result.

# Answer
> 4 votes
It's unlikely that you have killed the unit as this is pretty hard to do from the data interface and your picture is typical for an LCD that has not gone through the initialization sequence. A dead LCD driver will usually display nothing and what your picture shows is that the LCD controller itself is operating. If anything is dead, I would suspect the I2C interface board as this would yield the same result you are seeing. It may also be that the timing of the I2C interface is right on the edge which may explain why a long cable'd setup is working.

Note that if the initialization is not done, no other commands will work. Note also that the initialization timing and sequence of events is ABSOLUTELY CRITICAL and missing any single step or time requirement will give the result you are showing.

Starting at page 10 of this instructional PDF is my favorite and the basis of my driver that I have been using since the 80's.

---

The driver I use works on every display I have ever hooked to it, regardless of changes in the particular project's processor clock speed because I paid strict attention to the worst case timing requirements. If the timing of the I2C interface violates one LCD it may not violate another, i.e. one display can tolerate bad timing while another can't. There are also issues if the LCD driver uses the busy flag or not: Blind data transmission without reading the LCD's busy state will work if the LCD is fast enough and the driver is slow enough, otherwise 'No bueno!' plus the interface is not going to operate at its maximum speed. When using the busy flag (Bit 7 of the interface) there is solid handshaking which confirms (Instead of "Trusts") that the LCD is ready for the next cycle and allows operation right up to the limit of performance.

What I would suggest is that you put the interface on a logic analyzer and verify that the timing is not being violated.

Timing tolerances and variation between parts is like lug nuts on a car... If you car has 5 lug nuts per wheel, it will probably work with 3 or even 2 but NOT UNDER ALL CONDITIONS. SOME LCDs will be happy with bad timing but ALL LCDs NEVER will be.

---
Tags: lcd, arduino-nano
---


# Question
Title: Alternative to patching core library source and header files
I am following a DIY guide that requires me to patch two arduino core library files: `HID.cpp` and `USBAPI.h`. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?

# Answer
Unfortunately there *really* isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then amend boards.txt with the core containing the modifications.
> 2 votes

---
Tags: core-libraries, build
---


title: Using Analog Comparator on ATmega32u4

text:
# Question
Title: Using Analog Comparator on ATmega32u4
I am (currently) parsing a PPM analog signal using an Arduino Uno R3 using the analog comparator ASCR and analog hardware interrupts using AIN0 and AIN1. I am applying a specific negative comparison voltage using a linear voltage regulator on AIN0 and the signal on AIN1.

**Code snippets:**

*setup*

```
  ACSR  = B00011011;

```

*outside other closures*

```
ISR(ANALOG_COMP_vect) {
   CRCArduinoPPMChannels::INT0ISR();
}

```

I am trying to move this project to an Arduino (compatible) Pro Micro from SparkFun. The datasheet specifies AIN0 on ATmega32u4 pin 1 but do not see a reference to AIN1.

The datasheet outlines use of the analog comparator on page 289:

> AIN+ can be connected either to the AIN0 (PE6) pin, or to the internal Bandgap reference. AIN- can only be connected to the ADC multiplexer.

I have connected the signal to Arduino pin 7, the comparison voltage to Arduino pin 20 (analog 2) and set the following options of the ADMUX register:

```
ADMUX = B11000101;

```

The interrupts trigger but the comparator voltage (AIN-) is not being observed. Any help would be appreciated.

# Answer
AIN- won't be connected to the ADC mux unless ACME is set and ADEN is cleared. Don't forget to do so.
> 1 votes

---
Tags: atmega32u4, digital-analog-conversion
---


title: Training Commands with easyVR

text:
# Question
Title: Training Commands with easyVR
I am using the EasyVR Arduino Shield with Uno.

What i am trying to do is train a custom phrase like a name.

I want to be able to train the phrase directly with arduino whilst it is not connected a pc. I have noticed in the documentation there are some references to commands like it, but i'm not sure how to go around writing code for such a thing.

thank you

# Answer
> 1 votes
Hi a bit late but I thought it could be useful to someone, I successed to train SD commands without pc easyvr commander with this code:

```
// ARDUINO 1.6.6
// EasyVR Shield 2.0
// EasyVR library v1.7

#include "Arduino.h"
#if !defined(SERIAL_PORT_MONITOR)
#error "Arduino version not supported. Please update your IDE to the latest version."
#endif

#define pcSerial SERIAL_PORT_MONITOR

#include "SoftwareSerial.h"
SoftwareSerial port(12, 13);

#include "EasyVR.h"
EasyVR easyvr(port);

//

char label[33];
uint8_t data;

bool train = false;
bool recog = false;

int8_t group = EasyVR::PASSWORD;
int8_t index = 0;

void setup()
{
  pcSerial.begin(9600);
  port.begin(9600);

  while (!easyvr.detect())
  {
    pcSerial.println(F("EasyVR not detected!"));
    delay(1000);
  }

  //

  easyvr.setPinOutput(EasyVR::IO1, LOW);
  pcSerial.print(F("EasyVR detected, version "));
  pcSerial.println(easyvr.getID());
  easyvr.setTimeout(5);
  //  easyvr.setLevel(EasyVR::HARD);

  //

  printCommands();
}

void printCommands()
{
  pcSerial.print(F("Password: "));
  int16_t count = easyvr.getCommandCount(group);
  pcSerial.print(count);
  pcSerial.println(F(" command(s)"));
  for (int8_t idx = 0; idx < count; ++idx) {
    if (easyvr.dumpCommand(group, idx, label, data)) {
      pcSerial.print(idx);
      pcSerial.print(F(" = "));
      pcSerial.print(label);
      pcSerial.print(F(", Trained "));
      pcSerial.print(data, DEC);
      if (!easyvr.isConflict()) pcSerial.println(F(" times, OK"));
    }
  }
}

bool checkMonitorInput()
{
  if (pcSerial.available() <= 0) return false;

  int16_t rx = pcSerial.read();
  //  pcSerial.print(rx);

  if (rx == 's')
  {
    easyvr.removeCommand(group, index);
    easyvr.addCommand(group, index);
    easyvr.setCommandLabel(group, index, "cuss");

    printCommands();
  }

  if (rx == 't')
  {
    recog = false;
    pcSerial.print("say something");
    train = true;
  }

  if (rx == 'r')
  {
    train = false;
    pcSerial.print("start recognition");
    recog = true;
  }

  //

  if (rx >= 0)
  {
    easyvr.stop();
    pcSerial.flush();
    return true;
  }
  return false;
}

void loop()
{
  checkMonitorInput();

  if (train) {
    pcSerial.println("Train a word");
    easyvr.trainCommand(group, index);
  }

  if (recog) {
    pcSerial.println("Say the word");
    easyvr.recognizeCommand(group);
  }

  //

  do {
    if (checkMonitorInput()) return;
  }
  while (!easyvr.hasFinished());

  //

  int16_t idx = easyvr.getCommand();
  if (idx >= 0) {
    if (easyvr.dumpCommand(EasyVR::PASSWORD, idx, label, data)) {
      pcSerial.print("recognized = ");
      pcSerial.println(label);
    }
    easyvr.playSound(0, EasyVR::VOL_FULL);

  } else {
    if (easyvr.isTimeout()) pcSerial.println("Timed out, try again...");
    int16_t err = easyvr.getError();
    if (err >= 0) {
      pcSerial.print("Error 0x");
      pcSerial.println(err, HEX);
    }
  }
}

```

---
Tags: arduino-uno
---


# Question
Title: Having problems with HC-05 and three relays
I'm trying to control three relays with the Arduino Uno rev3 and a HC-05 bluetooth module from Elecfreaks.

I've wrote this code:

```
// the comments are the part of the code that I use to replace the Serial by default to be able to use the HC-05 module
//#include <SoftwareSerial.h>
int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay1estatus = 0;
int relay2estatus = 0;
int relay3estatus = 0;
char command;
//SoftwareSerial bluetooth(5,6);

void setup() {
 Serial.begin(9600); //bluetooth.begin(9600);
 pinMode(relay1, OUTPUT);
 pinMode(relay2, OUTPUT);
 pinMode(relay3, OUTPUT);
 digitalWrite(relay1, LOW);
 digitalWrite(relay2, LOW);
 digitalWrite(relay3, LOW);
}

void loop() {
 while(Serial.available() > 0){ //bluetooth.available()
  command = (byte)Serial.read(); //(byte)bluetooth.read();
  Serial.println(command); //bluetooth.println(command)

  if (command == 'a'){
   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   }else{
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }
  }

 if (command == 'b'){
  if (relay2estatus == 0){
   digitalWrite(relay2, HIGH);
   relay2estatus = 1;
  }else{
   digitalWrite(relay2, LOW);
   relay2estatus = 0;
  }
 }

 if (command == 'c'){
  if (relay3estatus == 0){
   digitalWrite(relay3, HIGH);
   relay3estatus = 1;
  }else{
   digitalWrite(relay3, LOW);
   relay3estatus = 0;
   }
  }
 }
}

```

The problem is that this code works perfectly using the Arduino IDE serial monitor, but when I try it using instead of the default serial methods, the SoftwareSerial ones it doesn't work.

Doesn't work in a very strange way because I can switch one by one the relays between on or off but, when I have two of them activated seems like freezes, I can't switch the third one on or off and neither I can switch the other two again.

To send the 'commands' through bluetooth I use the Bluetooth Terminal app available in the PlayStore. (I've just posted the same question in stackoverflow but now I think here's the best place to ask it)

# Answer
I don't see a problem with the code indicated for bluetooth; if that code is indeed ok, then probably you should look for hardware issues; first, look for low +5V when multiple relays are turned on. (Attach a voltmeter or a scope to +5, see if it changes when a second relay comes on, etc.) Second, look (with a storage scope) for glitches when the relays switch. If you don't have a storage scope, try testing with a separate power supply for the relays. (Tie the grounds of things together, but give the Arduino and the HC-05 +V that's isolated from relay +V.)

More seriously, your code is overweight. For example, replace

```
   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   } else {
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }

```

with

```
    relay1estatus = 1 - relay1estatus;
    digitalWrite(relay1, relay1estatus);

```
> 0 votes

---
Tags: bluetooth, relay
---


title: IR receiver transmitter High frequency

text:
# Question
Title: IR receiver transmitter High frequency
I build photo gate, to detect throwing ball. It works fine when delay time in main loop for max 40 milliseconds. Problems start when I delay every loop only for 20 milliseconds, now my LED which indicates if something broke path between IR led and IR receiver, **blinks occasionally**, if I set delay for 10 milliseconds and turn on, then LED is off for 2 seconds, then start blinking very fast and is ON for rest time, until I break IR path. I think some physics is going on here which I don't understand.

I also would like to ask if it is possible to **narrow IR wave path to be more like laser** (going strait into one direction) and how I can **control sensitivity** of IR detection

This is schematic

IR transmiter IR reciever

Code:

```
//define pins. I used pins 4 and 5
#define irLedPin 4          // IR Led on this pin
#define irSensorPin 5       // IR sensor on this pin
#define buzzerPin 2       // buzzer on this pin

int irRead(int readPin, int triggerPin); //function prototype

void setup()
{
  pinMode(irSensorPin, INPUT);
  pinMode(irLedPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
  // prints title with ending line break
  Serial.println("Program Starting");
  // wait for the long string to be sent
  delay(100);
}

void loop()
{

  bool isOn = irRead(irSensorPin, irLedPin);
  //Serial.println(isOn); //display the results
  if(isOn == true)
  {
    digitalWrite(buzzerPin, HIGH);
  }
  else
  {
     digitalWrite(buzzerPin, LOW);
  }
  delay(10);
}

int irRead(int readPin, int triggerPin)
{
  int halfPeriod = 13; //one period at 38.5khZ is aproximately 26 microseconds
  int cycles = 23; //26 microseconds * 23 is more or less 600 us
  int i;
  for (i=0; i <=cycles; i++)
  {
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(halfPeriod);
    digitalWrite(triggerPin, LOW);
    delayMicroseconds(halfPeriod - 1);     // - 1 to make up for digitaWrite overhead
  }
  return digitalRead(readPin);
}

```

# Answer
> 3 votes
While you are doing a `delay()` you can't be doing anything else - that includes looking to see if the beam has been broken by the ball.

You *must not* use `delay()` in your sketch, instead use `millis()` as in the **BlinkWithoutDelay** example sketch in the IDE's *File -\> Examples* menu.

Also how you are dealing with your IR system is incorrect. You are first generating a brief square wave and then afterwards you are looking to see what was received. Instead you need to be generating the square wave and *at the same time* see if that square wave is being received. Normally that is achieved by using one of the PWM outputs of the Arduino set to the right frequency to generate a constant waveform which the receiver then senses all the time.

---
Tags: ir
---


# Question
Title: Using Arduino UNO as FTDI programmer for 9DOF Razor IMU
I am trying to upload some code to the ATmega328 on Sparkfun's 9DOF Razor IMU. Because I don't have an FTDI board at hand I was trying to use my UNO by "grounding" the `RESET` pin. Communicating with the 9DOF works well (it has some sample firmware loaded):

**So here's the problem:**

When I try to program the ATmega328, the Arduino IDE gives e the following error:

`avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x0d`

What am I doing wrong?

# Answer
What you're missing is the signal that resets the ATMega so it can enter the bootloader. That signal is the one that goes to the DTR pin of the 9DOF and would normally be sent to the reset pin on your Arduino (that you are grounding).

What you need to do is reset the 9DOF just as it's about to start trying to upload the code. Timing is critical - you get about a second or so of leeway where the bootloader is actually available for avrdude to talk to.

Alternatively you can try and find a point on your Arduino board where the DTR signal from the USB interface chip is available *before* it passes through the capacitor to the RESET pin of the Arduino and take a wire from there (wherever that may be) to the DTR pin of the 9DOF.
> 1 votes

---
Tags: arduino-uno, uart, ftdi, programmer
---


# Question
Title: Timer (or other) interrupt happens while servicing an interrupt - how to accurately handle the second one?
This seems like a simple question but I'm not finding an answer so far: at a high level, say I have a timer interrupt and some input interrupt. The input arrives, the ISR is entered, interrupts are (automatically by default?) disabled, I service the input (quickly!), but while that's going on a timer used for some other purpose fires. I don't want to miss that timer but because interrupts are disabled my input processing won't get interrupted for it.

I exit the input ISR and interrupts are (automatically?) re-enabled. Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

I'm not looking to nest interrupts here, just to understand what happens when an interrupt happens during another ISR which has temporarily disabled them - do they pend and fire after the blocking ISR returns, or are they just lost?

# Answer
Q1:

> ... exit the input ISR and interrupts are (automatically?) re-enabled

Yes, the RETI (return from interrupt) instruction enables interrupts. See third paragraph of section 7.7 in Atmel's document #8271 (a 650-page spec sheet for the Atmega 48, 88, 168, 328 series), which says:

> When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.

Q2:

> Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

If the timer is running a clock, set the timer control bits to automatically reload the count register upon each overflow (or underflow). That will leave a full count period for processing each timer interrupt.

That is, you can pre-load a next-timer-count (I think it can be different from the current count if necessary), so the timer can start its next interval automatically. If the timer is used for some purpose more complicated than that, you may need a nested interrupt.

Q3:

> Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

If indeed input2 sticks around long enough to process after input1 processing is done, no problem. Its interrupt will occur after the first interrupted code sequence executes one more instruction after the RETI occurs. (See paragraph 6 of section 7.7 in doc8271.)

If input2 is brief, several different things can happen. (a) If it is shorter than a clock cycle, in general it won't trigger an interrupt. (b) If it is a level-interrupt-triggering event on INT0 or INT1 that ends while another interrupt is being processed, it won't trigger an interrupt. (See discussion on page 72, section 13.2.3, of doc8271 of INTF0 and INTF1 being clear for level interrupts.) (c) If it is an interrupt-flag-setting event that sets a flag and ends while another interrupt is being processed, it will trigger an interrupt after the global interrupt flag is set, unless current processing clears its flag.

I think the above accurately states what happens on Atmega devices, but I suggest you also see doc8271 – and run tests – to see for yourself. Here is part of what paragraphs 4 and 5 of section 7.7 in doc8271 say regarding (b) and (c):

> There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag. ... Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority.
>
> The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered.
> 1 votes

---
Tags: arduino-mega, avr, isr
---


# Question
Title: Error in my Arduino code " error: expected unqualified-id before ‘if’ "
I cant seem to find this error is:

```
elevator_bug_2.ino:38:1: error: expected unqualified-id before ‘if’

```

Here is the code:

```
// these constants won't change. They are the
// lowest and highest readings you get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the
  // range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}

if (Serial.println("dark") == true)   // LINE 38
{

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}
}

```

# Answer
C is procedural language and code is compiled. You cannot put code beyond procedure as you try to do in mentioned `if`. Remaining code following this point is nonsense. Do you mean you can put second `loop()` based on `if` condition ? I recommend to start learning programming C before using Arduino. In C you can do such a idea using preprocessor directives `IF, ELSE, ENDIF`.
> 2 votes

# Answer
As Tma mentioned earlier, C is a procedural language. That means that all the code must be part of a defined function. So in your code you have the functions void loop() and void setup(). Wich are two functions you must always have in an arduino sketch, but you can also define others. What you cannot do is having two functions with the same name and type in C like you have there, because there is no way to tell them apart from each other. You have two functions called loop and setup...

One basic thing about Arduino code that you must know is the way it runs your code. Every arduinos sketch must have a setup and a loop function. Then when you start the program, it wil first execute the code in your setup function ONCE and then start at your loop function. The name of the loop function already indicates that it will LOOP all the code inside it, so when your program reaches the end of loop() is starts again at the top of loop(). Your program will never reach any point below loop, because you need to specifically call a function to redirect your program to another point. I think the best way to learn Arduino is to study some C first.
> 1 votes

---
Tags: programming, c++, c
---


title: SD.begin() fails second time

text:
# Question
Title: SD.begin() fails second time
When I remove the SD card and try to open a file, I can detect the error properly.

But how do I detect that the card has been replaced after an error? My first thought was to call `SD.begin()` again but it appears that this function returns true exactly once and false thereafter.

Simplified example:

```
void setup() {
  SD.begin(pin); // called exactly once. Works.
}
void loop() {
  // stuff
}

```

But this does not:

```
void setup() {
  SD.begin(pin); // first time calling this function: works.
}
void loop() {
  delay(1000);
  SD.begin(pin); // always fails
}

```

I'd rather not reset the microcontroller just for this.

# Answer
I know this question is relatively old but still, if you wnat to run `SD.begin(chipselect);` again first call `if(root.isOpen()) root.close();` I added this to the library. This way `SD.begin(chipselect)` will return `true` if a card is present and `false` when it's not.
> 3 votes

# Answer
# Update

A **software reset**, while inelegant, was much simpler to implement and debug than trying to add "retry" type functionality to `SD.h`. The other alternative would be to access `SDFatLib.h` or the other lower-level stuff (which `SD.h` is a wrapper for) directly, so if someone has that solution, I'll accept it instead of this one.

# Original

Here is something, which ~~is working well enough for me at the moment:~~ does not reliably work:

```
bool SDState{false};
File LogFile;

bool trySDCard(void)
{
    // sanity check: maybe the SD card is actually here?
    LogFile = SD.open("test.txt", FILE_WRITE);
    delay(10);
    if (LogFile) {
        LogFile.close();
        return true;
    }
    int8_t counter{10};
    while (counter && !SDState) {
        SDState = SD.begin(TFT_CARD_CS);
        Serial.print(counter);
        Serial.print(" ");
        counter--;
        delay(100);
    }
    Serial.print("SD: ");
    Serial.println(SDState);
    return SDState;
}

void setup() {
    SDState = SD.begin(TFT_CARD_CS);
    Serial.begin(115200);
}

void loop() {
    // NB. Simplified a lot (exitMenuMessage(string) is my custom function defined elsewhere)
    switch (state) {
        case SD_RETRY:
            exitMenuMessage(trySDCard() ? "found SD card" : "no SD card");
            break;
    }
}

```

~~Seems to work~~ Sometimes works if I insert the SD card *while* `trySDCard()` is running.
> 1 votes

---
Tags: sd-card, reliability
---


# Question
Title: Prevent reiteration of loop instruction in Arduino/Execute instruction via off switch
I'd like to make an Arduino play a (2sec).wav file once when it is powered on (via push button) and another when it is switched off i.e. when the push button is pushed there is a 2sec delay and the .wav file plays, then the arduino turns off. What would the best way be to implement this? So far I've come up with:

```
void loop()
{
//play .wav file

while(1){}
}

```

or:

```
void setup(){
//play .wav file
}

void loop(){
//empty
}

```

# Answer
An Arduino doesn't understand the concept of "powering off". It is either on (running) or off (not able to do anything).

Your first task must be to design a system whereby the Arduino can control its own power so the Arduino can then go "I have been asked by this external stimulus to switch off. Therefore I will play this sound and then perform whatever actions are required to remove power from myself."

Only when you have worked out how you can get the Arduino to control its own power and still have the ability to manually turn the power on can you begin to think about adding things that happen "when it powers off".
> 1 votes

# Answer
Neither way addresses your second requirement. I would do something like:

```
void setup()
    {
    pinMode (OFF_BUTTON, INPUT_PULLUP);

    //play .wav file
    }

void loop()
  {

  if (digitalRead (OFF_BUTTON) == LOW)  // depending on how it is wired
    {
    delay (2000);   // 2 second delay
    // play .wav file
    // power self off somehow
    }

}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Graph plotting on Python using Tkinter Canvas
I'm trying to plot a graph with python using the canvas widget, I'm currently sending data in from an arduino sensor sketch ..does anyone have an idea on how I can plot this graph in real time on Python using canvas. I've read up on it but I'm having problems with unpacking the x , y and z axis data and looping it to updating in real time. Below is the arduino sketch.And also the skeleton of the Tkinter canvas sketch. Thanks!!

```
AcceleroMMA7361 ski;
int x;
int y;
int z;

void setup(){
    Serial.begin(115200);
    ski.begin(13, 12,11,10, A0, A1, A2);
    ski.setARefVoltage(3.3);
    ski.setSensitivity(HIGH);
    ski.calibrate();
}

void loop(){
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\nx: ");
    Serial.println(x);
    Serial.print("\ty: ");
    Serial.print(y);
    Serial.print("\tz: ");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}//End of Arduino Sketch

  from Tkinter import *
  import serial #import Serial Library
  import numpy as np # Import numpy

  ardoData = serial.Serial('COM4', 115200)
  accelX1 = []     #to hold the incoming axis data from the arduino
  accelY1 = []
  accelZ1 = []

  class GraphException(Exception):
      def __init__(self, string):
         Exception.__init__(self, string)

  class Smoking(Canvas):
     def __init__(self, master, FrameTitle, Col, Row, Height):
        Canvas.__init__(self, master)
          self.FrameTitle = FrameTitle
          self.x1Axis = range(1001)
          self.y1Axis = range(1001)
          self.z1Axis = range(1001)
          self.Line1 = range(1001)
          self.Line2 = range(1001)
          self.Line3 = range(1001)
          self.configure(height=Height, width=750, bg='grey', bd=3, relief=GROOVE)
         self.grid()
         self.grid_propagate(0)
         self.Col = Col
         self.Row = Row
         self.place(y=Col, x=Row)
         self.create_text(380, 20, text=self.FrameTitle, fill = 'black')
         for i in range(0, 1001):
            self.Line1[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='blue', width=0)
            self.Line2[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='red', width=0)
            self.Line3[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='yellow', width=0)

     def LiveValues(self,accelX1, accelY1, accelZ1, Centerline = False, Dritter = False):
          for x in range(1, 59):
             for i in np.arange(1, 1001, 1):
                  while(ardoData.inWaiting() == 0):
                      pass #do nothing
                  ardoString = ardoData.readline()
                  dataArray = ardoString.strip().strip('\n')   #Split into an array called dataArray and strip off any spaces
                # Ensure that you are not working on empty line
               if ardoString:
                   dataArray = ardoString.split(",")
               if len(dataArray) > 1:
                   self.x1Axis = int(dataArray[0])
                   self.y1Axis = int(dataArray[1])
                   self.z1Axis = int(dataArray[2])
                   accelX1.append(self.x1Axis)
                   accelY1.append(self.y1Axis)
                   accelZ1.append(self.z1Axis)
              for x in range(0, 1001):
                 self.coords(self.Line1[x], -10+(x*10), self.accelX1[x], (x*10), self.accelX1[x+1])
                 self.coords(self.Line2[x], -10+(x*10), self.accelY1[x], (x*10), self.accelY1[x+1])
                 self.coords(self.Line3[x], -10+(x*10), self.accelZ1[x], (x*10), self.accelZ1[x+1])

   # Create and run the GUI
   root = Tk()
   app = Smoking(root, "Smooth Sailing", 1000, 1000, 1000)
   app.mainloop()

```

So after working with the answer given on the post I ended up with a Line graph that is not reactive, I understand that I have to tweak the code to suit the range of values I am getting which is shown below. I increased the limit as indicated by @patthoyts but I still couldn't get either lines to show up on the canvas and to even be reactive ( what i mean by that is to respond to the movement of the sensor). Also, do bear with me Editors!, if I'm going about editing this question the wrong way, is just that I'm quite desperate to have this issue resolved. Does anyone have any clue as to how I could resolve this issue. Thanks PS: I added both images , that of my data stream and the image on the canvas.

# Answer
> 1 votes
To generate a useful example I've setup an Arduino Nano with a magnetic orientation sensor and have it output 3 values per line for the X, Y and Z field strengths. It prints 1 line every 50ms and the following python tkinter script plots this. It started as your python code above but it has been reworked to be more pythonic. The result looks like this:

Call the script with the comport and speed. eg: `python magplot.py COM21 19200`

```
#!/usr/bin/python
#
# Read stream of lines from an Arduino with a magnetic sensor. This
# produces 3 values per line every 50ms that relate to the orientation
# of the sensor. Each line looks like:
# MAG   1.00    -2.00   0.00
# with each data line starting with "MAG" and each field separated by
# tab characters. Values are floating point numbers in ASCII encoding.
#
# This script supports both Python 2.7 and Python 3

from __future__ import print_function, division, absolute_import
import sys
if sys.hexversion > 0x02ffffff:
    import tkinter as tk
else:
    import Tkinter as tk
from serial import Serial

class App(tk.Frame):
    def __init__(self, parent, title, serialPort):
        tk.Frame.__init__(self, parent)
        self.serialPort = serialPort
        self.npoints = 100
        self.Line1 = [0 for x in range(self.npoints)]
        self.Line2 = [0 for x in range(self.npoints)]
        self.Line3 = [0 for x in range(self.npoints)]
        parent.wm_title(title)
        parent.wm_geometry("800x400")
        self.canvas = tk.Canvas(self, background="white")
        self.canvas.bind("<Configure>", self.on_resize)
        self.canvas.create_line((0, 0, 0, 0), tag='X', fill='darkblue', width=1)
        self.canvas.create_line((0, 0, 0, 0), tag='Y', fill='darkred', width=1)
        self.canvas.create_line((0, 0, 0, 0), tag='Z', fill='darkgreen', width=1)
        self.canvas.grid(sticky="news")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid(sticky="news")
        parent.grid_rowconfigure(0, weight=1)
        parent.grid_columnconfigure(0, weight=1)

    def on_resize(self, event):
        self.replot()

    def read_serial(self):
        """
        Check for input from the serial port. On fetching a line, parse
        the sensor values and append to the stored data and post a replot
        request.
        """
        if self.serialPort.inWaiting() != 0:
            line = self.serialPort.readline()
            line = line.decode('ascii').strip("\r\n")
            if line[0:3] != "MAG":
                print(line) # line not a valid sensor result.
            else:
                try:
                    data = line.split("\t")
                    x, y, z = data[1], data[2], data[3]
                    self.append_values(x, y, z)
                    self.after_idle(self.replot)
                except Exception as e:
                    print(e)
        self.after(10, self.read_serial)

    def append_values(self, x, y, z):
        """
        Update the cached data lists with new sensor values.
        """
        self.Line1.append(float(x))
        self.Line1 = self.Line1[-1 * self.npoints:]
        self.Line2.append(float(y))
        self.Line2 = self.Line2[-1 * self.npoints:]
        self.Line3.append(float(z))
        self.Line3 = self.Line3[-1 * self.npoints:]
        return

    def replot(self):
        """
        Update the canvas graph lines from the cached data lists.
        The lines are scaled to match the canvas size as the window may
        be resized by the user.
        """
        w = self.winfo_width()
        h = self.winfo_height()
        max_X = max(self.Line1) + 1e-5
        max_Y = max(self.Line2) + 1e-5
        max_Z = max(self.Line3) + 1e-5
        max_all = 200.0
        coordsX, coordsY, coordsZ = [], [], []
        for n in range(0, self.npoints):
            x = (w * n) / self.npoints
            coordsX.append(x)
            coordsX.append(h - ((h * (self.Line1[n]+100)) / max_all))
            coordsY.append(x)
            coordsY.append(h - ((h * (self.Line2[n]+100)) / max_all))
            coordsZ.append(x)
            coordsZ.append(h - ((h * (self.Line3[n] + 100)) / max_all))
        self.canvas.coords('X', *coordsX)
        self.canvas.coords('Y', *coordsY)
        self.canvas.coords('Z', *coordsZ)

def main(args = None):
    if args is None:
        args = sys.argv
    port,baudrate = 'COM4', 115200
    if len(args) > 1:
        port = args[1]
    if len(args) > 2:
        baudrate = int(args[2])
    root = tk.Tk()
    app = App(root, "Smooth Sailing", Serial(port, baudrate))
    app.read_serial()
    app.mainloop()
    return 0

if __name__ == '__main__':
    sys.exit(main())

```

# Update

Looking at the updated question it is clear that the new Tkinter code is not updating the display. In all windowing systems it is essential that the application thread is allowed to process events regularly. This is why the example code above uses the Tk `after()` method to add calls to the event queue. The `read_serial()` function checks to see if any data is available and if not *schedules a retry later*. This is done by using `after()` to request the same method is called again in 10ms time. During that 10ms delay the Tk application processes all the other windowing system events like mouse movement, keyboard input and crucially expose and painting events.

The same method is used to call the `replot()` method once we have updated the list of data items. In this case `after_idle()` has been used which means schedule this function call as soon as nothing else is happening.

The act of changing the canvas line coordinates will cause further events to be raised by Tk which affect the display only once they are processed by the event loop. If we never process the events, nothing will appear on screen.

---
Tags: serial, programming, arduino-due, python
---


# Question
Title: Arduino Orion Upload - Which Board When Compiling
I'm trying to compile and upload the example code for the arduino robotics starter kit (https://github.com/Makeblock-official/Makeblock-Library and https://raw.githubusercontent.com/Makeblock-official/Assembly-Instructions/master/Starter\_Robot\_Kit\_IR\_Instruction.pdf).

In the IDE to compile the code, you need to select the appropiate 'board' for the sketch, and the Arduino Orion isn't listed. Should I just compile under the Arduino Uno, which I believe the Orion is based on?

# Answer
Yes, the "Orion" is just an Uno in a different shape with different connectors. Just treat it like an ordinary Uno.

Similarly the "Baseboard" is just a Leonardo in a different shape with different connectors.
> 2 votes

---
Tags: arduino-ide
---


title: Arduino W5100 AVR

text:
# Question
Title: Arduino W5100 AVR
I'm trying to use a W5100 Arduino Ethernet Shield on a ATMega2560 using avr code.

There exists a library written in C, which should work http://www.seanet.com/~karllunt/w5100\_webserv.zip from http://www.seanet.com/~karllunt/w5100\_library.html

The w5100\_webserv.c should be a working example for an ATmega644p. He mentions that the four callback functions should be modified, namely my\_select(), my\_deselect(), my\_xchg() and my\_reset()

The w5100\_webserv.c also contains the following definitions for SPI\_PORT/DDR CS\_PORT/DDR/BIT and RESET\_PORT/DDR/SPI:

```
/*
*  Define the SPI port, used to exchange data with a W5100 chip.
*/
#define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
#define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

#define CS_DDR        DDRD                /* target-specific DDR for chip-select */
#define CS_PORT     PORTD                /* target-specific port used as chip-select */
#define CS_BIT        2                    /* target-specific port line used as chip-select */

#define RESET_DDR   DDRD                /* target-specific DDR for reset */
#define RESET_PORT    PORTD                /* target-specific port used for reset */
#define RESET_BIT    3                    /* target-specific port line used as reset */

```

I've changed it to the following according to what i think the ATmega2560's datasheet specifies

```
/*
 *  Define the SPI port, used to exchange data with a W5100 chip.
 */
#define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
#define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

#define CS_DDR        DDRB                /* target-specific DDR for chip-select */
#define CS_PORT     PORTB                /* target-specific port used as chip-select */
#define CS_BIT        10                  /* target-specific port line used as chip-select */

#define RESET_DDR   DDRB                /* target-specific DDR for reset */
#define RESET_PORT    PORTB                /* target-specific port used for reset */
#define RESET_BIT    20                   /* target-specific port line used as reset */

```

Furthermore, in the main(), there are also specific code for the AT644p:

```
/*  * Initialize the ATmega644p SPI subsystem */
CS_PORT |= (1<<CS_BIT);                                    // pull CS pin high
CS_DDR |= (1<<CS_BIT);                                    // now make it an output

SPI_PORT = SPI_PORT | (1<<PORTB4);                        // make sure SS is high
SPI_DDR = (1<<PORTB4)|(1<<PORTB5)|(1<<PORTB7);            // set MOSI, SCK and SS as output, others as input
SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

```

I've changed it to the following according to what i think the ATmega2560's datasheet specifies

```
/*
 *  Initialize the ATmega2560 SPI subsystem
 */
CS_PORT |= CS_BIT;                                    // pull CS pin high
CS_DDR |= CS_BIT;                                    // now make it an output

SPI_PORT = SPI_PORT | (1<<PORTB0);                        // make sure SS is high
SPI_DDR = (1<<PORTB0)|(1<<PORTB2)|(1<<PORTB1);            // set MOSI, SCK and SS as output, others as input
SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

```

Lastly i've changed the my\_reset() function: void my\_reset(void) { RESET\_PORT |= RESET\_BIT; // pull reset line high RESET\_DDR |= RESET\_BIT; // now make it an output RESET\_PORT &=~RESET\_BIT; // pull the line low \_delay\_ms(5); // let the device reset RESET\_PORT |= RESET\_BIT; // done with reset, pull the line high \_delay\_ms(10); // let the chip wake up }

I am not sure whether my changes are 100 % correct and i don't know what changes needs to be done to my\_select() my\_deselect and my\_xchg. I hope someone can suggest som corrections.

Thanks in advance.

# Answer
> 0 votes
I've managed to specify the correct ports and bits in order to make the library function on the Arduino ATmega2560 using their Ethernet Shield.

The SPI port definitions has to be changed to the following:

```
#define SPI_PORT    PORTB               /* target-specific port containing the SPI lines */
#define SPI_DDR     DDRB                /* target-specific DDR for the SPI port lines */

#define CS_DDR      DDRB                /* target-specific DDR for chip-select */
#define CS_PORT     PORTB               /* target-specific port used as chip-select */
#define CS_BIT      4                   /* target-specific port line used as chip-select */

#define RESET_DDR   DDRB                /* target-specific DDR for reset */
#define RESET_PORT  PORTB               /* target-specific port used for reset */
#define RESET_BIT   8                   /* target-specific port line used as reset */

```

The section about the AT644p in the main() function has to be changed to the following:

```
/*
 *  Initialize the ATmega2560 SPI subsystem
 */
// Initial SPI Peripheral
SPI_DDR = (1<<PORTB2)|(1<<PORTB1)|(1<<PORTB0);

// CS pin is not active
SPI_PORT |= (1<<CS_BIT);

    // Enable SPI, Master Mode 0, set the clock rate fck/2
SPCR = (1<<SPE)|(1<<MSTR);
SPSR |= (1<<SPI2X);

//Disable the SD card
DDRB |= (1<<CS_BIT);

```

---
Tags: ethernet, avr, spi, port-mapping
---


# Question
Title: Why serial communication does not work on atmega168/328p?
I expect from the following program `serial.c` to light the led on if I send key `1` from terminal, and light the led off when I send key `0` from terminal:

```
#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data;
void main(void) {
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B |= (1<<RXEN0);
  UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
  DDRB |= (1<<PB1);
  while(1) {
    while(!(UCSR0A&(1<<RXC0)));
    data = UDR0;
    if (data=='0') PORTB &= ~(1<<PB1);
    if (data=='1') PORTB |= (1<<PB1);
  }
}

```

I use the following commands to compile and burn all the programs:

```
avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

```

The output of avrdude is the following:

```
$ avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

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

Writing | ################################################## | 100% 0.03s

avrdude: 12 bytes of flash written
avrdude: verifying flash memory against serial.hex:
avrdude: load data flash data from input file serial.hex:
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: input file serial.hex contains 12 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 12 bytes of flash verified

avrdude: safemode: Fuses OK (E:07, H:DE, L:FF)

avrdude done.  Thank you.

```

For serial connection I tried PL2302 and FT232RL usb-com adapters - the effect is always the same.

Terminal settings on the computer are correct (9600,8N1).

avr-gcc version 4.8.1 avrdude version 6.1

Why the very first program in this question does not work as needed and what should be changed in it to achieve the desired behavior?

# Answer
> 1 votes
The problem you have is that your baud rate is not being set right.

You only have part of the settings you need. There is a third macro in the setbaud.h file that you need to take account of: `USE_U2X`.

That defines whether or not you need to set or clear the U2X0 bit of UCSRA0. If that is set wrong then your baud rate will be either twice or half what you want it to be - in this case it's coming out as twice.

Modify your code to assign the baud rate like this:

```
#include <util/setbaud.h>
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_U2X
UCSR0A |= (1<<U2X0);
#else
UCSR0A &= ~(1<<U2X0);
#endif
UCSR0B |= (1<<RXEN0);
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);

```

Then you should be able to receive characters.

In the actual header file in question there is a large number of comments and instructions, including this:

> Assuming that the requested BAUD is valid for the given F\_CPU then the macro UBRR\_VALUE is set to the required prescaler value. Two additional macros are provided for the low and high bytes of the prescaler, respectively: UBRRL\_VALUE is set to the lower byte of the UBRR\_VALUE and UBRRH\_VALUE is set to the upper byte. **An additional macro USE\_2X will be defined. Its value is set to 1 if the desired BAUD rate within the given tolerance could only be achieved by setting the U2X bit in the UART configuration. It will be defined to 0 if U2X is not needed.**

My resulting UART configuration, which may be being affected by the bootloader, is:

```
UBRR0H: 0x00
UBRR0L: 0x67
UCSR0A: 0x20
UCSR0B: 0x10
UCSR0C: 0x06

```

That equates to `data register empty`, `RX enabled`, `8-bit`.

To my mind that is equal to the values being manually set in the code, so shouldn't be a problem.

---
Tags: serial, atmega328, avr-gcc, pl2303hx
---


# Question
Title: References (e.g, libraries and tutorials) for connecting the 24-bit ADS1256 ADC to arduino
The ADS1256 chip is a high precision 24bit, 8 channel, analog digital converter based on SPI communication that is suitable for biomedical applications and perfect for sensing ECG and EEG signals. I want to hook it up to an arduino, e.g., an arduino mega or an arduino due.

Similar ADCs from analog devices are: ADS1248, ADS1251, ADS1252, ADS1252U, ADS1253, ADS1255, ADS1259, ADS1278, ADS1298, ADS1299, etc.

It’s nice that there are \[tiny, coin sized breakout boards\] available for the ADS1256 that include basic components like an 8mhz quartz crystal and cost only around 25 USD.

Several people have in the past struggled to get ADC readings using Arduino. Working only with the data sheet it took them several days or even weeks. I have a logic analyzer, multi channel oscilloscope and bus pirate ready, but I still would prefer adapting an existing library or working with a good tutorial as a starting point.

I searched for code and tutorial not only for the ADS1256 but also for similar analog devices ADC chips.

Here are the tutorials, libraries and information I found so far:

**Main Links (working solution):**

-- ADS1213 Arduino library (seems to be working!!!)

-- ADS1213 Arduino tutorial (includes above library)

**Further Information:**

**Q:**
Is there a working library for the ADS1256 (or similar chip) and is there a current, up-to-date tutorial available for arduino?

---

(Update with my notes.)

**Next steps** (to get a working library that should be put on github):

1. Search for more relevant Information online (existing libraries, etc.)
2. Ask in AVR specific forum, if question is unanswered here. Possibly contact people via e-mail that could know more
3. Get familiar with Chip and Datasheet
4. Decide on available codebase as the starting point
5. Define the minimalistic testcase (This would check that some for of communication works with the chip, i.e., write register that changes the logic level of a bin of the ADC chip)
6. Implement the minimalistic testcase (i.e., possibly use different codebase as starting point if it fails to implement)
7. Expand and test the code to get a full implementation

**Risks:** Eittle experience with electronic design the microcontroller at hand, might miss important details that costs a lot of time. Can't be sure that my chip/PCB actually works, can be faulty hardware.

**Time Estimate**: 3 days of work doing 8 hours a day (total 24 hours). Exremly high variance (could be a matter of a few hours in the best case to a few weeks worst case).

# Answer
You are lucky. Looks like there is an Arduino library available for the ADS1256. You should give it a shot: https://github.com/Flydroid/ADS12xx-Library .

I haven't tested it but checked the registers and functions from the datasheet and it does look good.
> 2 votes

---
Tags: serial, arduino-mega, arduino-due, spi, analogread
---


# Question
Title: Computer to multiple arduino bluetooth modules
Im going to take part in a competition called IEEE Very Small Soccer and I need to set up a communication between my computer, that will run visual and strategy algorithms, and send some commands to 3 Arduinos, which will be the players. Most people use the Xbee module to send data to the Arduinos, so I was wondering why not use the Bluetooth module instead, once it is so much cheaper and the difference in power consumption isn't so big, the only drawback would be the working range, which is 10m, if Im correct... However, if the distance is really 10m, not 5m It will be ok, because the computer is always close to the robots.

Summing up, my questions are:

1. Can I use a computer to send data to 3 Arduinos at the same time?
2. What is the real working range of the Bluetooth module?
3. Any suggestions or tips? =D

?

# Answer
> 0 votes
1. yes, you can, this is what happens normally in a crowded area where multiple people use their phones with bluetooth headsets, for example.
2. if you believe the claims typical 10m max 100m but in practice there are a number of factors:

* Quality of the HW design of the antennas
    * Signal to noise ratio due to other radios operating in the same area
    * Obstacles in the path
    * Responsiveness and throughput required by your application
    * etc.
3. you could consider other options, like this module, which is basically the same, from the perspective of transferring data. Also wifi could work, if you are allowed to setup your own access point.

---
Tags: bluetooth, arduino-nano
---


# Question
Title: Burning arduino generate hex file to blank atmel chip
Is it possible to burn the hex file to a blank chip, generated by Arduino to burn using USBASP to that particular chip without using Arduino board ? Will the program work ?

---

My main goal is to use Atmega328P for low power. Should I select Arduino pro mini in the arduino IDE ?

Ater successful testing I will just burn the hex file to another 50 chips. thats why I dont want to use arduino board.

# Answer
> 2 votes
Yes. The binary generated by the Arduino IDE in no way requires the presence of the Arduino bootloader in order to operate. Note that certain characteristics such as the MCU and clock rate are set at build time and cannot be changed in the final binary.

# Answer
> 2 votes
Yes that's no problem as long as you check your fuse bytes. And the connections to the 6pin ISP header. Make sure you study the avrdude command line and the manual for the particular Atmel chip.

I'm assuming the programmer you are using must use avrdude to be able to work.

I often use a nice GUI called "avrdudess" which is freeware. Great for avr beginners, and takes some of the effort out of writing directly into the command prompt.

---
Tags: avr
---


# Question
Title: How to measure relay current draw from Arduino
How does one measure the amount of current a relay is drawing from an Arduino?

Do I connect a multimeter in series with the digital pin to which the relay 'IN1' is connected (in this case pin 7), the 5V pin or GND pin?

Provisional testing gives me the following results (when the relay is ON):

1. Pin 7: **3.93 mA**
2. 5V pin: **70.2 mA**
3. GND pin: **66.8 mA**

Also, assuming I pull more than 40 mA through digital pin 7 for a number of seconds, is the pin likely to fail immediately? Or slowly degrade over time?

# Answer
Have you noticed how the 5V current is, give or take a little inaccuracy on the part of your ammeter, the sum of the other two currents?

Without knowing what relay you are talking about, my guess is it is one of the SainSmart 5V relay modules with opto-coupler. Those, by default, use a common 5V input and split it between the opto-coupler (and then into your digital pin to be sunk through ground) and the relay to ground. Therefore the 70mA is split between 66mA through the relay and 4mA through the digital IO pin.

So the correct place to measure the total current in this instance is the 5V pin since that is the common point for the circuit.

In answer to your second question, *read the datasheet*. It quite clearly states:

> Although each I/O port can sink more than the test conditions (20 mA at VCC = 5V, 10 mA at V CC = 3V) under steady state conditions (non-transient), the following must be observed:
>
> ATmega48PA/88PA/168PA/328P:
>
> 1. The sum of all I OL , for ports C0 - C5, ADC7, ADC6 should not exceed 100 mA.
> 2. The sum of all I OL , for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100 mA.
> 3. The sum of all I OL , for ports D0 - D4, RESET should not exceed 100 mA.
>
> If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

And also a similar note for sourcing current.

So although they *can* sink or source more than 20mA, and theoretically up to 40mA, anything more than 20mA is not guaranteed and should be avoided.

Basically overcurrents cause increased heat dissipation in the MOSFETs which causes the internals to break down. Hence the note about *under steady state conditions*.

So sourcing or sinking more than 20mA for longer than a few ms is asking for trouble. More than 40mA is just being irresponsible.

Furthermore, the MOSFETs in the IO pins act like resistors when turned on. As you should know, according to Ohm's Law, the voltage across a resistor is proportional to the current through the resistor. Increase the current and you increase the voltage across the resistor. Since that resistance is in series with your circuit that voltage gets subtracted from your available voltage on the IO pin - so drawing too much current will cause the voltage to drop (or rise for sinking) below (above) the specifications for the logic voltage for that IO pin. So not only do you risk damage to the IO pin and other parts of the chip through overheating, but you also then operate outside the specifications for the logic levels which can cause things that you are communicating with to not work right.
> 1 votes

---
Tags: relay, current
---


title: Why were Atmel MCUs used for Arduino?

text:
# Question
Title: Why were Atmel MCUs used for Arduino?
Atmel microcontrollers are not cheap compared to STM and Microchip. Why did Arduino select Atmel MCUs such as atmega328 and atmega2560 on their board out of so many alternatives?

# Answer
Simply because the Wiring system that Arduino stole was written for the Atmel chips.

Arduino didn't "invent" the Arduino system - they just took an existing system called Wiring and adapted it slightly and branded it Arduino.
> 6 votes

---
Tags: atmega328
---


# Question
Title: Sending serial data to Arduino from Matlab(not using support package)
I am learning Arduino and trying to understand how integers and strings are sent across the serial port. I tried a small program in arduino which reads a number as a string and tries to blink led 13 according to that number. Below is the arduino side of code.

```
const int ledpin = 13;
int value = 0;
int blinkrate;
void setup()
{
   Serial.begin(9600);
   pinMode(ledpin,OUTPUT);

}

void loop()
{
    if (Serial.available())
      {
         char ch = Serial.read();
         if (isDigit(ch))
            {
               value = (value*10) + (ch - '0');
            }
         else if (ch == 10)
            {
               blinkrate = value;
               Serial.println(blinkrate);
               value = 0;
            }
      }
    blinkled(blinkrate);
}

void blinkled(int blinkrate)
 {
   digitalWrite(ledpin,HIGH);
   delay(blinkrate);
   digitalWrite(ledpin,LOW);
   delay(blinkrate);
 }

```

When i try to send a string from MATLAB, the RX led blinks once indicating something is coming, but the LED on pin 13 is not behaving accordingly(it should blink according to the number i send). Here is the matlab side of code.

```
pre_open = instrfindall;
delete(pre_open);
serial_port = serial('COM3');
set(serial_port,'Terminator','CR');
set(serial_port,'BaudRate',9600);
set(serial_port,'DataBits',8);
set(serial_port,'StopBits',1);
set(serial_port,'Parity','none');
fopen(serial_port);
num = 200;
fwrite(serial_port,int2str(num));
data = fscanf(serial_port,'%d');
pause(2);
fclose(serial_port);

```

When i try to read the return string from arduino, MATLAB shows me a timeout error.

I would be grateful if anybody points me to the right solution. Thank you.

# Answer
> 1 votes
Got it, instead of depending on the Serial object, i sent the line feed to arduino. All this time it has been waiting for the Line feed that never arrived.

```
delete(instrfindall)
s = serial('COM3', 'BaudRate', 9600); %38400
fopen(s);
pause(0.1);
text = input('enter','s');
fprintf(s,'%s\n',text,'sync');
pause(0.1);
d = fscanf(s,'%s');
pause(0.1);
delete(instrfindall)

```

# Answer
> 0 votes
You're setting the terminator to be 'CR'. CR, or Carriage Return, is character 13. In your Arduino program you are looking for character 10. That is 'LF' or Line Feed.

Either are commonly used to denote a line ending, but both ends must agree on which it is.

For instance, Unix files use a single LF for a line ending. Windows files use the combination of both a CR and an LF. Many networking protocols use a single CR for the line ending. It really doesn't matter what is used *as long as it is consistent.*

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


title: Arduino UNO, using 5V and 3.3V

text:
# Question
Title: Arduino UNO, using 5V and 3.3V
I am newbie in Arduino (using UNO) and as I have 2 components that I wish to connected that one needs 5V and the other need the 3.3V, is it safe to connected them together next to each other?

# Answer
> 1 votes
If a component needs 5V it must be connected to 5V. If it needs 3.3V it must be connected to 3.3V. Connecting a 3.3V component to a 5V supply is a sure fire way of destroying it.

Furthermore, since the Arduino's main chip is a 5V device, if you want to connect it to a 3.3V device you must use some form of *level translation* so that the 5V signals from the Arduino don't damage the 3.3V device. Also it may (though not always) be necessary to convert the signals from the 3.3V device to a level that the Arduino can understand (5V).

---
Tags: arduino-uno
---


# Question
Title: How can I have two Arduino Uno's communicate wirelessly?
I'm an art student, using arduino in an Electronic Arts Class. I have already created a skateboard speedometer, using a Hall Effect Sensor and a magnet embedded in one of my skateboards wheels. I've attached a speaker to the arduino that plays a tone, with the pitch depending on the RPM's of the wheel. (the faster the board is going, the higher pitch the tone being played is). Currently the speaker is attached to the skateboard and wired directly to the arduino. My goal is to have a speaker with an arduino wirelessly connected to the arduino on the skateboard. The arduino on the skateboard record's the RPM's and then wirelessly send that information to the second arduino to play the tone through the speaker. Is this possible? what hardware would yo recommend? I've been looking at the Bluetooth HC-05 but I'm not sure this will work. Thanks for any help!

# Answer
> 1 votes
ESP8266 is also a good choice. these little guys are really useful and give you a Wi-Fi connection between your Arduino boards.

Also, the cost of one ESP8266 is about $3.. super cheap!

---
Tags: wireless
---


title: creating array using string name

text:
# Question
Title: creating array using string name
I appreciate if someone can help me. I have a function that counts the time and I would like to store values according to the day.

`For example: day_7.11.2015 = [gain = 100.23, cost = 78.0 ...]
 day_8.11.2015 = ...`

I do not know how can I create an array with these values taking as input the day, month and year. Does anyone have any idea?

`String test = "day_" + String(day) + "." + String(month) + "." + String(year);
float String(test)[] = {11.2, 10, 20, 31.2};
 Serial.println(test);`

Thanks a lot!

# Answer
> 0 votes
What you're talking about is often called a *Hash* or a *Map* or sometimes both together as a *HashMap*.

Unfortunately it's a facility that isn't supported in the Arduino C++ language

There are `map` objects available in normal C++, but they are incredibly expensive to use with regards to memory and they just aren't practical for use on a small microcontroller with memory measured in the kilobytes.

The closest you can probably get is to "invert" the storage, so you have a list of values that happen to be in date order (because that's when you added them) but the "key", a simple sequential number, doesn't define the date. Instead you store the date inside the array along with the data - assuming you really need to know the date.

A good concept to get to grips with for this is the *struct*. This is a custom data type which you define and can store a number of other different data types within itself. You can then make an array or linked list out of those new data types.

For instance, you may have:

```
typedef struct {
    int year;
    byte month;
    byte day;
    float gain;
    float cost;
} Data;

```

You can then create variables of type "Data" and assign values to the items within it:

```
Data myEntry;
myEntry.year = 2015;
myEntry.month = 11;
myEntry.day = 7;
myEntry.gain = 100.23;
myEntry.cost = 78.0;

```

Or assign them directly at creation time:

```
Data myEntry = {2015, 11, 7, 100.23, 78.0};

```

If you wanted to store 100 days' worth of data you could use an array:

```
Data myArray[100];

```

Then you access each slice:

```
myArray[0].year = 2015;
... etc ...

```

I mentioned above "assuming you really need to know the date". Most of the time with this kind of method you really don't need to store the date. If you have one entry per day and you know *when you started gathering data* then you know that each entry is one day more than the one before it - so you know that the tenth entry is ten days later than when you started gathering data. Alternatively, if you have a 100 entry circular array (that is, when you reach the end of the array you start filling from the bottom again, so you keep the last 100 days' worth of data) and you know what the date is *today* you can count backwards from today to work out what date each entry is.

---
Tags: arduino-mega
---


# Question
Title: Getting a binary string and convert it to decimal
I have a 4 dipswitch to get a 1 or a 0, try to get that into a string and from that get a decimal, therefor if I get for example a 0011 a 3.

so, I know that from the variations of 0000 to 1111 is a decimal from 0 to 15, I already have my string but how do I convert the "binary string" to decimal?

to get the string I'm using this (the I is at 5because there is where is the dipswitch):

```
      for(int i = 5; i <= 9; i++){
           Serial.println(digitalRead(i));
           Dstate = Dstate + digitalRead(i);
      }

```

# Answer
> 1 votes
What you want are the bit-shifting operators \<\< and \>\>, and the OR operator |:

```
for(int i = 0; i < 4; i++) {
    Serial.println(digitalRead(5 + i));
    Dstate = Dstate | (digitalRead(5 + i) << i);
}

```

You'll notice I changed the loop so it runs from 0 to 3 instead of 5 to 9 - it makes other parts easier if you start counting from 0.

Then the line:

```
Dstate = Dstate | (digitalRead(5 + i) << i);

```

is where all the magic happens. Let's break it down:

```
digitalRead(5 + i)

```

That of course gives you a 0 or 1 for pins 5, 6, 7 and 8 in turn.

```
<< i

```

That shifts the value returned by `digitalRead()` left `i` bits. For instance, if `digitalRead()` returns 1 and `i` is 0 then `1` is left shifted 0 times so remains as 0b0001. If `i` is 1 then it left shifts one bit, so the value becomes `0b0010`. If `i` is 2 then it shifts two bits, so you get `0b0100`.

Finally the result is combined with the current value of `Dstate` with OR, so the four values basically get laid over the top of each other.

So say you have the four switches in the positions ON-OFF-ON-OFF and `Dstate` starts off as 0, then the sequence would be:

```
i = 0, digitalRead = 1, shifted = 0b0001, OR = 0b0001
i = 1, digitalRead = 0, shifted = 0b0000, OR = 0b0001
i = 2, digitalRead = 1, shifted = 0b0100, OR = 0b0101
i = 3, digitalRead = 0, shifted = 0b0000, OR = 0b0101

```

---
Tags: arduino-nano
---


# Question
Title: Can't get Ubuntu to see FTDI cable for breadboarding Arduino project
I am in the process of breadboarding an Arduino for a project and am using my FTDI Serial cable Adafruit FTDI Cable (tested working on Windows 7). I have also tested the breadboarded Arduino successfully on Win7.

When I plug the FTDI Serial cable into my Linux (Ubuntu 14.04 with Mint Desktop) laptop and the other end to my project (exactly as I did for Windows and it works for Win7), the Tools, Port is grayed out when in Linux.

I have tried running Arduino as root, with no success.

The output of : dmesg | tail is

```
sudo dmesg | tail
[  729.069015] usb 4-1.2: New USB device strings: Mfr=1, Product=2,     SerialNumber=3
[  729.069019] usb 4-1.2: Product: TTL232R-3V3
[  729.069022] usb 4-1.2: Manufacturer: FTDI
[  729.069024] usb 4-1.2: SerialNumber: FTF50VXW
[  729.487689] usb 4-1.2: USB disconnect, device number 4
[  729.615330] usbcore: registered new interface driver usbserial
[  729.615384] usbcore: registered new interface driver usbserial_generic
[  729.615432] usbserial: USB Serial support registered for generic
[  729.621997] usbcore: registered new interface driver ftdi_sio
[  729.622057] usbserial: USB Serial support registered for FTDI USB Serial Device

```

When I type "lsusb" into the terminal, there is no difference between when the FTDI is plugged in and not plugged in. I have tried switching ports with no success.

Any suggestions?

# Answer
> 1 votes
Check if the driver is loaded, in Terminal type:

```
lsmod | grep  ftdi_sio

```

If you get no answer then it's not loaded, load it using:

```
sudo modprobe ftdi_sio

```

I hope this helps.

---
Tags: arduino-uno, ftdi
---


# Question
Title: Arduino Leonardo bugs and lack of removable microcontroller
Following one of the article from 2013 :

> Before you start hammering that “add to shopping cart” button, note that the general impression around the web seems to be that the Leonardo still has a few bugs that need ironing out, and isn’t quite as beginner friendly as the Uno. For builders already familiar with Arduino, this is the better deal.

The question is if Leonardo is still buggy and may cause any confusion to newbie Arduino programmers. Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

# Answer
> 2 votes
> The question is if Leonardo is still buggy

Probably.

> and may cause any confusion to newbie Arduino programmers.

Definitely. The whole way the Leonardo works is very different to the likes of the Uno. Transitioning from one to the other, if you don't know what the differences really mean, can be confusing.

> Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

You build your circuit on a PCB and you provide an ICSP header. ICSP stands for *I*n *C*ircuit *S*erial *P*rogramming. You then use a hardware programmer to install either the Leonardo bootloader, which can then be used to install sketches through USB, or install a sketch direct without the bootloader.

Or, if you're making thousands of them you send your code to Atmel and they burn it to the chip in the factory for you - at a price of course.

---
Tags: arduino-leonardo
---


# Question
Title: what is the difference between providing 7 volts or 12 volts to arduino uno?
according to this the recommended input voltage is between 7 and 12 volts.
The question is what is the difference between providing 7 volts(minimum recommended volts) and 12 volts(maximum recommended volts) ?.

# Answer
> 2 votes
The amount of heat dissipated by the voltage regulator. The higher the voltage you supply the hotter the regulator will get.

---
Tags: arduino-uno
---


title: Turning on led every half hour

text:
# Question
Title: Turning on led every half hour
How can I make my program so that every half hour LED lights on and work for 5 minutes and than go off and the process should repeat

I made code but it does not works. Can someone help me?

```
void setup() {
  pinMode(8,OUTPUT);

}
void loop() {
  digitalWrite(8,HIGH);
  delay(300000);
  digitalWrite(8,LOW);
  delay(1800000);

}

```

# Answer
> 2 votes
1. Test the LED: Connect it between +5v and ground *with* its current-limiting resistor. Make sure the cathode is connected to ground and not the other way round. Inside the plastic bubble are two tiny bits of metal. The larger one is the cathode. Does it light? If not, the LED is faulty or the resistor is too high.
2. Reconnect the LED to pin 8, which is physical pin #14. (In case you got confused and used physical pin 8, no harm was done - physical pin 8 is another ground!) Reduce the delay times to 1 second on, 1 second off. Again be sure to connect its cathode side to ground. Does it blink? If not, perhaps Arduino's pin 8 driver is faulty.
3. Try the same thing on a different pin (adjusting your code, of course). If it still doesn't blink, there is probably an issue with either the MCU chip or the power you're supplying to it. Assuming you used the board's +5v and ground in test (1.), then the power is OK and the chip is likely the cause.

# Answer
> 1 votes
I see that the code is OK,
are you sure that the led pis is 8 ?
what is your input voltage ? (is it between 7 to 12 ?)
did you tried lower time values ? (like 1:2 minuts ?)
if you answer to all of these questions is "yes" then probably the arduino board is broken.

# Answer
> 1 votes
You need to make sure that the LED is connected with the right polarity, you need to connect the negative to Ground and the positive to the digital pin 8.

Try the led by connecting 3.3v and GND so you are sure that the led is not broken.

---
Tags: arduino-uno, led, timing
---


# Question
Title: Algorithm to detect motion using ultrasonic sensor
I have a PIR sensor which sometimes give false readings and I have added a ultrasonic sensor to compensate for that. I think my algorithm can work, however currently it is very prone to give false positives.

## Algorithm theory

My idea is to have an arduino which will obtain six samples and wait 25 milliseconds between each sample and then calculate the variance. If the variance exceeds a specific threshold, which I have set to a thousnad, it will send an motion event over the serial bus.

## Problem with the algorithm

Ultrasonic sensors can give faulty responds which usually isn't hard to detect. My HC-SR04 sensor can only accurately read the distance between 2 cm and 400 cm. All the faulty readings are usually way over 400 cm or lower than 2 cm, therefore if is not within these boundaries a new try will be made to get a value within the boundaries, if it fails for three times it will assume the distance is exactly 400 cm.

It is redundant to wait for more than 23280 µs because 400\*29.1\*2 is the corresponding microseconds it would take for the distance to be 400 cm. `pulseIn` has a timeout value which can be used for this.

In theory this sounds great to me but very often this algorithm will erroneously send motion events. My belief for this is that when the ultrasonic sensor transmitts a wave and wait for it come back, `pulseIn` will timeout and retry and yet again ask the sensor to send a wave. This happens before the first wave has come back thus the distance will be incorrect and vary from time to time making the variance higher than my threshold.

If the distance is much lower than 4 metres my algorithm works very well.

## What I tried

I figured I might be able to block for some time until the *echo* pin on the ultrasonic sensor turns low or a time of 100ms has passed. The code hanged and I couldn't communicate with my arduino any more. I can't see the problem with my code to obtain the distance pursuant to the ultrasonic sensor.

```
for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      continue;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
}
return 400.0f;

```

This just blocks my program indefinently and I had to upload a new program removing that code for my arduino to respond again.

So my question boils down to: how can I resolve this issue where my algorithm very frequently sends motion events erroneously? Is there a better way to detect motion with an ultrasonic sensor?

(**EDIT:** I was really tired when I wrote the code above and Majenko corrected me, I changed the code for this

```
for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(PINB & 0b00000010) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      goto retry;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
  retry:
  continue;
}
return 400.0f;

```

# Answer
The main blocking part of your code is this bit:

```
while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
  if((micros() - time) >= 100000) {
    continue;
  }
}

```

That is saying "While the echo pin is low, check the time. If too much time has passed then carry on with the loop".

So basically that will loop until the echo pin goes high, regardless of the time.

The `continue` command means to jump back to the beginning of the loop that it's in, be that a while, for, or do loop. In this case it jumps back to the beginning of the while loop it's in.

Instead you should consider using `break`, which means "Terminate this loop and carry on with what comes next".

---

Ultrasound sensing with `pulseIn()`, while simple to perform is rarely particularly accurate. Any interrupts that occur during the sensing will affect the outcome, and it's only as accurate as the micros() function allows it to be.

If you need a more precise and reliable measurement you should consider using one of the *Input Capture* modules in the ATMega. I don't know if there is a library to do it off hand, but programming it through the registers shouldn't be that difficult - just read the datasheet to find out how it all works.

Briefly the operation of IC is:

1. Send trigger pulse
2. Start IC timer counting
3. Pulse arrives
4. IC stops counting automatically and interrupt is triggered
5. Read counter value and convert to microseconds.
6. Set flag to indicate a result is available

The timing source is the main system clock and counting happens in the background completely parallel to the operation of the CPU, so nothing can interrupt it or delay it. Even if the execution of the IC interrupt routine is delayed by another interrupt running the counter value will have already stopped incrementing, so it will have been "captured" and give the correct result every time.
> 1 votes

---
Tags: sensors, atmega328, algorithm
---


# Question
Title: Battery Solution for ESP8266 and HC-SR04
I'm working on a project that includes an ESP8266 (requires 3.3v input (250 mA peak)) and a HC-SR04 (requires 5v 20 mA peak). I'm making it battery/solar powered.

I'm trying to keep costs down as well as make a system that works reliably and has good longevity.

I'll be waking the device every 15 minutes and keeping it in deep sleep at the other times.

Originally I was going to use a battery source over 6v, like a 6 cell AA rechargeable battery pack, a 10v or so solar panel, and a breadboard type voltage regulator that conveniently provides 3.3v and 5v on the same board. This seems to waste a decent amount of power though.

Right now I'm looking into using a 2 AA rechargeable NiMH batteries, a 5v solar panel, a 3.3v step up voltage booster, and a 5v step up voltage booster. 5v step up voltage boosters are everywhere and cheap because of their uses for portable cell phone chargers. 3.3v step up voltage boosters on the other hand are more expensive and harder to find.

Looking for any advice or affirmation that I'm on the right path. Thanks!

# Answer
> 1 votes
A time a go when searching for some circuit to provide power to ESP and also being capable of charging batteries I came across this reply here. Is intended for usb charger/Li-Ion batteries but maybe it could suit your needs too and be adapted. In the output the circuit presented there, you could use some LDO like MCP1825S (or even the MCP1825 with extra information possibilities). Never test the circuit yet, so can not provide any good answer about how long it provides juice to ESP.

---
Tags: esp8266, battery, solar
---


# Question
Title: Unsure how to connect the anode in this circuit
I am making a game of X and O’s and ran out of pins on the Arduino. After searching on the internet I found out about connecting it in a grid connecting all the anodes in columns and the different colours in rows but I don't know how to connect the anodes so it only turns on only one of the LEDs rather than the other 2 in the grid if they are all connected to ground. The wires I am unsure to connect are the orange ones in the diagram below (bottom left corner). Note the Red on the RGBs are not used so don't need to be connected

# Answer
> 1 votes
Firstly, you have made the classic rookie mistake with your circuit regarding your LED current limiting resistors. You have one per LED group instead of one per LED within a group. The arrangement you have at the moment means that *at best* some LEDs will be dim or not light at all, and *at worst* will result in LEDs burning out.

There should be a resistor in every red, green and blue wire in your diagram.

As for what to do with the three orange wires (once you have re-arranged the resistors) they connect to three spare IO pins on the Arduino - you then turn each column on or off as you need - only one column is on at a time. If you need more than 20mA for a column (which is highly likely with up to 9 LEDs on at a time) then those lines should be connected to either +5V or GND (depending on if you are common anode or common cathode) via transistors and the transistors should be switched by the IO pins.

---
Tags: arduino-uno, wires, rgb-led
---