# Question
Title: Since double and float represent the same data type (usually), which is preferable?
It looks like on ATMega based boards, `float` and `double` are equivalent 32-bit (4-byte) data types.

However, on the Arduino Due, `doubles` are 64-bit (8-byte) where `floats` are 32-bit (4-byte), same as the ATMega boards.

I also saw one source on avr-gcc that listed `double` as non-standard.

So, when writing code for ATMega based boards are `floats` preferable to using `doubles`, since that would make the code equivalent for Due boards? Or are `doubles` preferable for any reason?

# Answer
> 2 votes
See avr-gcc

> Deviations from the Standard
>
> **double**
>
> double is only 32 bits wide and implemented in the same way as float

---

> when writing code for ATMega based boards ...

They are the same, therefore.

---

*(Edited to add)*

> When writing code, is it then preferable to using one over the other?

I don't really understand your question. You asked about writing code for the ATMega based boards. Do you really mean, if you are writing code for the Due? The quick answer would be, on the Due, double takes twice the RAM, however it is over twice as precise - around 7.2 decimal digits for float compared to 15.9 for double. (I'm not sure about the speed, probably double would be slower, unless it is implemented in floating-point hardware - however I cannot see any reference to that on the AT91SAM3X8E datasheet).

See: https://en.wikipedia.org/wiki/Floating\_point

If you want more precision (however slower and taking more RAM) then you could use `double` \- which won't make any difference on the ATmega based boards, but will on the Due.

---

As Edgar Bonet said:

> I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect.

That makes quite a bit of sense.

---

I warn you though that "preferable" is subjective. It is close to asking "what is best"? To which the reply is: "best for what?"

# Answer
> 1 votes
Neither are preferable.

Unless your microcontroller has a hardware floating point unit using float or double results in huge overheads for your program.

So instead use integer mathematics whenever possible.

Instead of working in Volts, work in millivolts, for example.

However, if your MCU does have an FPU, and some modern more powerful ones do, then you should use the size of float or double that is native to the FPU. If it is a 32 bit FPU then use float. If it is a 64 bit FPU then you can use double.

---
Tags: programming, arduino-ide, avr, data-type, avr-gcc
---


title: Arduino Infinity Loop

text:
# Question
Title: Arduino Infinity Loop
I'm new to this Arduino programming. So I want to ask about my current project. My lecturer told me to make a temperature sensor using an LM35, where a green LED will light up when below some certain temperature that I set. The same goes for yellow and red LEDs for medium, and high temperatures. The tricky part here is that I need to make sure my buzzer (piezo) is on forever if it reaches the high temperature, until I press a button to reset it.

This is my coding so far:

```
const int greenLed = 3;
const int redLed = 4;
const int yellowLed = 5;
float tempC;
int reading;
int tempPin = 0;
int speakerOut = 11;
const int buttonPin = 2;
int buttonState = 0;
long duration = 10000;
int tempo = 0;

void setup() {
// initialize digital pin 13 as an output.
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(2, INPUT);
pinMode(11, OUTPUT);
analogReference(INTERNAL);
Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {
buttonState = digitalRead(buttonPin);
reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.println(tempC);
delay(500);

if (tempC < 30.00) {
//Serial.println("Temp LOW");
digitalWrite(3, HIGH);
delay(10);
}else {
digitalWrite(3,LOW);
delay(10);

}

if (31.00 < tempC < 33){
//Serial.println("Temp MED");
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(50);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(50);

}else {
digitalWrite(4,LOW);
digitalWrite(5,LOW);

}

if(tempC >= 34){
**WHAT SHOULD I FILL UP HERE TO MAKE SURE MY PIEZO BUZZER ON FOREVER**
}
if(buttonState = 1);{
digitalWrite(11, LOW);
}

```

}

Any help would be great. Or if you have a better idea on how to do this, I'm gonna love it.

# Answer
You can use the toneAC library, which allows even better handling of piezo speakers then the standard "tone"-functions.

> **Features:** Nearly twice the volume (because it uses two out of phase pins in push/pull fashion) Higher quality (less clicking) Capability of producing higher frequencies (even if running at a lower clock speed) Nearly 1.5k smaller compiled code Bug fixes (standard tone library can generate some odd and unpredictable results) Can set not only the frequency but also the sound volume Less stress on the speaker so it will last longer and sound better

With the library you can do something like:

```
int freq = 1000
int vol = 10
int length = 0
boolean background = true

toneAC(freq, vol, length, background);

```

The tone now will play forever in the background, until you stop it with:

```
toneAC(0);

```
> 5 votes

# Answer
1. The answer is simple add

```
digitalWrite(speakerOut,HIGH);

```
2. Common mistake made by beginners is to use assign operator instead of compare operator

```
if(buttonState=1)

```

should actually be

```
if(buttonState==1)

```
3. Never pull that pin LOW

```
if(buttonState = 1);{
digitalWrite(11, LOW);
}

```

is wrong use the below code

```
if(buttonState == 1){
    digitalWrite(11, LOW);
}

```

Don't forget to connect the button to buttonPin or you will get random HIGH or LOW from that pin since its floating

Hope this helps.
> 0 votes

---
Tags: programming
---


title: Need help debugging my Binary Clock

text:
# Question
Title: Need help debugging my Binary Clock
I have tried everything but I can't get my binary clock to display correctly. The diagram and code are here: Binary Clock | Electronics Lab.

The hardware is based off this (it also explains the process that my program is trying to do): DIY: Binary Clock with Arduino. The problems lie in a, probably, simple error as my variable `tempTime`, which is used to convert the individual digits to their binary equivalent, does not change when I tell it to. All this occurs in the display function. (Sorry, I'm new Here and only a high school student)

While debugging it I realized that the only problem is the variable `tempTime` \- the hardware and other functions work as they were intended. Can anyone help? (Sorry if this is not very well documented).

```
    int digitPins[4][4] = {{13,6,-1,-1},{12,7,3,1},{11,8,4,-1},{10,9,5,2}};
int time[4] = {0,0,0,0};
int steps[4]={1,2,4,8};
int tempTime = 0;
void setup(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    pinMode(digitPins[x][y],OUTPUT);
    }
  }
    Serial.begin(9600);
    convertHour(12);
    convertMinute(57);
    Serial.println("The time is:");

  for(int z = 0; z < 4; z++){
    if(z == 2){
    Serial.print(":");
    }
  Serial.print(time[z]);
  }
  display();
}
void loop(){

}
void display(){
  int displayer[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
/*
0 - Hour
1 - Hour
2 - Minute
3 - Minute
4 - Hour(Total)
5 - Minute(Total)
*/

  int counter1 = 0;
  for(int i = 0; i < 4; i++){ //Loop for the individual digits
    tempTime = time[i];
    if(tempTime >= 10){
    tempTime = tempTime % 10;
    }
    Serial.print("\nBegining new iteration i = ");
    Serial.print("\nStarting with digit: ");
    Serial.print(tempTime);
    Serial.print(i);
    Serial.println("");
    for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
      if(time[i]/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
        Serial.print("\n");
        Serial.print(time[i]);
        Serial.print("/");
        Serial.print(steps[j]);
        Serial.print(" = ");
        Serial.print(time[i]/steps[j]);
        tempTime =tempTime - (time[i]*steps[j]);
        displayer[counter1] = digitPins[i][j];
        Serial.print("\nAdded: ");
        Serial.print(digitPins[i][j]);
        counter1++;
      }
    }

  }
  clear();
  for(int a = 0; a < 13; a++){
  digitalWrite(displayer[a],HIGH);
  }
}
void clear(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    digitalWrite(digitPins[x][y],LOW);
    }
  }
}
  void convertHour(int value){
    int digits[] = {0,0};
    if(value >= 10){
        debug("Bigger than 10");
        if(value >= 20){
            digits[0] = 2;
        }else{
            digits[0] = 1;
        }
    }
    digits[1] = value - (digits[0] * 10);
    //String hour = digits[0]+""+digits[1];
    //Serial.print(digits[0]);
    //Serial.print(digits[1]);
    time[0] = digits[0];
    time[1] = digits[1];
  }
void convertMinute(int value){
  int digits[2] = {0,0};
  int val = value;
  if(value >= 10){
    digits[0] = val/10;
  }
  digits[1] = value - (digits[0] * 10);
  Serial.print("\n");
  Serial.print(digits[0]);
  Serial.print(digits[1]);
  time[2] = digits[0];
  time[3] = digits[1];
}
  void debug(String value){
    boolean de = true;
    if(de){
    Serial.println(value);
    }
  }

```

# Answer
> 0 votes
In your “Loop to determin the arrangement”, you are erroneously using `time[i]` in several places where you mean `tempTime`. Also, to update `tempTime` you only have to subtract `steps[j]`. With these fixes, your loop becomes:

```
for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
  if(tempTime/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
    Serial.print("\n");
    Serial.print(tempTime);
    Serial.print("/");
    Serial.print(steps[j]);
    Serial.print(" = ");
    Serial.print(tempTime/steps[j]);
    tempTime = tempTime - steps[j];
    displayer[counter1] = digitPins[i][j];
    Serial.print("\r\nAdded: ");
    Serial.print(digitPins[i][j]);
    counter1++;
  }
}

```

Now, if you learn a little bit about how binary numbers work, and about the binary operators in C and C++, you can rewrite your loop in a simpler form:

```
for (int j = 3; j >= 0; j--) {
  int weight = 1 << j;      // 2 raised to the power j
  if (tempTime & weight) {  // if bit j of tempTime is set
    displayer[counter1++] = digitPins[i][j];
    Serial.print("Added bit ");
    Serial.print(j);
    Serial.print(", weight ");
    Serial.print(weight);
    Serial.print(", output ");
    Serial.println(digitPins[i][j]);
  }
}

```

As a side note, it is considered good practice to print a new line at the *end* of each string you print (using `println()`), rather than at the beginning.

**Edit**: As your `display()` function is way too complex for what it does, I did not resist the temptation to simplify it:

```
void display() {
  for (int i = 0; i < 4; i++)
    for (int j = 0; j < 4 && digitPins[i][j] >= 0; j++)
      digitalWrite(digitPins[i][j], time[i] & (1<<j));
}

```

---
Tags: c++, led
---


title: Arduino Hardware Issue

text:
# Question
Title: Arduino Hardware Issue
I have two Arduino Uno R3 boards and both of them now seem to have an issue. There's a micro sized 8 Pin chip near the dc power port. This seems to get incredibly hot (i managed to get a blister from touching it) and the "L" Led seems to stay dimly lit even when the reset button is pressed.

The Arduino Uno was working fine during operation and only started giving me this problem recently, i cant seem to find any visible short or loose terminal on the board.

I can see that the reset function is being used as my LCD does reset. Would anyone have a reason for this mysterious issue?

# Answer
There are two issues here:

* The "L" LED lighting. On the R3 Uno this is driven by an op-amp and if pin 13 is "floating" the op-amp may, or may not, turn the LED on. So this is normal.
* The 8-pin chip near the power plug getting very hot. This is definitely not normal. You must be consuming a lot of current to do that. You could try measuring it. A Uno running an "empty" sketch should be consuming around 50 mA. Note that this chip is the op-amp mentioned in my first point. Possibly you have damaged it. Did you connect an LED (or motor) or similar to pin D13? If so, what current-limiting precautions did you take?

---

* Try running an empty sketch (or the Blink sketch) with no hardware connected to the board, to see if it still happens.
* Try measuring the power consumption, if possible, with a meter measuring the input through the 5V pin, if you have a 5V power supply you could use for this.
* Are these genuine boards, or cheap clones from eBay?
> 1 votes

---
Tags: hardware
---


title: Another traffic light project

text:
# Question
Title: Another traffic light project
I have a school project, where I'm going to make a traffic light system on a pls. I want to try it out on an Arduino first, just to get the hang of it.

To make it a little bit more advanced than I have found on the internet, I want to make the lights go in "emergency mode" if the green lights in both directions are on at the same time. It will then go into a yellow blink.

My idea is something like this:

```
// Yellow blinking if fault in the system or operator activates it
int killState = digitalRead(Kill);
int resState = digitalRead(Res);
if (killState == HIGH /*|| greenlights in both directions */) {
 while (resState == LOW;) { // Yellow blink as long as system is not reset
  BLINK();
 }
}

```

I guess I need a variable or two that tells what state the lights are in, but I'm stuck. Any good solutions out there?

Another thing is the reset button. I haven't put much effort in it, but I want it to go into the starting point.

The link to the complete script can be found here.

# Answer
For starters, take a close look at this line:

```
while (resState == LOW;)

```

That is not the correct syntax. But the real issue is how is this while loop terminated? The value is never set again?

Cheers!
> 1 votes

# Answer
You could do something simple to test if both red and green are on, eg.

```
if (digitalRead (RED_PIN) == HIGH && digitalRead (GREEN_PIN) == HIGH)
  {
  digitalWrite (RED_PIN, LOW);  // turn off red
  digitalWrite (GREEN_PIN, LOW);  // turn off green
  while (true)
    {
    digitalWrite (YELLOW_PIN, HIGH);
    delay (500);
    digitalWrite (YELLOW_PIN, LOW);
    delay (500);
    }  // end of while
  }  // end of it

```

---

If you have other questions please post your code and not a snippet \- however I suggest you try to get further on your own. This is obviously an exercise, and the more you try to work it out yourself the more you will learn.
> 1 votes

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


title: Double ## in macros

text:
# Question
Title: Double ## in macros
I was looking at some macro use in an Arduino code. I believe what this macro does is it expands into a state that basically sets a pin to either input or output, but I'm a little confused about everything going on in this macro.

I do understand the point behind the do{...} while(0), but I'm sure what the ## are accomplishing. Also, what if anything do the underscores before DDR and PIN do? I would very appreciative of a simple clarification. Thank you!

```
#define MASK(PIN)  (1 << PIN)

/// set pin as input
#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)
/// set pin as output
#define _SET_OUTPUT(IO) do {DIO ##  IO ## _DDR |=  MASK(DIO ## IO ## _PIN); } while (0)

```

# Answer
> 7 votes
`##` is the concatenation operator in macros. It joins two macros or pieces of text together when expanded.

```
#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)

_SET_INPUT(3);

```

woukd expand to:

```
do {DIO3_DDR &= ~MASK(DIO3_PIN); } while (0);

```

You can read more about how it works here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

---
Tags: programming, pins, sketch
---


# Question
Title: Pass class's public function as an argument to external command
I am trying to write a library for encoders.

main.ino:

```
#include <./Encoders.h>

Encoders encoders();

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

void loop(){
    Serial.print("");
}

```

Encoders.h:

```
#ifndef Encoders_h
#define Encoders_h

#include "Arduino.h"

class Encoders{
    public:
        Encoders();
        void EncodersSetup();
        long RightCount;
        long LeftCount;
        void R_A_RISE();
        void R_A_FALL();
        void R_B_RISE();
        void R_B_FALL();
        void L_A_RISE();
        void L_A_FALL();
        void L_B_RISE();
        void L_B_FALL();
    private:
        short R_A_SIG, R_B_SIG, L_A_SIG, L_B_SIG;
};

#endif

```

Encoders.cpp

```
#include "Arduino.h"
#include "Encoders.h"

long RightCount;
long LeftCount;
long R_A_SIG, R_B_SIG, L_A_SIG, L_B_SIG;

Encoders::Encoders(){
    attachInterrupt(0, R_A_RISE, RISING);
    attachInterrupt(1, R_B_RISE, RISING);
    attachInterrupt(2, L_A_RISE, RISING);
    attachInterrupt(3, L_B_RISE, RISING);
    R_A_RISE();
}

void Encoders::R_A_RISE(){
    detachInterrupt(0);
    R_A_SIG = 1;
    if(R_B_SIG == 0){
        RightCount++;
    }
    if(R_B_SIG == 1){
        RightCount--;
    }
    attachInterrupt(0, R_A_FALL, FALLING);
}
void Encoders::R_A_FALL(){
    detachInterrupt(0);
    R_A_SIG = 0;
    if(R_B_SIG == 1){
        RightCount++;
    }
    if(R_B_SIG == 0){
        RightCount--;
    }
    attachInterrupt(0, R_A_RISE, RISING);
}
void Encoders::R_B_RISE(){
    detachInterrupt(1);
    R_B_SIG = 1;
    if(R_A_SIG == 1){
        RightCount++;
    }
    if(R_A_SIG == 0){
        RightCount--;
    }
    attachInterrupt(1, R_B_FALL, FALLING);
}
void Encoders::R_B_FALL(){
    detachInterrupt(1);
    R_B_SIG = 0;
    if(R_A_SIG == 0){
        RightCount++;
    }
    if(R_A_SIG == 1){
        RightCount--;
    }
    attachInterrupt(1, R_B_RISE, RISING);
}
void Encoders::L_A_RISE(){
    detachInterrupt(2);
    L_A_SIG = 1;
    if(L_B_SIG == 0){
        LeftCount++;
    }
    if(L_B_SIG == 1){
        LeftCount--;
    }
    attachInterrupt(2, L_A_FALL, FALLING);
}
void Encoders::L_A_FALL(){
    detachInterrupt(2);
    L_A_SIG = 0;
    if(L_B_SIG == 1){
        LeftCount++;
        }
    if(L_B_SIG == 0){
        LeftCount--;
        }
    attachInterrupt(2, L_A_RISE, RISING);
}
void Encoders::L_B_RISE(){
    detachInterrupt(3);
    L_B_SIG = 1;
    if(L_A_SIG == 1){
        LeftCount++;
    }
    if(L_A_SIG == 0){
        LeftCount--;
    }
    attachInterrupt(3, L_B_FALL, FALLING);
}
void Encoders::L_B_FALL(){
    detachInterrupt(3);
    L_B_SIG = 0;
    if(L_A_SIG == 0){
        LeftCount++;
    }
    if(L_A_SIG == 1){
        LeftCount--;
    }
    attachInterrupt(3, L_B_RISE, RISING);
}

```

When I try to compile this, I get errors like this:

```
C:/Users/marcel/Documents/dev/Arduino/encodeurs/Encoders.cpp:10:38: error: cannot convert 'Encoders::R_B_RISE' from type 'void (Encoders::)()' to type 'void (*)()'

```

I tried answers on other threads. Most said to make the functions passed to `attachInterrupt()` `static`. That threw different errors:

```
C:/Users/marcel/Documents/dev/Arduino/encodeurs/Encoders.cpp:16:33: error: cannot declare member function 'void Encoders::R_A_RISE()' to have static linkage [-fpermissive]

```

I also tried this:

```
attachInterrupt(0, &Encoders::R_A_RISE, this, RISING);

```

with no success.

The Arduino in question is a Mega but I doubt that matters.

# Edit: Per Nick Gammon's answer, I now have this.

MotorEncoderMaster.ino

```
#include </home/marcel/dev/Arduino/encoders/MotorEncoderMaster/Encoders.h>
Encoders * Encoders::instances [2] = { NULL, NULL };

// instances of our class
Encoders right;
Encoders left;

void setup (){
    right.begin (2);   // pin D2
    left.begin (3);   // pin D3
}  // end of setup

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

```

Encoders.h:

```
class Encoders{
    volatile bool switchChanged;

    static Encoders * instances [2];

    static void switchPressedExt0(){
        if(Encoders::instances [0] != NULL){
            Encoders::instances [0]->switchPressed();
        }
    }

    static void switchPressedExt1 (){
        if (Encoders::instances [1] != NULL){
            Encoders::instances [1]->switchPressed();
        }
    }

    public:
        void begin (const int whichPin){
            pinMode (whichPin, INPUT_PULLUP);
            switch (whichPin){
                case 2:
                    attachInterrupt(0, switchPressedExt0, CHANGE);
                    instances [0] = this;
                    break;

                case 3:
                    attachInterrupt(1, switchPressedExt1, CHANGE);
                    instances [1] = this;
                    break;

            }
        }

        void switchPressed(){
            switchChanged = true;
        }

};

```

When I try to compile this, I get :

```
In file included from MotorEncoderMaster.ino:1:0:
/home/marcel/dev/Arduino/encoders/Encoders.h: In static member function ‘static void Encoders::switchPressedExt0()’:
/home/marcel/dev/Arduino/encoders/Encoders.h:7:34: error: ‘NULL’ was not declared in this scope
    if(Encoders::instances [0] != NULL){
                                  ^
/home/marcel/dev/Arduino/encoders/Encoders.h: In static member function ‘static void Encoders::switchPressedExt1()’:
/home/marcel/dev/Arduino/encoders/Encoders.h:13:35: error: ‘NULL’ was not declared in this scope
    if (Encoders::instances [1] != NULL){
                                   ^
/home/marcel/dev/Arduino/encoders/Encoders.h: In member function ‘void Encoders::begin(int)’:
/home/marcel/dev/Arduino/encoders/Encoders.h:21:24: error: ‘INPUT_PULLUP’ was not declared in this scope
     pinMode (whichPin, INPUT_PULLUP);
                        ^
/home/marcel/dev/Arduino/encoders/Encoders.h:21:36: error: ‘pinMode’ was not declared in this scope
     pinMode (whichPin, INPUT_PULLUP);
                                    ^
/home/marcel/dev/Arduino/encoders/Encoders.h:24:45: error: ‘CHANGE’ was not declared in this scope
       attachInterrupt(0, switchPressedExt0, CHANGE);
                                             ^
/home/marcel/dev/Arduino/encoders/Encoders.h:24:51: error: ‘attachInterrupt’ was not declared in this scope
       attachInterrupt(0, switchPressedExt0, CHANGE);
                                                   ^

```

# Answer
# Interrupt Service Routine (ISR) outside a class

Let's consider a simple use of interrupts:

```
volatile bool switchChanged;

void switchPressed ()
  {
  switchChanged = true;
  }  // end of switchPressed

void setup ()
  {
  pinMode (2, INPUT_PULLUP);
  attachInterrupt (0, switchPressed, CHANGE);
  }  // end of setup

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

```

That compiles fine.

---

# ISR inside a class as a class function (method)

Now let's imagine we want to put the interrupt handling into a class for our convenience.

```
class myClass
  {
  volatile bool switchChanged;

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);   // <--- line 10
    }  // end of myClass::begin

  void switchPressed ()
    {
    switchChanged = true;
    }  // end of myClass::switchPressed

  };  // end of class myClass

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

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

```

That does **not** compile:

```
ISR_in_class_test.ino: In member function ‘void myClass::begin()’:
ISR_in_class_test:10: error: argument of type ‘void (myClass::)()’ does not match ‘void (*)()’

```

What is going on here?

ISRs have to be static functions, taking no arguments. However (non-static) class functions have an implied `this->` pointer which points to the particular *instance* of the class.

For example, if we have two instances:

```
myClass foo;
myClass bar;

```

If we call foo.begin() then `this->` points to "foo", and if we call bar.begin then `this->` points to "bar".

However an ISR, when fired by the processor, cannot know whether `this->` is "foo" or "bar" or something else. Thus the compiler cannot compile that line.

---

# ISR inside a class as a static class function

We can try to work around this by making the class function **static**. Doing that means that the function is not tied to any particular instance, and thus the attachInterrupt line will compile.

```
class myClass
  {
  volatile bool switchChanged;   // <--- line 3

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);
    }  // end of myClass::begin

  static void switchPressed ()
    {
    switchChanged = true;   // <--- line 15
    }  // end of myClass::switchPressed

  };  // end of class myClass

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

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

```

However now we have a different problem:

```
ISR_in_class_test.ino: In static member function ‘static void myClass::switchPressed()’:
ISR_in_class_test:3: error: invalid use of member ‘myClass::switchChanged’ in static member function
ISR_in_class_test:15: error: from this location

```

A non-static class variable cannot be called from a static class function. Why? Because the compiler doesn't know *which* variable you want. Is it `foo.switchChanged` or `bar.switchChanged`?

---

# ISR inside a class as a static class function with static variables

To make the static function work, it can only access static variables. So we can make switchChanged static. Plus we need to define an instance of this static variable.

```
class myClass
  {
  static volatile bool switchChanged;  // declare

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);
    }  // end of myClass::begin

  static void switchPressed ()
    {
    switchChanged = true;
    }  // end of myClass::switchPressed

  };  // end of class myClass

volatile bool myClass::switchChanged;  // define

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

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

```

Now the class compiles. However we have thrown away most of the advantages of having a class in the first place, as we are forced to use a static function, and that static function can only access static variables.

---

# Glue routines

To work around this problem we can write short "glue" routines. These are functions that interface between an ISR and an **instance** of a class.

```
class myClass
  {
  volatile bool switchChanged;

  static myClass * instances [2];

  static void switchPressedExt0 ()
    {
    if (myClass::instances [0] != NULL)
      myClass::instances [0]->switchPressed ();
    }  // end of myClass::switchPressedExt0

  static void switchPressedExt1 ()
    {
    if (myClass::instances [1] != NULL)
      myClass::instances [1]->switchPressed ();
    }  // end of myClass::switchPressedExt1

  public:

  void begin (const byte whichPin)
    {
    pinMode (whichPin, INPUT_PULLUP);
    switch (whichPin)
      {
      case 2:
        attachInterrupt (0, switchPressedExt0, CHANGE);
        instances [0] = this;
        break;

      case 3:
        attachInterrupt (1, switchPressedExt1, CHANGE);
        instances [1] = this;
        break;

      } // end of switch
    }  // end of myClass::begin

  void switchPressed ()
    {
    switchChanged = true;
    }

  };  // end of class myClass

myClass * myClass::instances [2] = { NULL, NULL };

// instances of our class
myClass foo;
myClass bar;

void setup ()
  {
  foo.begin (2);   // pin D2
  bar.begin (3);   // pin D3
  }  // end of setup

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

```

This is a bit fiddly, however what it is doing is remembering in an array which instance of the class is associated with which interrupt. The "glue" routines switchPressedExt0 and switchPressedExt1 call the appropriate instance of the switchPressed function by using the remembered class pointer.

Now the non-static function switchPressed can access non-static class variables.

---

Adapted from my web page Calling an ISR from a class
> 5 votes

---
Tags: library, class, callbacks
---


title: Ambiguity in Software Serial

text:
# Question
Title: Ambiguity in Software Serial
HW: 2 Arduino ProMini 16Mhz, 5V Software serial directly connected using male jumpers on bredboard.

I have creates a software serial port for communication between two arduinos, **Parent** and **child**

as per the documentation http://arduino.cc/en/Reference/SoftwareSerialAvailable

```
mySerial.available()

```

should return the number of bytes available in the buffer. and

```
mySerial.read();

```

should give me the byte or return -1 (255) on error. http://arduino.cc/en/Reference/SoftwareSerialRead

here is my code snippet where i read the values

```
if(child1.available() > 0){
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }

```

the Serial outputs are for debugging, The condition for while is true. we go inside. Now what i receive with child1.read() is the following

```
ParentReceived Something from child 2
255 0 255 1 255 2 255 3 255 4 255 5 255 6 255 7

```

all i see is 255.

what i did: I first suspected the child of sending these data, but i used a TTL to USB converter to directly read the values being sent by the child and they are received correctly as they should be. even if i TAP the serial ports to another TTL to USB converter i get 255 on my arduino Serial monitor and the correct data on the sniffer.

# Answer
I notice that your code only mentions "child1", but the output you've displayed mentions "child 2". I assume that means you're using more than one instance of `SoftwareSerial`.

It's important to note that only one instance can receive data at any given time. You need to call `listen()` on an instance to enable it, which will prevent any other instance from receiving data. (Anything which would have been received by another instance will be discarded.)

See the documentation here: http://www.arduino.cc/en/Reference/SoftwareSerialListen
> 1 votes

# Answer
I would suggest trying this with only one Arduino using Software Serial at first. Try using the receiver board's Hardware Serial to listen, possibly using its Software Serial for the debug output. The Hardware Serial is full duplex - it can talk and listen at the same time. Software Serial is not; only xmit or recv can run at one time, and nothing else on the board runs while it does. That can make synchronizing your two boards difficult if the communication needs to be bi-directional.
> 0 votes

# Answer
The question is - are you "listening" to the port? Per doc SoftwareSerial will discard the data if not in"listening state".

The real question is - when not in listening state how does "available" becomes \> 0 (true) AKA there is data in SoftwareSerial "buffer"? It really looks as if there is no real data in the buffer - character count 1 and up to 254 , the buffer content is 255 == -1 which "available" will evaluate as "true".

It can be verified using code to actually get the buffer character count returned from "available" and not just test for if () validity.

```
if(int count = child1.available())
{
    than print count - how many characters in buffer for real
or

if(child1.available() != -1) to test for real data in buffer.

if(child1.available() > 0){ // anything != 0 will ring true
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){// anything != 0 will ring true
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }

```
> 0 votes

---
Tags: arduino-pro-mini, softwareserial, uart
---


title: Arduino and hard drive

text:
# Question
Title: Arduino and hard drive
So in a laptop you have a CPU and a hard drive. The hard drive feeds data to the CPU and the CPU executes it. In Arduino you flash the CPU and the "hard drive" is built into it. Is it possible to have a hard drive or SD card feed data into the Arduino to be executed and then feed more data in and so on? If it is possible how is it done?

# Answer
> Is it possible to have a harddrive or sd card feed data into the Arduino to be executed and then feed more data in and so on. If it is possible how is it done?

A harddrive would be difficult to connect, but an SD card will work just fine.

You can write a sketch that reads data from an SD card. There is library support for both SD and FAT16/32 file systems.

Another interpretation of your question is; is it possible to load a sketch from an SD card. The answer is yes; there are a number of projects that have done that.

Cheers!
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Trying to read a 93lc46b chip using Arduino
I am trying to read a 93lc46b EEPROM chip using Arduino. I am reusing the code from http://owlsan.blogspot.de/2012/10/accessing-93c4693c46n-serial-eeprom.html, except I have modified it for 93lc46b chip, plus I am using Arduino Uno and not Arduino Mega. The problem I am facing is, I get different set of bytes every time I try to read 93lc46b EEPROM chip. I doubt this might be some garbage data. Can you please explain me what and where exactly I am doing something wrong. The modified code snippet is as follows:

```
#include <avr/io.h>
#include <util/delay.h>

#define CLEAN 0b00000000

#define DDR93LC46B  _SFR_IO8(0x04)
#define PORT93LC46B _SFR_IO8(0x05)
#define PIN93LC46B  _SFR_IO8(0x03)

#define SK 13
#define DO 12
#define DI 11
#define CS 10

#define READ 0x02

#define SET_CS PORT93LC46B |= (1 << CS)
#define CLR_CS PORT93LC46B &= ~(1 << CS)

#define SET_SK {PORT93LC46B |= (1 << SK); _delay_us(0.01);}
#define CLR_SK PORT93LC46B &= ~(1 << SK)

#define SET_DI PORT93LC46B |= (1 << DI)
#define CLR_DI PORT93LC46B &= ~(1 << DI)

class SPI_93LC46B {
  private:
    uint8_t Transfer(uint8_t data) {
      SPDR = data;
      while(!(SPSR & (1 << SPIF))); // Wait for SPI interrupt flag
      return SPDR;                  // Return byte gathered from SPI data register
    }
    void Opcode(uint8_t opcode, uint8_t address) {
      SET_CS;
      SPCR &= ~(1 << SPE);               // SPI disable
     _delay_us(1);
      CLR_SK;
      SET_DI;                            // Send start bit
      SET_SK;
      CLR_SK;
      SPCR |= (1 << SPE);         // SPI enable
      Transfer((opcode << 6) | address); // Transmit byte
    }
  public:
    SPI_93LC46B() {
      SPCR =    CLEAN        // Set SPI control register
         & ~(1 << SPIE)  // SPI interrupt disable
         |  (1 << SPE)   // SPI enable
         & ~(1 << DORD)  // MSB first
         |  (1 << MSTR)  // SPI master device
         & ~(1 << CPOL)  // SPI
         & ~(1 << CPHA)  //  mode 0
         |  (1 << SPR1)  // XX/64 MHz
         & ~(1 << SPR0); //  speed
      SPSR =    CLEAN         // Init SPI status register
         & ~(1 << SPI2X); // SPI double speed
      DDR93LC46B =    CLEAN      // Set up inputs/outputs
             |  (1 << SK)  // Serial clock output
             |  (1 << DI)  // Data input (MOSI) output
             |  (1 << CS)  // Chip select output
             & ~(1 << DO); // Data output (MISO) input
      PORT93LC46B |= (1 << DO); // Data output (MISO) high
      CLR_DI;
      CLR_CS;
      CLR_SK;
     _delay_us(1);
    }
    ~SPI_93LC46B() {
      //
    }
    uint16_t Read(uint8_t address) {
      uint16_t data = 0;
      Opcode(READ, address);
      CLR_DI;
      SET_SK;
      CLR_SK;
      SPCR |=  (1 << CPHA);
      data = Transfer(0);
      data = (data << 8) | (Transfer(0));
     _delay_us(1);
      CLR_CS;
      CLR_DI;
      SPCR &= ~(1 << CPHA);
      return data;
   }
};

void setup(void) {
  Serial.begin(115200);
  _delay_ms(100);
  Serial.println("EEPROM writing/reading");
}

void loop(void) {
  Serial.println("new round");
  SPI_93LC46B _93LC46B;
  int i;
  uint16_t data;
  for(i = 0; i < 64; i++) {
    data = _93LC46B.Read(i);
    _delay_ms(50);
    Serial.print(data, HEX);
    Serial.print(" ");
    if((i + 1) % 8 == 0)
      Serial.println();
  }
  _delay_ms(10000);
}

```

# Answer
> 0 votes
This code is over complicated and has a lot of errors. Let us start with the obvious. Look closely at this section. Do you see the error(s)?

```
#define SK 13
#define DO 12
#define DI 11
#define CS 10

#define READ 0x02

#define SET_CS PORT93LC46B |= (1 << CS)
#define CLR_CS PORT93LC46B &= ~(1 << CS)

#define SET_SK {PORT93LC46B |= (1 << SK); _delay_us(0.01);}
#define CLR_SK PORT93LC46B &= ~(1 << SK)

#define SET_DI PORT93LC46B |= (1 << DI)
#define CLR_DI PORT93LC46B &= ~(1 << DI)

```

The symbols SK, D0, DI, CS seem to be pin numbers but look how they are used in the SET\_XX and CLR\_XX macros. That is very wrong. They should be the bit numbers in the PORT register instead.

There is more. How about this?

```
_delay_us(0.01);

```

What is the intention? \_delay\_ns(10)??? In any case yet another error.

Cheers!

---
Tags: arduino-uno, eeprom
---


title: Raspberry Pi Arduino Installer broken

text:
# Question
Title: Raspberry Pi Arduino Installer broken
I am tring to use ShorTie8's new arduino ARM installer on my RPI B+ by copying this into my terminal:

> cd
>
> sudo apt-get update -y && sudo apt-get dist-upgrade -y
>
> wget https://raw.githubusercontent.com/ShorTie8/Arduino\_IDE/master/Arduino\_IDE\_builder.bash
>
> chmod +x Arduino\_IDE\_builder.bash
>
> sudo ./Arduino\_IDE\_builder.bash
>
> sudo Arduino/build/linux/work/./arduino
>
> sudo Arduino/build/linux/work/./install.sh
>
> sudo apt-get install -y mercurial subversion build-essential gperf bison ant texinfo zip automake flex libusb-dev libusb-1.0-0-dev libtinfo-dev pkg-config libwxbase3.0-dev libtools

But Getting The following Error at sudo ./Arduino\_IDE\_builder.bash

> * echo -e '\n\nConfiguration values\n\n'
>
> Configuration values
>
> * Stable=1.6.7
> * Update\_me=yes
> * Silence\_is\_Golden=yes
> * echo -e '\n\nSystem check\n\n'
>
> System check
>
> ++ date \+ start\_time='Sat 13 Feb 11:12:37 GMT 2016' ++ pwd \+ Start\_Directory=/home/pi ++ pwd \+ Working\_Directory=/home/pi/Arduino/build \+ echo -e '\n\nChecking for root .. \n'
>
> Checking for root ..
>
> ++ id -u \+ '\[' 0 '!=' 0 '\]' \+ echo 'Yuppers .. :)~' Yuppers .. :)~ \+ \[\[ yes == \y\e\s \]\] \+ echo -e '\n\nChecking to see if I'\\''m update\n'
>
> Checking to see if I'm update
>
> * git remote update fatal: Not a git repository (or any of the parent directories): .git

# Answer
Instead of manually downloading a file from the github repository, check out the repository properly with `git clone 《repository》`
> 1 votes

---
Tags: arduino-ide, raspberrypi
---


# Question
Title: Arduino Nano no output on any controllable pins except for RX and TX pins
I have 2 Arduino Nanos which don't output anything on any controllable pins except for RX and TX pins. I used an LED which I have tested works on the 3.3v/GND and 5.0v/GND. When I try to control the RX and TX pins (1 and 2) the LED lights up on the board and the external LED I am using to test. I am using the example "Blink" program to test it, and I've tried it on both nanos. I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything. Why isn't it working?

```
    /*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
 */

// Pin 13 has an LED connected on most Arduino boards.
// Pin 11 has the LED on Teensy 2.0
// Pin 6  has the LED on Teensy++ 2.0
// Pin 13 has the LED on Teensy 3.0
// give it a name:
int led = 26;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

```

# Answer
> 3 votes
> I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything.
>
> No, the LED doesn't need a resistor ...
>
> because I tested it with the 5v and 3.3v therefore higher voltages doesn't blow it up

---

Sounds to me like you have damaged your output pins. Read The care and feeding of LEDs by Mike Cook.

The LED may briefly light up, but without a resistor you are damaging both the LED and the output pin. It is no surprise then, that afterwards the pins "none output anything".

Without a limiting resistor the output driver on the Arduino is overloaded and may burn out. Whether you have damaged the LED, the pin, or both, is hard to say.

---

*(Edited to add)*

> still doesn't work on pins that I haven't used ...

Can you slow down a bit?

> I've tested pins 26 (serial) ...

There is no pin 26 from the IDE point of view. On the board pin 26 is A7 (analog input 7) which **cannot be used for digital input/output**.

Please specify exactly what pin you tried (just choose one) and stick to the Arduino number (printed on the board, eg. D05) and then show the code you used to access that pin.

---

> According to this ... the analogue pins can be used just the same as digital pins

That page shows a Uno. You have a Nano.

See Arduino Nano - Arduino.cc. On that page:

> Analog pins 6 and 7 cannot be used as digital pins.

# Answer
> 1 votes
No, the LED doesn't need a resistor ...

That is correct, but the processor I/O - output pin - does. Check the schematic to see how RX /TX LEDs are connected.

---
Tags: led, arduino-nano, digital
---


# Question
Title: Connecting arduino to an existing circuit
I have a little clock with a button on it that i need to push four times every second hour. I am trying to get the arduino micro to do it for me.

I am trying to figure out how to connect the arduino to trigger it. The clock is operated by a CR2 (3.0V) cell battery. Is there a way to do this without a transistor? If not what do i need? How can i find out how much amp my circuit requires?

The red arrow is pointing on the cable i think triggers the clock, and i think the black arrow is pointing on the cable that is the clock gnd.

(edit: I have found similar questions explaining the process with transistor, but not without..)

# Answer
> 0 votes
You might try attaching an Arduino IO through a resistor to pin 4 (where your red arrow points), and Arduino ground to pin 1 (where your black arrow points). Because the clock is battery-operated, you can connect its ground to the Arduino's ground without problem.

Before attaching the Arduino, use your DVM to measure the voltage between pins 4 and 1, with the switch open and with the switch closed. In following, I'll suppose you have measured 3V when the switch is open and 0V when it's closed. This would indicate that the clock's circuit pulls or drives pin 4 high when the switch is open. In initial experiments, I'd start with a 1KΩ or so resistor (eg, any resistor between 500Ω and 2000Ω) in series with an ammeter and the Arduino IO. If you measure at most a few microamps of current in both the “switch open” and “switch closed” cases (see below) then the circuit should function ok with the resistor in place (since there will be only a tiny voltage drop across it). \[If, on the other hand, you measure several milliamps of current in either case, then my ideas about the clock circuit might not apply; in which case you might need an optoisolator or relay.\]

To represent switch operation, put the Arduino IO into INPUT mode to represent an open switch, and into OUTPUT LOW to represent a closed switch. For example, in `setup()` say

```
pinMode(ClockPin, INPUT);  // Also does digitalWrite(ClockPin, LOW);

```

and in your `loop()` say stuff like

```
if (TheTimeHasCome) {
   for (int k=0; k<4; ++k) {
      pinMode(ClockPin, OUTPUT);  // Presses the button
      delay(50);                  // Holds the button
      pinMode(ClockPin, INPUT);   // Releases the button
      delay(50);                  // Wait between buttons
   }

```

The comment `// Also does digitalWrite(ClockPin, LOW);` is a reminder that `pinMode(ClockPin, INPUT);` has two actions: it sets ClockPin to be an input instead of an output, and takes the corresponding PORTx bit low (ie, resets a bit in PORTB, PORTC, PORTD, or whatever). If we had said `pinMode(ClockPin, INPUT_PULLUP);`, then the corresponding PORTx bit would have been set high, and the pin would be weakly pulled to Vcc, eg +5V. It would be a mistake to send 5V to the clock, as it's likely that would exceed its voltage tolerance.

Since `pinMode(ClockPin, INPUT);` leaves the appropriate PORTx bit low, there is no need to use `digitalWrite()` separately in the sketch. When ClockPin is an input, its high impedance allows the clock to pull pin 4 high; when ClockPin is an output, its 0 level connects pin 4 to pin 1.

# Answer
> 0 votes
Yes, This can be achieved without a transistor.

As the circuits would be on isolated power supplies: Arduino circuit on one and the clock on another, you can use a Solid State Relay.

Use the relay with your Arduino (5v or 3.3v) and wire the relay contacts parallel to the clock switch. This will isolate any power issues as clock will be powered with its own power and Arduino will be powered with its own.

You can program Arduino with proper delays to actuate the relay accordingly.

Hope this helps.

# Answer
> 0 votes
Connect the Arduino and your clock grounds together. Get a small resistor - no less than 1 kOhm - and connect your VOM (in current mode) in series with the resistor and your Arduino output pin. Set the output pin to LOW and observe Did the clock reset? What was the current on your VOM? If the clock reset and the current was more than 20 mA get a bigger ( 10 kOhms ) resistor and try it again. If the clock reset and your current was less than 20 mA you are done.

And if you really want to isolate the clock from Arduino use low current LED and connect the cathode to the output pin and anode to the clock. Keep the resistor in the circuit.
Than you will also have an indicator of "circuit is active".

---
Tags: arduino-micro
---


title: Error uploading to ATtiny

text:
# Question
Title: Error uploading to ATtiny
I followed Great Scott's video on YouTube for uploading to an ATtiny85. When I tried I got the following error messages:

> Arduino: 1.6.7 (Windows Vista), Board: "ATtiny85 (internal 8 MHz clock)"
>
> Board attiny-master:attiny:attiny85-20 doesn't define a 'build.board' \>preference. Auto-set to: ATTINY\_ATTINY85-20
>
> Board attiny-master:attiny:attiny45-8 doesn't define a 'build.board' \>preference. Auto-set to: ATTINY\_ATTINY45-8
>
> Board attiny-master:attiny:attiny85-8 doesn't define a 'build.board' \>preference. Auto-set to: ATTINY\_ATTINY85-8
>
> Board attiny-master:attiny:attiny44 doesn't define a 'build.board' \>preference. Auto-set to: ATTINY\_ATTINY44

etc. etc. ...

> exec: "-w": executable file not found in %PATH% Error compiling.\`
>
> This report would have more information with "Show verbose output during compilation" enabled in File \> Preferences.

When I unplug my ATtiny85 and restart Arduino, I have no problems uploading, though I get about 8 error messages saying something like:

> Board attiny-master:attiny:attiny84 doesn't define a 'build.board' preference. Auto-set to: ATTINY\_ATTINY84

# Answer
It's likely that a compiler's file name is missing from a command line the IDE is trying to execute. To find out more about what the command looks like (which will let you figure out what name is missing), turn on verbose output during compilation. That is, click File, Preferences in the IDE, then click the box in front of “compilation”. After you find out what's missing, you can then turn off verbose output and fix `platform.txt`, which is the file the IDE looks at to find out what commands to execute when compiling sketches.

To get rid of the warnings about undefined `build.board` values, add lines like the following to the `boards.txt` file in the `tiny/avr/` directory (or whereever you installed it). (Your 1.6 IDE wants `build.board` definitions, which IIRC weren't needed by 1.5 and earlier IDEs.)

```
attiny85-20.build.board=ATTINY_ATTINY85-20

```

Each of the lines you add will contain the Auto-set value, prefaced by a string made up of a board-type and `.build.board=` concatenated together. Add each line just before or after other `.build.`-containing lines.
> 1 votes

---
Tags: avr, avrdude
---


title: Convert UNIX Timestamp

text:
# Question
Title: Convert UNIX Timestamp
I have an UNIX Timestamp in my Arduino Sketch and would like to get the day of the week of this timestamp (1-7).

How can I convert the timestamp to get the day of the week?

# Answer
The simplest solution to that problem is to download the Time library and use the weekday() function:

```
int weekday(time_t t); // the weekday for the given time

```

Cheers!
> 2 votes

---
Tags: time
---


title: Timer/Counter programming Arduino

text:
# Question
Title: Timer/Counter programming Arduino
I'm trying to blink an LED on an ATMega328P (same MCU as Arduino I think..) using the internal timer but I'm stuck since it doesn't seem to light the LED at all....

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

void delay(void);

void delay_long(void);

int main(void) {

  DDRB = 0xFF;                   // port B is configured as output   DDRB : 0b11111111
  DDRB &= ~(1<<PB1);             // pin 1 of port B is configured as input  DDRB : 0b11111101
  PORTB = 0x00;                  // pins of port B are low (output) and with no pull-up resistor (input)
  PORTB |= (1<<PB0)|(1<<PB1);    // pin 0 is high (output) and pin 1 is pulled high (input)    PORTB : 0b00000011

  while(1) {
    PORTB &= ~(1<<PB0);
    delay();
    PORTB |= 1<<PB0;
    delay();
    PORTB = ~(1<<PB0);
    delay_long();
    PORTB = 1<<PB0;
    delay_long();
  }

  return 1;

}

void delay(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

void delay_long(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

```

if I remove the body of the event loop it lights up... so I think I must be missing something in the delay functions...

# Answer
> 1 votes
It seems that the offending line is:

```
while ( (TIFR0 & TOV0) == 0 )

```

`TOV0` by itself equals 0, so the above loop will never end.

You should use:

```
 while ( (TIFR0 & (1<<TOV0)) == 0 )

```

instead.

---
Tags: c, atmega328, timers, avr
---


# Question
Title: How to perform action if two rfid tag UIDs have been detected?
I'm using an rfid-rc522 and I want to print to the serial a string of text if two rfid tags have been read in a given time period.

Essentially this:
1. First tag is read (print to serial: Tag 1 has been read)
2. Wait 2 seconds
3. Second tag is read (print to serial: Tag 2 has been read)
4. Print to serial: Tag 1 and Tag 2 has been read)
5. Bonus: Keep this state - and then when a button is pressed (print to serial: Tag 1 and Tag 2 are finished)

I know how to read the UID and print to the serial if one is read. Thank you so much for your help, it's greatly appreciated.

Here is my code so far:

```
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>
#include <MFRC522.h>

// For the breakout, you can use any 2 or 3 pins
// These pins will also work for the 1.8" TFT shield
#define sclk 4  // SainSmart: SCL
#define mosi 5  // SainSmart: SDA
#define cs   6  // SainSmart: CS
#define dc   7  // SainSmart: RS/DC
#define rst  8  // SainSmart: RES

Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk, rst);

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  Serial.print("Starting cornhole leaderboard...");
  mfrc522.PCD_Init(); // Init MFRC522 card
  Serial.println("Scan PICC to see UID and type...");
  // Use this initializer if you're using a 1.8" TFT
  tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab

  // Use this initializer (uncomment) if you're using a 1.44" TFT
  //tft.initR(INITR_144GREENTAB);   // initialize a ST7735S chip, black tab

  Serial.println("Initialized");

  uint16_t time = millis();
  tft.fillScreen(ST7735_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);

  // large block of text
  tft.fillScreen(ST7735_BLACK);
}

void loop() {

  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    if (mfrc522.uid.uidByte[0] == 0xA4 &&
       mfrc522.uid.uidByte[1] == 0xB8 &&
       mfrc522.uid.uidByte[2] == 0xB8 &&
       mfrc522.uid.uidByte[3] == 0x96) {
          Serial.println("Nate has checked in to the game.");
          tft.fillScreen(ST7735_BLUE);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_YELLOW);
          tft.print("Nate ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);
    }

    if (mfrc522.uid.uidByte[0] == 0x03 &&
       mfrc522.uid.uidByte[1] == 0xFD &&
       mfrc522.uid.uidByte[2] == 0xBC &&
       mfrc522.uid.uidByte[3] == 0x02) {
          Serial.println("Ted has checked in to the game.");
          tft.fillScreen(ST7735_RED);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_CYAN);
          tft.print("Ted ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);

    }

}

```

# Answer
> 1 votes
What you can do is store the current time whenever a card is swiped, and then when another card is swiped check how long it's been since the last card was swiped

first create a couple of variables

```
unsigned long swipedTime;
int tag1 = 0;
int tag2 = 0;
int swipeTimeOut = 10000; // how much time in MS you have to swipe both cards

```

Next we'll jump down to where where you read the cards.

```
      if (mfrc522.uid.uidByte[0] == 0xA4 &&
           mfrc522.uid.uidByte[1] == 0xB8 &&
           mfrc522.uid.uidByte[2] == 0xB8 &&
           mfrc522.uid.uidByte[3] == 0x96) {

               ........

               if (tag2 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }

                tag1 = 1;
                swipedTime = millis();
        }

        if (mfrc522.uid.uidByte[0] == 0x03 &&
           mfrc522.uid.uidByte[1] == 0xFD &&
           mfrc522.uid.uidByte[2] == 0xBC &&
           mfrc522.uid.uidByte[3] == 0x02) {

               ........

               if (tag1 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }
                tag2 = 1;
                swipedTime = millis();

         }

```

You'll also want to come up with a system for resetting `tag1` and `tag2` to 0 or "checking them out".

# Answer
> 0 votes
You could try:

```
byte tag1[] = {0xA4, 0xB8, 0xB8, 0x96};
byte tag1_read = 0;    // flag is set when tag 1 is read
byte tag2[] = {0x3, 0xFD, 0xBC, 0x02};
byte tag2_read = 0;    // flag is set when tag 2 is read

int BUTTON = 3;

void setup(){
    pinMode(BUTTON, INPUT_PULLUP);  //set button as input pulled high
    .... // the rest of your setup()
}

void loop() {

  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    if (tag1_read == 0 && memcmp(mfrc522.uid.uidByte, tag1, 4) == 0){
          Serial.println("Tag 1 has been read.");
          tag1_read = 1;   //tag 1 has been read
          //delay(2000);   //not sure why u need the delay
    }

    if (tag1_read && tag2_read == 0 && memcmp(mfrc522.uid.uidByte, tag2, 4) == 0) {
          Serial.println("Tag 2 has been read.");
          tag2_read = 1;    // tag 2 has been read
          Serial.println("Both tags have been read.");
    }

    if (digitalRead(BUTTON) == LOW && tag1_read && tag2_read){
        Serial.println("Both tags are finished.");
        tag1_read = 0; tag2_read = 0;
    }
}

```

This code assumes the cards must be presented and read in order.

---
Tags: serial, rfid
---


# Question
Title: Simultaneously reading data from multiple serial ports
I have three sensors latched on to three different Arduino devices.

The respective Arduino devices are connected on to an Arduino Mega on Serial1, Serial2 and Serial3.

The data from each device component (i.e., an Arduino with an accompanying sensor) were sent in data packets with different starter byte headers ('$' , '/' & '#' ) accompanying the buffered data from each individual device component onto the Mega on the Tx/Rx lines.

My question here is, how can I simultaneously read out all the data from the different serial ports on the Arduino mega sketch?

# Answer
> My question here is how can I simultaneously read out all the data from the different serial ports on the arduino mega sketch.

As you are using several serial ports data can already be received simultaneously. Each serial software class (Serial1, Serial2, Serial3) has an internal buffer where data is stored until it is read.

You only need to read the data before the internal buffers are filled and there is a risk for over-flow. Check that data is available and read as usual per serial port. Avoid any blocking calls to avoid buffer over-flow.

Cheers!
> 4 votes

# Answer
I had my arduino mega receiving the data from Serial2 and Serial3, by adopting a sketch that was developed by @Majenko in answer to the post Processing Serial data. The sketch below outputs data to the serial monitor. The NEW problem I have now is trying to develop a python sketch that would seperate the data from the buffers into two different csv files, with each csv files representing the data from each of the two sensors.

```
    static char buffer[20];
    int count =0;

    void setup()
   {
    Serial.begin(115200);
    Serial2.begin(115200);
    Serial3.begin(115200);
    delay(50);

    }

    void loop(){

if (Serial.available()){  //Slide the window
   for(count=0; count<10; count++){
      buffer[count] = Serial.read();
      //Add the new character
      buffer[9] = Serial.read();

      //Check the framing window
   if((buffer[0] == '$') && (buffer[9] == 0xAC)){
     //Calculate the checksum
      uint16_t cs = 0;
   for (uint16_t i = 2; i < 8; i++){
    cs += buffer[i];
    }
    //if the checksum matches....
    if(cs == buffer[8]){
      //Send the byte to serial port three
      Serial2.write(buffer, count);
  }
  }

 }
}

 if (Serial2.available()){
    for(count=0; count<10; count++){
      buffer[count] = Serial2.read();
      //Send the byte to serial port three
      Serial.write(buffer, count);
     }
 }

 if (Serial.available()){  //Slide the window
   for(count=11; count<20; count++){
      buffer[count] = Serial.read();
      //Add the new character
      buffer[19] = Serial.read();

      //Check the framing window
   if((buffer[11] == '+') && (buffer[19] == 0xAE)){
     //Calculate the checksum
      uint16_t cs2 = 0;
   for (uint16_t i = 6; i < 18; i++){
    cs2 += buffer[i];
    }
    //if the checksum matches....
    if(cs2 == buffer[18]){
      //Send the byte to serial port three
      Serial3.write(buffer, count);
  }
  }

 }
}

 if (Serial3.available()){
    for(count=11; count<20; count++){
      buffer[count] = Serial3.read();
      //Send the byte to serial port three
      Serial.write(buffer, count);
     }
 }

```

}
> 1 votes

# Answer
The easiest and most overlooked way to read ANY hardware serial ( Serialx) is to utilize Arduino IDE main() function layout and let the serialEventx do the work.

Here is much simplified layout of IDE main () function.

main() { Setup() for(;;) { loop() serialEventx() } }

However using serialEvent requires much different approach to your program flow - the loop() cannot have any logic which would introduce a delay. Your program must process the serialEvent FIRST, loop() processing is secondary.
> 0 votes

---
Tags: serial, sensors, arduino-due, datalogging
---


# Question
Title: Random(min,max) Function only giving ~50 range no matter what the values?
I can't get the min,max range to function properly. Monitoring the serial, only gives out ~50 difference from the min. I then added truerandom.ino to try to fix, but no help.

```
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
//long interval = random(800, 8000); // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
long interval = random(800,8000);
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
Serial.println(interval);
}
}

```

Added truerandom.ino still ~50 range:

```
// TrueRandomSeed.ino
//   This example sketch shows how to provide a truly random seed value to the built in
//   library pseudo random number generator.  This ensures that your sketch will be
//   using a different sequence of random numbers every time it runs.  Unlike the
//   usually suggested randomSeed(analogRead(0)) this method will provide a much more
//   uniform and varied seed value.  For more information about the basic technique used
//   here to produce a random number or if you need more than one such number you can
//   find a library, Entropy from the following web site along with documentation of how
//   the library has been tested to provide TRUE random numbers on a variety of AVR
//   chips and arduino environments.
//
//   https://sites.google.com/site/astudyofentropy/project-definition/
//           timer-jitter-entropy-sources/entropy-library
//
//   Copyright 2014 by Walter Anderson, wandrson01 at gmail dot com
//

#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <util/atomic.h>
// The following addresses a problem in version 1.0.5 and earlier of the Arduino IDE
// that prevents randomSeed from working properly.
//        https://github.com/arduino/Arduino/issues/575
#define randomSeed(s) srandom(s)

volatile uint32_t seed;  // These two variables can be reused in your program after the
volatile int8_t nrot;    // function CreateTrulyRandomSeed()executes in the setup()
                         // function.
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated

void CreateTrulyRandomSeed()
{
  seed = 0;
  nrot = 32; // Must be at least 4, but more increased the uniformity of the produced
             // seeds entropy.

  // The following five lines of code turn on the watch dog timer interrupt to create
  // the seed value
  cli();
  MCUSR = 0;
  _WD_CONTROL_REG |= (1<<_WD_CHANGE_BIT) | (1<<WDE);
  _WD_CONTROL_REG = (1<<WDIE);
  sei();

  while (nrot > 0);  // wait here until seed is created

  // The following five lines turn off the watch dog timer interrupt
  cli();
  MCUSR = 0;
  _WD_CONTROL_REG |= (1<<_WD_CHANGE_BIT) | (0<<WDE);
  _WD_CONTROL_REG = (0<< WDIE);
  sei();
}

ISR(WDT_vect)
{
  nrot--;
  seed = seed << 8;
  seed = seed ^ TCNT1L;
}

void setup()
{
  CreateTrulyRandomSeed();
  randomSeed(seed);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  // The preceeding two function calls will take approximately 0.5 second to execute if
  // nrot is set to 32 ... the rest of your setup code should FOLLOW from here.
}

void loop()
{
  long interval = random(800,8000);
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
Serial.println(interval);
}
}

```

# Answer
I suspect it actually is generating other values and it's your program logic that's at fault.

Here's what I think you meant your program to do:

1. Generate a random interval.
2. Wait until that interval has elapsed.
3. Start again with a new interval.

Here's what's actually happening:

1. Generate a random interval.
2. Check if that interval has elapsed.
3. Whether or not it has elapsed, generate a new random interval anyway.

Note that you're generating a new random interval **every time round `loop()`**. This means your condition just keeps trying new random intervals until one happens (by chance) to be less than the amount of time that's elapsed since the last interval. You're only outputting the interval when that occurs, and evidently it happens on average at least every 50ms.

You can test this theory by outputting `interval` to serial as soon as you've generated it (i.e. before the `if` statement). I think you'll find it will flood the serial monitor with a huge range of values.

Fixing the problem should be pretty easy. Just generate your first `interval` value during `setup()`. After that, only generate a new random `interval` value when the old interval has elapsed (i.e. inside the `if` block). Don't do it every time round the main loop.
> 2 votes

# Answer
I had the same problem (random, milliseconds), and in my case what I needed to make was a toy, able to Blink its eye (LED) in a more human way, with variable intervals, so I used the basic "blink without delay" and tweaked until I got a result I wanted. This is my first post here so I hope I'm doing it correctly. Here is the code that worked for me:

```
const int ledPin =  13;      // the number of the LED pin
unsigned long previousMillis = 0;        // will store last time LED was     updated

 long interval = 4000;           // starting interval at which to blink   (milliseconds)

void setup() {
Serial.begin(9600);
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}

void loop()
{
digitalWrite(ledPin, HIGH);

unsigned long currentMillis = millis();

if(currentMillis - previousMillis >= interval)

{
  // save the last time you blinked the LED
  previousMillis  = currentMillis;
  interval = random((3, 14) * 1000);

Serial.println("Blink");
Serial.println(interval);  // Just so I can confirm if the effect seems natural
digitalWrite(ledPin, LOW);
delay(250);
digitalWrite(ledPin, HIGH);
 }
}

```
> 2 votes

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


# Question
Title: Is the Uno Vin pin protected by the voltage regulator?
I guess it's all in the title. When using Vin as input, does it go through voltage regulator, or must I feed it precisely 5V?

# Answer
If you look at the schematic you'll see Vin is connected to the input of the voltage regulator. Just like the barrel-jack (except for the diode).

So the same input-voltage of 7-12V applies to Vin.
> 5 votes

# Answer
when you connect you regulated 5V at Vin port your 5V output will be lower than 5V as it have to pass through the 5V regulator. The input voltage should range from 7-12V.
> 1 votes

---
Tags: arduino-uno, power, voltage-protection
---


# Question
Title: Is it possible to upload previously compiled binary?
I have a number of sketches that I keep wanting to load into the Arduino but I don't necessarily need to recompile them because I haven't changed anything since the last compile. Since the compile takes a minute or 2 each time, this would save me some waiting.

I can see that the IDE has the option to "Export Compiled Binary", but doesn't seem to have the converse option of Uploading a previously compiled binary. Is there any way to do this?

# Answer
Yes! Its possible that you can upload a previously complied binary, using

AVRDUDE - a command line utility which is actually used to upload binaries, behind the arduino IDE.

You can find AVRDUDE in Arduino folder \> hardware \> tools \> avr \> bin

This some documentation for AVRDUDE http://www.nongnu.org/avrdude/user-manual/avrdude.html

else simplest thing you can do is turn on verbose output during upload and watch for a command in the end with AVRDUDE in it along with the path of hex file, just copy paste & run the same command in CommandLine; your task is accomplished.
> 14 votes

---
Tags: uploading, ide
---


title: Distance sensor

text:
# Question
Title: Distance sensor
I am adding a distance sensor to existing project that uses Arduino due, do I connect the trigger pin and the echo pin of the HC-SR04 ultrasonic sensor directly to Arduino due which uses 3.3V while HC-SR04 ultrasonic sensor uses 5V or do I need to use a voltage divider?

# Answer
As suggested in previous answers, you can directly use a Due output to drive the HC-SR04's Trig pin; according to the HC-SR04 spec sheet, that pin operates at TTL levels. It will see 0 V as a 0-input and will see 3.3 V as a 1-input since it exceeds 2.4 V. Also see 3.3v input to Arduino digital pin in electronics.stackexchange.

However, the Due's inputs are not 5 V tolerant, so you will need to use a voltage divider between the Echo pin and a Due input. See second paragraph of arduino.cc's ArduinoBoardDue article:

> Warning: Unlike most Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board.
> 1 votes

# Answer
Well, it depends on the sensor itself. Some sensors run on both 5V and 3.3V. There's a similar question here on StackExchange: How to connect 5V sensors to 3.3V digital input (Due)?

But, in short, if the sensor can't operate in 3.3V, you'll need a level converter /shifter.
> 0 votes

# Answer
The trigger pin is an input, so you can connect that directly to the Due.

The echo pin will however output 5v. You could use a voltage divider to bring that down to 3.3v or a bit lower.
> 0 votes

---
Tags: arduino-due
---


title: Four Fast PWM outputs, in parallel

text:
# Question
Title: Four Fast PWM outputs, in parallel
I need four Fast PWM signals for four different transistors.

I want to use timers 1+2 (pins 3, 11, 9, 10) so it wouldn't interfere with `delay(...)`.

I tried setting the timers to Fast PWM mode, and applied different OCRnA/OCRnB values, but nothing really worked - at most, I managed to get two good PWM signals, *one from each timer*.

How should I deal with `TCCRnA/TCCRnB, OCRnA/OCRnB` to achieve 4 parallel PWM signals?

My latest attempt:

```
// Timer 1 Fast PWM setup: TOP=0x00FF, Update of OCRx at BOTTOM (0), TOV Flag Set on TOP
pinMode(9, OUTPUT); pinMode(10, OUTPUT);
TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10); // Divisor 64
// Timer 2 Fast PWM setup: TOP=0xFF, Update of OCRx at BOTTOM (0), TOV Flag Set on MAX (0xFF)
pinMode(3, OUTPUT); pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22); // Divisor 64
// ...
int val = 200; // Desired PWM output
OCR1A = val;
OCR1B = val;
OCR2A = val;
OCR2B = val;

```

# Answer
Basically, your question comes down to this:

"How to generate two PWM signals with only one timer."

(Once you've got that figured out, you could set up 6 PWM channels)

Keep in mind that there also are PWM generator IC's, if you don't want to use up all your timers, which can be usefull for other things.

IF you really want to set all outputs to toggle at the same time (based on your code example) why won't you just use one PWM signal, and drive all the 4 devices with the same signal? (Given you're not going to change it) IF you're going to drive motors, why would you need 4 different PWM signals? It's often enough to only use one PWM signal for the right tires/tracks and one PWM signal for the left tires/tracks.

---

**Setting the max**

Since we want to generate different PWM signals from one timer, we can't just make the timer overrun (and generate a pulse or switch polarity at that point). We want to let the timer run to completion over and over, and only change the signal when it reaches a set value.

The datasheet tells us this:

> The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR0A Register. (328P datasheet 15.2.1 Definitions)

**Setting a limit per pin**

We want to set 2 limits on one timer, each timer has an output compare register (OCR), the action will be generated when the timer hits this value.

> The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). (328P datasheet 15.2.2 Registers)

**Extra info on compare**

Below you can read some extra info on the signaling. What actually will happen, depends on how the WGM

> 15.5 Output Compare Unit The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The max and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in some modes of operation (”Modes of Operation” on page 98).

**Fast PWM** The actual settings are different per mode/modus, but for fast PWM we have:

```
Table 15-3. Compare Output Mode, Fast PWM Mode(1)
COM0A1 COM0A0 Description
0      0      Normal port operation, OC0A disconnected.
0      1      WGM02 = 0: Normal Port Operation, OC0A Disconnected.
              WGM02 = 1: Toggle OC0A on Compare Match.
1      0      Clear OC0A on Compare Match, set OC0A at BOTTOM, (non-inverting mode).
1      1      Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

```

The table tells us we need to set COM0A1 and COM0A0 to 1.

```
COM0B1 COM0B0 Description
0      0      Normal port operation, OC0B disconnected.
0      1      Reserved
1      0      Clear OC0B on Compare Match, set OC0B at BOTTOM, (non-inverting mode)

```

This table tells us we need to set COM0B1 and COM0B0 to 1.

**WGM mode**

If it's all set up, we only need to put the PWM in the right mode.

```
Mode WGM02 WGM01 WGM00 Timer/Counter TOP  Update-OCRx TOV-on
0    0     0     0     Normal        0xFF Immediate   MAX
1    0     0     1     PWM,P-Correct 0xFF TOP         BOTTOM
2    0     1     0     CTC           OCRA Immediate   MAX
3    0     1     1     Fast PWM      0xFF BOTTOM      MAX

```

So we'll need to set WGM02 to 0 and WGM01 and WGM00 to 1, to use fast PWM.F

**Succes?**

You should now be able to change the PWM's of these pins by setting the output compare registers of these. Getting the double PWM of the other timer ready, shouldn't be much more different. Be sure to set the right prescaler. Though it depends on a lot of external things.
> 1 votes

---
Tags: arduino-uno, motor, pwm, transistor, arduino-duemilanove
---


# Question
Title: Combining code for multiple sensors in one program
I need to operate 2 different sensors (gas and temp) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.

Here are the sketches:

Thermistor code:

```
void setup() {
  //This function gets called when the Arduino starts
  Serial.begin(9600);
  //This code sets up the Serial port at 9600 baud rate
}

void loop() {
  //This function loops while the arduino is powered
  int val; //Create an integer variable
  val=analogRead(0);
  //Read the analog port 0 and store the value in val
  Serial.println(val);
  //Print the value to the serial port
  delay(1000);
  //Wait one second before we do it again
}

```

This is the gas detector code:

```
/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int sensorPin = A0;
// select the input pin for the potentiometer
int DOPin = 2;
// select the pin for the LED
int sensorValue = 0;
// variable to store the value coming from the sensor
int ledPin =13;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(DOPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.print("Analog Output = ");
  Serial.println(sensorValue);
  // turn the ledPin on if triggered
  if (digitalRead(DOPin) ==HIGH) {
    digitalWrite(ledPin, LOW);
    Serial.println("Digital Output = OFF");
  } else {
    digitalWrite(ledPin, HIGH);
    Serial.println("Digital Output = ON");
  }
  delay(1000);
}

```

# Answer
> 5 votes
You just need to assign the sensors different pins.

```
/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int gasSensorPin= A0; // GAS sensor pin
int DOpin= 2; // select the pin for the LED
int gasSensorValue= 0; // variable to store the value coming from the sensor
int ledPin = 13;

int tempSensorPin = A1;  //Temperature sensor pin
int tempSensorValue;

void setup() {
 // declare the ledPin as an OUTPUT:
 pinMode(DOPin, INPUT);
 pinMode(ledPin, OUTPUT);
 Serial.begin(9600);
 }

void loop() {
 // read the value from the sensor:
 gasSensorValue= analogRead(gasSensorPin);
 Serial.print("Analog Output = ");
 Serial.println(gasSensorValue);
 // turn the ledPin on if triggered
 //
 if (digitalRead(DOpin) == HIGH){
 digitalWrite(ledPin, LOW);
 Serial.println("Digital Output = OFF");
 }
   else {
     digitalWrite(ledPin, HIGH);
     Serial.println("Digital Output = ON");
  }

Serial.print("Temperture: ");
tempSensorValue = analogRead(tempSensorPin));
Serial.println(tempSensorPin);  //Print the value of pin A4

delay(1000);
}

```

This is your combined sketch.

---
Tags: programming, sensors
---


title: Detaching interrupts

text:
# Question
Title: Detaching interrupts
I am using the following code to enable an interrupt for a pin:

```
*digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group

```

But I can't disable it. I am trying with this code:

```
if (*digitalPinToPCMSK(pin) == 0)
*digitalPinToPCICR(pin) &= ~(1<<digitalPinToPCICRbit(pin));

```

but it isn't working.

# Answer
> 1 votes
Don't you mean:

```
  PCICR  &= ~bit (digitalPinToPCICRbit(pin));

```

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


# Question
Title: "tamper" circuit of a reed switch: can I connect the two wires to an INPUT and an OUTPUT pin?
While working for the automation side of my new house, I'm currently in the process of installing several reed switches on top of external doors and windows.

Even if this could be used as a "security" infrastructure, I'm more interested, at the moment, at the "automation" side (*checking the status of door and windows without the need to physically watch them*) and as such, I'm going to extend the arduino-based infrastructure I've already planned and prototyped \[*more details here*\].

This is the reed-switch I've installed (1€ coin added for size reference):

and this is the related circuits:

As you can see, it comes with two circuits: one related to the "switch" funcionality; another one as a safety-measure to catch some "cuts" along the wires.

To check its status, currently, I've configured:

* "contact circuit":

+ one end to an Arduino GROUND\_PIN;
    + the other end to Digital PIN 52 (REED1\_SW\_Pin);
* "tamper circuit":

+ one end to an Arduino GROUND\_PIN (same GND pin as above);
    + the other end to Digital PIN 50 (REED1\_AT\_Pin);
* Arduino setup:

+ `pinMode(REED1_SW_Pin, INPUT_PULLUP)`
    + `pinMode(REED1_AT_Pin, INPUT_PULLUP)`
* Arduino code:

+ the main code-block handling REED events is reported below

Even tough everything is working fine, I wonder if there are better approaches, expecially inchecking the status of door and windows without the need to physically watch them terms of POWER-CONSUMPTION. So, here are my questions:

1. **TAMPER-Circuit**: due to its nature, it will always be a "closed" circuit, with current flowing inside, from REED1\_AT\_Pin to GND. Currently I'm checking its state every 1 second (`#define REED_AT_CHECKDELAY 1000`) but a frequency of once every 5 seconds, or even 10 seconds would be acceptable (for me). So I would like to have the current flowing *ONLY* during the "checking-timeframe". Something like:
    * every 5 seconds...
    * power-up something, getting the current flowing along the circuit;
    * check if the current flows;
    * if yes =\> OK
    * if no =\> set/keep the ALARM state
    * power-down the "something"

Is it feasible? If yes, how? Also: is it worth the effort?

2. **REED-switch circuit**: same as above. Polling approach is still acceptable (for me) but frequency need to be relatively high (5 seconds max), in order to keep of sort of "near-real-time feedback" when opening/closing windows. Best would be 2 secs polling-interval. With such a timing, does the polling-approach make sense?
3. from an "electronic" point of view, what is the "to-be-preferred-scenario" for the Arduino board:

* having a small, fixed, steady current, flowing out from a PIN, for *YEARS* on a 24/7/365 basis or...
    * having a continuosly transition from LOW-\>HIGH-\>LOW for a Digital PIN, say once every 5 seconds, again, for YEARS?

Every comment, sidenotes, hints, critics, whatever... is **REALLY** welcomed/appreciated.

---

## Arduino code-block handling REED events

BTW: the full-code, where the REED switch is handled togheter with pushbuttons and relays, it's available on GitHub

```
    [...]
    if (reed_sw1_state != reed_sw1_previous_state) {
        // a change occurred. Are we in a "boucing" window?
        if (millis() - last_reed_sw1_debounce > REED_DEBOUNCE) {
          // no. So it's a real change
          // Let's handle the event...
          Serial.print(millis());
          Serial.print("[REED] - SW1 state CHANGED from [");
          Serial.print(reed_sw1_previous_state);
          Serial.print("] to [");
          Serial.print(reed_sw1_state);
          Serial.println("]");
          reed_sw1_previous_state = reed_sw1_state;
          last_reed_sw1_debounce = millis();
        } else {
          // yes. Let's ignore it
        }
      }

      // Let's check REED Switches anti-tamper state
      if (millis()-reed_at1_lastcheck > REED_AT_CHECKDELAY) {
         reed_at1_state = ! digitalRead(REED1_AT_Pin);
         if (reed_at1_state == HIGH ) {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state OK [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         } else {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state ALARM - OnGoing TAMPER!!! [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         }
         reed_at1_lastcheck = millis();
      }
      [...]

```

# Answer
> 3 votes
> So I would like to have the current flowing ONLY during the "checking-timeframe".

Turn off the pull-up until just before checking. Allow a few milliseconds for the pull-up to raise the voltage.

> With such a timing, does the polling-approach make sense?

Certainly, if you are trying to save battery power.

---

Bear in mind the voltage drops over long cable runs (and also possibly induced spikes). You might want a more powerful pull-up (eg. 10k) rather than the inbuilt 50k. You can still organize that by having an output pin turn on the voltage to the pull-up. Or, have the pull-up wired in permanently but instead of running the other side to ground, set the "ground" wire to `OUTPUT` and write `LOW` to it - and then set it to `INPUT` when you want it to be inactive.

See my post about Power saving \- you could use a watchdog timer to wake the device at (say) every 4 seconds, to check things.

You may want to add in input-circuit protection (eg. a couple of diodes) to dampen down any incoming spikes. Even something simple like this:

---
Tags: arduino-mega, sensors, power, current, system-design
---


title: FTDI stdk 500k not responding

text:
# Question
Title: FTDI stdk 500k not responding
I programming atmega328P bootloaded with an FTDI.

Some tutorial mentions that you have to connect the DTR to the reset pin:

http://electronics-diy.com/FT232RL\_USB\_to\_Serial\_Adapter\_for\_PIC\_AVR\_ATMEGA\_ARDUINO\_MCUs.php

Is that so? Because some don't, they just say rx,tx is enough. I still can't program the chip with the error:

```
 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

avrdude: Version 5.11.1, compiled on Oct 18 2011 at 21:17:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : avrisp
         Overriding Baud Rate          : 9600
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

avrdude done.  Thank you.

```

I tried different baud rates, no matter what it's not responding. Linux recognizes the FTDI as:

```
Sat Feb 13 22:52:14 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:52:14 2016] ftdi_sio 1-2.1:1.0: device disconnected
[Sat Feb 13 22:52:19 2016] usb 1-2.1: new full-speed USB device number 73 using uhci_hcd
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device found, idVendor=0403, idProduct=6001
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Product: FT232R USB UART
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Manufacturer: FTDI
[Sat Feb 13 22:52:20 2016] usb 1-2.1: SerialNumber: A6004mhS
[Sat Feb 13 22:52:20 2016] ftdi_sio 1-2.1:1.0: FTDI USB Serial Device converter detected
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Detected FT232RL
[Sat Feb 13 22:52:20 2016] usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0
[Sat Feb 13 22:56:25 2016] usb 1-2.1: USB disconnect, device number 73
[Sat Feb 13 22:56:25 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:56:25 2016] ftdi_sio 1-2.1:1.0: device disconnected

```

Well my questions now are:

1, When I use the Arduino IDE to program a barebone 328P with this FTDI what should be the **BOARD** and what should be the **PROGRAMMER**?

Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Although I tried almost all... I think something else is wrong.

2, Should I be able to get any result with doing the previous:

```
 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

```

command WITHOUT connecting the barebone chip? I think not, since this doesn't act like a fully fledged MCU just like a serial converter.

Thanks

# Answer
> 1 votes
> Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Tha AVRISP is not an FTDI programmer. How do you have it wired up?

See: How to make an Arduino-compatible minimal board

From that page, this is how I hooked up my FTDI cable:

And a close-up:

You need RTS, via a 0.1 µF capacitor (in series) in order to trigger a reset.

# Answer
> 0 votes
You need to connect DTR to the reset pin because the Arduino IDE (really avrdude) needs to be able to reset the processor in order to return control to the bootloader, which will then receive the new program. When an Arduino board is running your sketch, the serial port is available for use by the sketch; it can't be used to upload a new program.

To answer your first question, you should set the board to whatever your board actually is. You don't have to worry about the programmer. It's only used if you use the "upload with programmer" function. The normal "upload" function uses the serial port to send the sketch to the board via the bootloader. That's what you want. Note that while you don't have to set the programmer, you do have to set the port.

You can use avrdude to program the Arduino through the serial port via the bootloader. That's exactly what the IDE does. You have to specify the port just as you do in the IDE. To determine the other settings, look up your board in the Arduino IDE's boards.txt file. Most of what boards.txt does is tell the IDE how to invoke avrdude.

I suspect that one reason why avrdude isn't working for you is that you've set the baud rate to 9600. According to boards.txt the upload speed for the Nano with the ATmega328P is 57600.

---
Tags: ftdi
---


# Question
Title: Physical dimensions(size) of the new MKR1000 board?
Anybody here knows the physical dimensions(size) of the new Aduino MKR1000 board?

# Answer
> 1 votes
If the diagram on the main page is to scale, then it's approximately 2.2 inches by 1.0 inches.

---
Tags: arduino-uno, arduino-mega, arduino-nano
---


# Question
Title: Do I have a faulty arduino uno, or have I found an Arduino bug?
Lately, we got an old arduino uno donated from a friend and have been trying to get it to work with servos. We have been having very perplexing results. We have tried many different "stock" code and servo combinations with our servos, but here is the behavior:

* 180 Servos automatically move to right max as soon as power is applied.
* Sail Winch servo moves a tiny amount and then stops. If power wire is removed and then reapplied, the servo moves another tiny amount.

The code is very simple. First we call the `servo.attach(pin)`, and confirm the pin. We have also tried doing the manual uSec definition: `servo.attach(pin, 600, 2400)`. In our loop() we have tried `servo.write(*value from 0-180*)` and `servo.writeMicroseconds(*value in PWM range*)`

Power is being supplied by a 9v battery, the sensor (yellow) is directly in digital pwm pin, while red (power) is in **+** and black (ground) is in **-**.

**I'm trying to decide whether I should invest in another arduino system.**

servos:

180 servos

Sail Winch servo

# Answer
If the Arduino "fails" the moment you apply power to a motor, you can bet that it is a power issue.

Or possibly you are exceeding the output rating of the output pin. You should not draw more than 20 mA from each output pin continuously.

> I'm trying to decide whether I should invest in another arduino system.

Power the motor independently of the Arduino. This is normal advice for all but very small motors. Also make sure that you have a suitable driving transistor / MOSFET if the motor draws more than 20 mA. Take into account any surge startup current.

---

See Driving motors, lights, etc. from an Arduino output pin for some design ideas.

For example:
> 2 votes

---
Tags: arduino-uno, servo
---


title: while compare, something is wrong

text:
# Question
Title: while compare, something is wrong
I have 5 LDR and Arduino Mega. I connect them and get light level.

```
void loop() {
// print the analog output in milli volts
int w=analogRead(west);
Serial.print("west = ");

Serial.print(w);
Serial.println(" mv");

int e=analogRead(east);
Serial.print("east = ");

Serial.print(e);
Serial.println(" mv");

int n=analogRead(north);
Serial.print("north = ");

Serial.print(n);
Serial.println(" mv");

int s=analogRead(south);
Serial.print("south = ");

Serial.print(s);
Serial.println(" mv");

int c=analogRead(control);
Serial.print("control = ");

Serial.print(c);
Serial.println(" mv");

delay(1000);

if(e > w)
Serial.println("west");

else if(e < w)
Serial.println("east");

else if(s > n)
Serial.println("south");

else(s < n);
Serial.println("north");

Serial.println("\n");
}

```

This is my loop and I always see east-north. When west is bigger than east I also see east. What

# Answer
Nick Gammon correctly points out a problem due to an extra semicolon, but you should also note what the construct `else(s < n)` is doing. When the `if` condition that this `else` gives an alternative to is false, the statement `(s < n)` gets executed. That statement is an expression statement, and its value is the evaluation of `s<n`, either true or false.

If the semicolon after `(s < n)` weren't there, you'd get a compile error because `(s < n) serial.println("north")` is not a valid statement. You may have meant to say `else if(s < n)` instead of `else(s < n)`.

Note, in the sequence

```
if (e > w)
   Serial.println("west");
else if (e < w)
   Serial.println("east");
else if (s > n)
   ...

```

that last `else` typically is reached only rarely, because the only condition to get to it is `e` and `w` being equal. Due to sensor noise and signal processing noise, the chance of `e` and `w` being equal is probably at most a few percent.

If your north/south test sequence is supposed to be independent of your east/west test sequence, leave out the second `if` and second `else` . That is, instead say:

```
if (e > w)
   Serial.println("west");
else
   Serial.println("east");
if (s > n)
   ...

```
> 3 votes

# Answer
Here:

```
else(s < n);
-----------^

```

That is wrong. See Arduino programming traps, tips and style guide.

---

## Trap #13: Don't put a semicolon at the end of every line

Semicolons end statements. However `if`, `for` and `while` are *compound* statements, so they should *not* have a semicolon after them like this:

**Wrong! ...**

```
  if (temperature > 40);    // <----- this semicolon is incorrect!
    {
    digitalWrite (furnaceControl, LOW);
    digitalWrite (warningLight, HIGH);
    }

  for (int i = 0; i < 10; i++);   // <----- this semicolon is incorrect!
    digitalWrite (i, HIGH);

```

The semicolons above (as indicated) terminate the `if` and `for` so they don't do anything useful. The lines following them are just unconditional blocks of code which are always executed, once.

**Correct:**

```
  if (temperature > 40)
    {
    digitalWrite (furnaceControl, LOW);
    digitalWrite (warningLight, HIGH);
    }

  for (int i = 0; i < 10; i++)
    digitalWrite (i, HIGH);

```
> 2 votes

---
Tags: sensors
---