# Question
Title: Something's wrong with my code for a 4 digit 7 segment clock display
I'm trying to do a clock using 4x7 segment displays but once I run the code **the Display doesn't turn on**

here's my Code that I'm like 90% sure that there's nothing wrong with it

```
bool A = 2;
bool B = 3;
bool C = 4;
bool D = 5;
bool E = 6;
bool F = 7;
bool G = 8;
int PWR1 = 10;
int PWR2 = 11;
int PWR3 = 12;
int PWR4 = 13;
int TimeSec = 0;
int TimeMin1 = 0;
int TimeMin2 = 0;
int TimeHour1 = 8;
int TimeHour2 = 0;
int Display = 0;
int Loop = 0;
int Digit = 0;
int Memory1 = 0;
int Memory2 = 0;
int Memory3 = 0;
int Memory4 = 0;
int Rewrite1 = 0;
int Rewrite2 = 0;
int Rewrite3 = 0;
int Rewrite4 = 0;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(F, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(PWR1, OUTPUT);
  pinMode(PWR2, OUTPUT);
  pinMode(PWR3, OUTPUT);
  pinMode(PWR4, OUTPUT);
}
void loop() {
  loop:
  delay(250);
  Digit = Digit + 1;
  if (Digit > 4) { Digit = 1; }
  if (Digit == 1) { goto digit1; }
  if (Digit == 2) { goto digit2; }
  if (Digit == 3) { goto digit3; }
  if (Digit == 4) { goto digit4; }

  // Supposedly turns on the 7-segment display that is next in line to have its digit edited but doesn't work?
  digit1:
  digitalWrite(PWR1, HIGH);
  digitalWrite(PWR2, LOW);
  digitalWrite(PWR3, LOW);
  digitalWrite(PWR4, LOW);
  Display = Memory1;
  goto skip;
  digit2:
  digitalWrite(PWR2, HIGH);
  digitalWrite(PWR1, LOW);
  digitalWrite(PWR3, LOW);
  digitalWrite(PWR4, LOW);
  Display = Memory2;
  goto skip;
  digit3:
  digitalWrite(PWR3, HIGH);
  digitalWrite(PWR1, LOW);
  digitalWrite(PWR2, LOW);
  digitalWrite(PWR4, LOW);
  Display = Memory3;
  goto skip;
  digit4:
  digitalWrite(PWR4, HIGH);
  digitalWrite(PWR1, LOW);
  digitalWrite(PWR2, LOW);
  digitalWrite(PWR3, LOW);
  Display = Memory4;
  skip:

   // Manual Turning on of LEDs is overcomplicated and can be made much shorter yes I know :(
   if (Display == 1) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
  }
  if (Display == 2) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(G, LOW);
    digitalWrite(E, LOW);
    digitalWrite(D, LOW);
  }
  if (Display == 3) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(G, LOW);
    digitalWrite(D, LOW);
  }
  if (Display == 4) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(G, LOW);
    digitalWrite(F, LOW);
    digitalWrite(C, LOW);
  }
  if (Display == 5) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
  }
  if (Display == 6) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(E, LOW);
  }
  if (Display == 7) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
  }
  if (Display == 8) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
    digitalWrite(E, LOW);
  }
  if (Display == 9) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
  }
  if (Display == 0) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(E, LOW);
    digitalWrite(F, LOW);
  }

  // Checks how many times it has looped over
  Loop = Loop + 1;
  if (Loop < 4) {goto loop;}
  else
  {
    // Resets Loop count and counts 1 second (normally it has a delay(1000) but the delay(250) on the loop to account for LED's turning on is counting for me )
    Loop = 0;
    TimeSec = (TimeSec + 1);
    if (TimeSec == 60) {
      TimeMin1 = (TimeMin1 + 1);
      Memory1 = TimeMin1;
      TimeSec = 0;
      if (TimeMin1 == 10) {
        TimeMin2 = (TimeMin2 + 1);
        Memory2 = TimeMin2;
        TimeMin1 = 0;
        Memory1 = TimeMin1;
        if (TimeMin2 == 7) {
          TimeHour1 = (TimeHour1 + 1);
          Memory3 = TimeHour1;
          TimeMin2 = 0;
          Memory2 = TimeMin2;
          if (TimeHour1 == 10) {
            TimeHour2 = 1;
            Memory4 = TimeHour2;
            TimeHour1 = 0;
            Memory3 = TimeHour1;
            if (TimeHour1 == 3 && TimeHour2 == 1) {
              TimeHour2 = 0;
              Memory4 = TimeHour2;
              TimeHour1 = 1;
              Memory3 = TimeHour1;
            }
          }
        }
      }
    }
  }
}

```

And here's how it's Wired up

Also I think that I have to make a clock of my own for the Timer or else it will become a problem later on but I don't know how to make 2 loops so if someone can tell me how to do it (preferably in a way that I can understand xD) I'd be very grateful

**Notes:**

* The Displays are Common Anode so to turn on a LED I used `digitalWrite(ledpin, LOW)` for a negative output
* I'm not using a 4 digit 7-segment display -- I'm using 4 individual 7-segment displays
* Resistors are 220 Ohm
* The Picture was made using https://circuits.io
* I'm still new at this so my code may have some newb mistakes or just stuff that was made overcomplicatedly simple if you know what I mean :P

UPDATE 1:

I fixed it now the problem was I was setting the variables to bool instead of integer but I still can't figure out how to do a self-sufficient clock because the current code now runs but doesn't turn on as fast as I need to

# Answer
> 1 votes
There are several bugs that I spot right off the bat. First off, you should never need goto in C++. You should be able to use if, for, and while to completely eliminate those. goto makes code hard to follow and read, so it makes it nearly impossible for someone else to try to debug. Be nice to yourself and forget that goto ever existed. I would suggest hitting a C++ tutorial and learning about functions, because most of the places you've used goto, what you really needed was a function call.

Second is this:

```
bool A = 2;
bool B = 3;
bool C = 4;
bool D = 5;
bool E = 6;
bool F = 7;
bool G = 8;

```

A bool is meant to hold a true or false value, not a pin number. You should use int here, or better yet save a few bytes and use byte. But not bool. The second issue here are the single capital letter variable names. Those are always a bad idea. Many of them (B and F for sure) are already defined as macros in the core. They're not available for you to use. Single letter variable names are bad form, but single capital letters are right out.

Third is the way you have the digits connected. There should be a resistor for each segment, or you will have brightness differences depending on how many segments are in use at any one time. But that can wait until you get the code worked out.

Finally, here is some code for working with 7-segment displays. It's a lot easier to work with than the whole thing you've got written out. See if you can follow it and ask questions if you don't understand. This code would count 0 to 9 over and over on a single 7 segment display.

```
byte digits[] = {0b1111110 , 0b0110000, 0b1101101, 0b1111001,
0b0110011, 0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1111011};

// pins to segments g,f,e,d,c,b,a
byte pins[] = {3,4,5,6,7,8,9};

void displayNumber(int aNumber) {
  for (int i = 0; i < 7; i++) {
    digitalWrite(pins[i], digits[aNumber] & (1 << i));
  }
}

void setup(){
  for (int i = 0; i < 7; i++){
    pinMode(pins[i], OUTPUT);
  }
}

void loop(){
  for (int i = 0; i < 10; i++) {
    displayNumber(i);
    delay(1000);
  }
}

```

---
Tags: arduino-uno, display, 7-segment
---


# Question
Title: Including an arduino library in Eclipse Neon (undefined reference to)
I'm trying for the first time to use Arduino Libraries (Servo.h & Servo.cpp in this case) in Eclipse IDE.

So far I've managed to compile and run Arduino code using this tutorial (I suppose many of you already know it).

The problem comes when I add the Servo.cpp and Servo.h files and try to run the program:

```
    13:35:08 **** Incremental Build of configuration Release for project Servo ****
make all
arduinoEclipse/subdir.mk:268: warning: overriding commands for target `arduinoEclipse/wiring_pulse.o'
arduinoEclipse/subdir.mk:261: warning: ignoring old commands for target `arduinoEclipse/wiring_pulse.o'
Building file: ../ServoTest.cpp
Invoking: AVR C++ Compiler
avr-g++ -I"C:\arduino\arduinoEclipse" -Wall -Os -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -funsigned-char -funsigned-bitfields -fno-exceptions -mmcu=atmega328p -DF_CPU=1600000UL -MMD -MP -MF"ServoTest.d" -MT"ServoTest.o" -c -o "ServoTest.o" "../ServoTest.cpp"
Finished building: ../ServoTest.cpp

Building target: Servo.elf
Invoking: AVR C++ Linker
avr-g++ -Wl,-Map,Servo.map,--cref -mrelax -Wl,--gc-sections -mmcu=atmega328p -o "Servo.elf"  ./arduinoEclipse/CDC.o ./arduinoEclipse/HardwareSerial.o ./arduinoEclipse/HardwareSerial0.o ./arduinoEclipse/HardwareSerial1.o ./arduinoEclipse/HardwareSerial2.o ./arduinoEclipse/HardwareSerial3.o ./arduinoEclipse/IPAddress.o ./arduinoEclipse/PluggableUSB.o ./arduinoEclipse/Print.o ./arduinoEclipse/Servo.o ./arduinoEclipse/Stream.o ./arduinoEclipse/Tone.o ./arduinoEclipse/USBCore.o ./arduinoEclipse/WInterrupts.o ./arduinoEclipse/WMath.o ./arduinoEclipse/WString.o ./arduinoEclipse/abi.o ./arduinoEclipse/hooks.o ./arduinoEclipse/main.o ./arduinoEclipse/new.o ./arduinoEclipse/wiring.o ./arduinoEclipse/wiring_analog.o ./arduinoEclipse/wiring_digital.o ./arduinoEclipse/wiring_pulse.o ./arduinoEclipse/wiring_shift.o  ./ServoTest.o
./ServoTest.o: In function `setup':
ServoTest.cpp:(.text.setup+0x8): undefined reference to `Servo::attach(int)'
./ServoTest.o: In function `loop':
ServoTest.cpp:(.text.loop+0x20): undefined reference to `Servo::writeMicroseconds(int)'
ServoTest.cpp:(.text.loop+0x5a): undefined reference to `Servo::writeMicroseconds(int)'
ServoTest.cpp:(.text.loop+0xbc): undefined reference to `Servo::write(int)'
./ServoTest.o: In function `_GLOBAL__sub_I_myservo':
ServoTest.cpp:(.text.startup._GLOBAL__sub_I_myservo+0x4): undefined reference to `Servo::Servo()'
collect2.exe: error: ld returned 1 exit status
make: *** [Servo.elf] Error 1

```

As you can see in the console output, it compiles correctly, but when it comes to the linker, it doesn't find the function references from the Servo.cpp.

As I have seen in this post, the problem comes from the fact that I need also to generate an .a (static library) file in order to link both .h and .cpp files. Still, I have no idea how I am supposed to generate this file.

For this project, I have just added in arduinoEclipse folder all the .cpp and .h files from `C:\arduino\hardware\arduino\avr\cores\arduino`, `C:\arduino\hardware\arduino\avr\variants\standard` & `C:\arduino\libraries\Servo`.

Do you see what I could be missing?

Thank you in advance

# Answer
The arduino build process is described here: https://www.arduino.cc/en/Hacking/BuildProcess
You do not really need to build a archive. You can link all your source files but that will result in a far bigger file to upload to the embedded device.
The normal CDT process to build a archive is by having 2 projects. One for the "archive" one for your sketch and then use project dependencies.
However since Arduino IDE 1.5 this process is hard to maintain because changing settings for your sketch may force you to change your archive compilation settings.
As far as I know; out of the box CDT does not support creating a library and linking it to a "executable" in one project. This is something Sloeber (road 1 in the article) has added.
I know this because I'm authoring Sloeber.
> 1 votes

# Answer
I don't have eclipse handy right now, so I may not have the menu options verbatim here, but with eclipse there are more steps to including a library than just writing the line in the code. Go to the project in the project explorer and right click the project name. Hit import and select the option for importing Arduino libraries into the sketch. It should bring up a dialog with a list of all the libraries you have installed and you can choose from there. Then there will be a folder in your project called includes IIRC and it will have a link to the library that you imported. Now when you compile it will find the library.
> 1 votes

---
Tags: arduino-uno, servo, avr, eclipse
---


# Question
Title: Problem with 2 decimal places/2 significant figures
Lora/GPS Shield + Arduino Uno + PLX-DAQ (latest custom version)

I have a problem on how to generate more than 1/2 decimal output. Currently, I'm trying to generate GPS Lat and Long(code from TinyGPS++) on PLX-DAQ

Just like in the image. Latitude generated in 1/2 decimal places. I'm trying to get more than 2 decimal places.

For example : from 3.2 to 3.123953

Coding link: https://www.dropbox.com/s/rqjpnsc9pg33f9n/Coding.txt?dl=0

Thanks.

# Answer
You're talking about the output from this line?

```
Serial.println( (String) "DATA,DATE,TIME," +flat+ "");

```

drop the use of the String class and make that two separate print statements. Then you can use the second argument to print to define the precision.

```
Serial.print("DATA,DATE,TIME,");
Serial.println(flat, 6);

```

That gets the same end result output going out the serial line, but lets you specify the precision and avoids the nasty String class.
> 1 votes

---
Tags: arduino-uno, gps
---


# Question
Title: I am trying to combine an automatic door lock with an RFID MFRC522 with a IR REMOTE program
I am getting this error.

```
Arduino: 1.8.2 Hourly Build 2017/02/17 11:33 (Windows 8.1), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\REMOTE\IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

Here is the entire code:

```
#include <RFID.h>
#include <Wire.h>  // i2C Conection Library
#include <LiquidCrystal_I2C.h>  //Memanggil i2C LCD Library
LiquidCrystal_I2C lcd(0x3F, 16, 2);

#include <SPI.h>
#include <RFID.h>
#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN,RST_PIN);

const int buzzer = 7;   //Passive buzzer ke Pin D7 dan GND
const int doorLock = 8; //Driver Selenoid Door Lock/Relay input ke pin D8
int serNum[5];          //Variable buffer Scan Card

int cards[][5] = {      //ID Kartu yang diperbolehkan masuk
  {120, 181, 196 ,101, 14}

};

bool access = false;

int alarm = 0;
uint8_t alarmStat = 0;
uint8_t maxError = 5;
void setup(){
    Serial.begin(9600);
    lcd.begin();
    SPI.begin();
    rfid.init();

    pinMode(doorLock, OUTPUT);
    digitalWrite(doorLock, HIGH);

  tone (buzzer,1200);
  lcd.setCursor (0,0);
  lcd.print(F("  RFID System   "));
  lcd.setCursor (0,1);
  lcd.print(F(" Control Access "));
  delay (2000);
  lcd.clear();
  noTone (buzzer);
}

void loop(){
  if (alarm >= maxError){
    alarmStat = 1;    }

  if (alarmStat == 0){
  lcd.setCursor (0,0);
  lcd.print(F(" -System Ready- "));
  lcd.setCursor (0,1);
  lcd.print(F(" Scan Your Card "));

    if(rfid.isCard()){

        if(rfid.readCardSerial()){
            Serial.print(rfid.serNum[0]);
            Serial.print(" ");
            Serial.print(rfid.serNum[1]);
            Serial.print(" ");
            Serial.print(rfid.serNum[2]);
            Serial.print(" ");
            Serial.print(rfid.serNum[3]);
            Serial.print(" ");
            Serial.print(rfid.serNum[4]);
            Serial.println("");

            for(int x = 0; x < sizeof(cards); x++){
              for(int i = 0; i < sizeof(rfid.serNum); i++ ){
                  if(rfid.serNum[i] != cards[x][i]) {
                      access = false;
                      break;
                  } else {
                      access = true;
                  }
              }
              if(access) break;
            }
        }

       if(access){
          Serial.println("Welcome!");
          lcd.setCursor (0,0);
          lcd.print(F(" DOOR UNLOCKED!! :)"));
          lcd.setCursor (0,1);
          lcd.print("ID:");
          lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
          lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
          lcd.print(rfid.serNum[4]);
           digitalWrite(doorLock, LOW);
           tone (buzzer,900);
           delay(100);
           tone (buzzer,1200);
           delay(100);
           tone (buzzer,1800);
           delay(200);
           noTone(buzzer);
           delay(600);
           lcd.setCursor (0,0);
           lcd.print(F("WELCOME"));
           lcd.setCursor (0,1);
           lcd.print(F("AutoLock after "));
           for(int i=5; i>0; i--){
            lcd.setCursor (15,1); lcd.print(i);
            delay (1000);
           }
           digitalWrite(doorLock, HIGH);
           lcd.clear();
      } else {
           alarm = alarm+1;
           Serial.println("Not allowed!");
           lcd.setCursor (0,0);
           lcd.print(F(" ACCESS DENIED!!  "));
           lcd.setCursor (0,1);
         lcd.print("ID:");
           lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
           lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
           lcd.print(rfid.serNum[4]);
           tone (buzzer,900);
           delay(200);
           noTone(buzzer);
           delay(200);
           tone (buzzer,900);
           delay(200);
           noTone (buzzer);
           delay(500);
           lcd.clear();
       }
    }
    rfid.halt();
}
else {
  lcd.setCursor (0,0);
  lcd.print(F("-System LOCKED- "));
  lcd.setCursor (0,1);
  lcd.print(F(" Please Wait "));
for(int i=5; i>0; i--){
tone (buzzer,4000);

lcd.setCursor (13,1); lcd.print(i);
lcd.print(F("  "));delay (1000);}
noTone (buzzer);
alarmStat = 0;
alarm = 0;
  }
}

//code  of an IR REMOTE

#include <IRremote.h>

int RECV_PIN = 2; // the pin where you connect the output pin of TSOP4838
int lock =13 ;
int itsONled[] = {};
/* the initial state of LEDs is OFF (zero)
the first zero must remain zero but you can
change the others to 1's if you want a certain
led to light when the board is powered */
#define code1 26775 // code received from button 1

IRrecv irrecv(RECV_PIN);

decode_results results;

void remote()
{
  Serial.begin(9600);   // you can comment this line
  irrecv.enableIRIn();  // Start the receiver0
  pinMode(lock, OUTPUT);

}

void loop_1() {
  if (irrecv.decode(&results)) {
    unsigned int value = results.value;
    switch(value) {
       case code1:
         if(itsONled[1] == 1) {        // if first led is on then
            digitalWrite(lock, LOW);   // turn it off when button is pressed
            itsONled[1] = 0;           // and set its state as off
            Serial.println("ledl OFF");
         } else {                      // else if first led is off
             digitalWrite(lock, HIGH); // turn it on when the button is pressed
            Serial.println("led 1 ON");
             itsONled[1] = 1;          // and set its state as on
         }

          break;
    }

    Serial.println(value); // you can comment this line
    irrecv.resume(); // Receive the next value
  }
}

```

# Answer
The error message `multiple definition of __vector_7` means that you have more than one interrupt handler defined for the interrupt that has interrupt vector 7.

Although the ATmega328x datasheet in a table called *Interrupt Vectors in ATmega328 and ATmega328P* refers to interrupt vector 7 as the Watchdog Time-out Interrupt, that probably is misleading, because only the following ISRs can be defined in `Tone.cpp`:

```
ISR(TIMER0_COMPA_vect)
ISR(TIMER1_COMPA_vect)
ISR(TIMER2_COMPA_vect)
ISR(TIMER3_COMPA_vect)
ISR(TIMER4_COMPA_vect)
ISR(TIMER5_COMPA_vect)

```

(These can be defined, but typically most are not. All of them are conditional upon which MCU is selected.)

The article *multiple definition of '\__vector\_7'* at arduino.cc attributes the problem to the last of those ISRs, `ISR(TIMER5_COMPA_vect)`. Anyhow, in short, you might need to check what board or MCU you are compiling for, or may need to find a substitute for one of `Tone` or `IRremote`, the libraries that are both defining the ISR that has a conflict.

*Edit 1:* The article TimerFreeTone Library v1.5: Play tones without timers and therefore no conflicts at arduino.cc describes a *TimerFreeTone v1.5* library that generates tones without using timers. You might be able to use that library in place of the `Tone` library that has a conflict.
> 1 votes

# Answer
1. You can't use tone and IRremote in the same sketch as they are both trying to use the same timer interrupt.
2. Don't use the hourly build. It's not tested. Get the latest stable version if you are working on your final project. You don't want unknown bugs. Let the beta testers use the hourly build. For something like a final project you need things to work, so stick with the stable version, not the bleeding edge of development.
> 0 votes

---
Tags: arduino-uno, programming, rfid, ir
---


# Question
Title: How can I get my Attiny85 interupt to trigger
I have an ATTiny85 set up to detect a magnet passing over a hall sensor. Every 2 detection's I want it to light up an LED.

I decided to do the code using the arduino IDE and the code is as follows:

```
const int hallPin = 2;     // the number of the hall effect pin
const int ledPin =  1;      // the number of the LED pin

// variables will change:
volatile int hallState = 0;         // variable for storing the hall counter

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  digitalWrite(hallPin, HIGH);

  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

void loop()
{
  if(hallState>1)
  {
      digitalWrite(ledPin,HIGH);
      delay(2000);
      digitalWrite(ledPin,LOW);
      delay(2000);
      hallState=0;
  }
}

void pin_ISR()
{
    hallState++;
}

```

I've dry run this a bunch of times and cant see anything wrong with it. I use the digitalWrite on the hall pin to enable the internal pullup. But the circuit just doesnt work.

Here is the circuit:

I connected a multi meter to the hall effect sensor on its own just to check if it was working. I added an external pull up using a 10k resistor and it worked as expected 5v when no magnet present and almost 0 volts when a magnet is brought in range.

So my guess is my interrupt routine isnt working in my code, what could I be doing wrong? I've read in the documentation that pin 0 is the correct interrupt pin on the attiny85

Edit: Adding Schematic

# Answer
> 1 votes
You main problem is that you have wired up your MCU wrong.

Pin 5 (PB0) is *not* the external interrupt pin. Pin 7 (PB2) is the external interrupt 0 (INT0) pin.

As a result your code will not do anything when the hall sensor changes because it is not looking at it.

---

I would suggest not trying to use the `attachInterrupt()` abstraction. Instead I would simply enable the external interrupt directly:

```
GIMSK |= _BV(INT0);

```

And use a proper ISR handler:

```
ISR(INT0_vect) {
    //Your ISR code here.
}

```

---
Tags: attiny
---


title: ATmega328P SPI Slave

text:
# Question
Title: ATmega328P SPI Slave
I was scrolling through the ATmega328P datasheet when I came across a rather fascinating statement about the way in which the data part of the SPI interface is buffered. I can't seem to understand why the double input buffer is necessary. The following statement can be found on page 161 (Datasheet):

> The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle is completed. When receiving data, however, a received character must be read from the SPI Data Register before the next character has been completely shifted in. Otherwise, the first byte is lost.

Can someone please briefly explain to me why the double input buffer is necessary?

# Answer
> 2 votes
You have control over when you place a byte in the TX buffer and control over when you read a byte from the RX buffer. You don't have control over when the master sends data to you, though, so somewhere is needed to store that incoming data until you read it. Since the master can start sending another byte before you have read the last one it's critical that the receiving shift register is separate from the register you read the shifted in data from. Only when the complete byte has been shifted in does it get copied to the receive buffer, so that another shifting in can begin.

When transmitting you don't need to worry about that since what you write into the TX buffer is what is about to be shifted out. You don't write anything else until it's time to send the next byte, at which point the TX register is empty anyway.

---
Tags: atmega328, spi, shift-register
---


# Question
Title: Help understanding circuit for button example
I´m working on the button example .Basically, i don't quite get the use of this connection.

Also, the breadboard i'm using is not quite the ones i see on most tutorials.

is there any 'mapping' i could make between them?

I really appreciate any help you can provide.

# Answer
> 1 votes
The connection in that picture is pointless. They are just putting power and ground on the top set of rails, but they aren't using it.

Your breadboard has only one rail on either side. So you'll have to designate one for power and one for ground and you'll need some slightly longer wires for some of the connections.

---
Tags: arduino-uno, button, breadboard
---


# Question
Title: Correct use of interrupt vs monitoring switch
Background: I have a uni assignment which requires an autonomous robot to do a number of tasks and then finish in a set spot after being triggered to start by an outside physical interaction. I've set up a light limit switch to detect this interaction.

My approach would normaly be to look for the switch in the loop to go high and then run through my code and put a really long delay at the end. e.g.

```
switchState = digitalRead(switch);
 if (switchState == HIGH){
 //do my routine which is a function defined outside of the loop
}

```

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

# Answer
> 2 votes
No, an interrupt here would be pointless.

You use an interrupt to detect a change on an input whilst you are doing something else. It's a good way of getting instant (or near instant) notification of something happening.

If you're using the input to start something going when there's nothing happening then you gain nothing other than extra complexity by using an interrupt. You're not doing anything else, and you don't need an instant response, so just polling the input is the simplest option.

# Answer
> 1 votes
> Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

it depends critically on your definition of "go high", ie. if you are looking for a transition to high, or if you are looking for the switch to be high. edge triggererd vs. level triggered.

As is, your existing (level-triggered) logic can be easily implemented via an interrupt, as will an edge triggered logic.

interrupt-driven code is generally more efficient for slow / infrequent inputs: it doesn't waste the cpu's processing power. But it does add a level a complexity that can be difficult to handle for beginners.

As for me, I think it is (practically) impossible to code without the use of interrupts.

---
Tags: interrupt, code-optimization
---


# Question
Title: How to make DC motor rotate a specific number of turns?
Can someone please give the code which can be used to rotate the dc motor a specific number of rotations like 2 rotations or 5 rotations. I'm using arduino uno board.

# Answer
You can't. You either have to attach a sensor to the motor shaft to measure the numbers of rotations or use a stepper motor.
> 2 votes

# Answer
No! That is not how motors work.

If you need precision control you need to use a stepper motor or servo.

You could implement some solution with a geared motor and position sensor, but this really only works (imprecisely) with a slow rotation speed.
> 0 votes

# Answer
> Can someone please give the code which can be used to rotate the dc motor a specific number of rotations like 2 rotations or 5 rotations.

fairly simple:

```
rotation_count = 0; //initialize rotation counter
motor_on();  //turn on the motor
while (rotation_count < DESIRED_COUNT) {
  rotation_count = count_rotation(); //update rotation count
};
motor_off(); //turn off the motor

```
> -1 votes

---
Tags: arduino-uno, code-review
---


title: programming arduino in pure c

text:
# Question
Title: programming arduino in pure c
I'm trying to flash pure c-code to arduino Mega2560 board from linux using avr-gcc & avrdude. Compilation is done , now trying to flash using avr-dude, getting error as "*avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x00*"

I used below command to produce hex file

```
avr-gcc -mmcu=atmega2560 -DF_CPU=16000000UL led.c -o led.elf

```

*In file included from led.c:3:0: /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler optimizations disabled; functions from won't work as designed" \[-Wcpp\] \# warning "Compiler optimizations disabled; functions from won't work as designed"*

And then

```
avr-objcopy -j .text -O ihex led.elf led.hex

```

finally for flashing

```
avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

```

FYI: port is correct & RX pin is blinking i.e connection is perfect between computer & board

# Answer
> 2 votes
> In file included from led.c:3:0: /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler optimizations disabled; functions from won't work as designed"

You should start by fixing this. Simply add `-Os` to the compiler command line. This means “optimize for size”, and is the standard optimization option used with Arduinos.

> avr-objcopy -j .text -O ihex led.elf led.hex

If your copy of avrdude was compiled with libelf (like the one supplied with Ubuntu is), you don't need this: you can hand your elf file directly to avrdude.

> avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

`-F` tells avrdude to **not** verify the device signature. `-V` tells it to **not** verify the upload. I wouldn't use any of these options unless I had a very good reason to do so. `-c arduino` is wrong: it selects the upload protocol used by optiboot (used, e.g., in the Uno). The Mega 2560 uses a different bootloader based on the “wiring” protocol. I would also add the `-D` option (disable auto erase) because I saw the Arduino IDE using it, and because without this option I get the error:

```
avrdude: erasing chip
avrdude: stk500v2_command(): command failed

```

In the end, the upload command ends up being something like:

```
avrdude -p atmega2560 -c wiring -P /dev/ttyACM3 -b 115200 -D -U led.elf

```

---
Tags: avr, avrdude, avr-gcc, avr-toolchain
---


# Question
Title: Storing a 2 dimensional Array in PROGMEM
I am running a Mega 2560 processor board.

I have a large "unsigned char" database currently stored in a 2 dimensional array in SRAM. I have plenty of room in program memory and need to move the database to PROGMEM. It appears that the rules around how to use PROGMEM have changed and the documentation does not reflect the change. I have found a way to store the array in PROGMEM and can access the data statically (ARRAY\[0,1\]). If I try to access the array dynamically, (ARRAY\[var1,var2\]), I get junk.

Since I have seen some questions what I mean by "static" and "Dynamic" I gladly add the following examples:

```
//Array initialization

const static unsigned char __attribute__ ((progmem)) Image_1d_Array[234]={
  0x00, 0x0e, 0xf8, 0xff, 0xdf, 0x03, 0xc0, 0x1d, 0x60, 0x1f, 0x60, 0x00, 0x03,
   0xdb, 0x01, 0x00, 0x08, 0xe3, 0x07, 0x00, 0x0e, 0x00, 0x1e, 0x30, 0x00, 0x00,
   0x00, 0x0e, 0xf0, 0x07, 0xfc, 0x01, 0xc0, 0x39, 0x00, 0x1f, 0xe0, 0x00, 0x03};

void setup:
  int i;
  char myChar;

//  Static read.  This will give me the correct values
  Serial.print("Image= "); Serial.println(Image_1d_Array[0],HEX);
  Serial.print("Image= "); Serial.println(Image_1d_Array[1],HEX);
  Serial.print("Image= "); Serial.println(Image_1d_Array[2],HEX);
  Serial.print("Image= "); Serial.println(Image_1d_Array[3],HEX);
  Serial.println("");

//  Dynamic read.  This will give me the junk values
  for(i = 0; i <=11; i++){
     Serial.print("AImage= ");
     myChar = pgm_read_byte_near(&Image_1d_Array + i);
     Serial.println(myChar,HEX);
    }

```

I can't even get a single dimensional array to work dynamically.

Does anybody understand the new rules to access the array?? The following data structures from the Arduino reference manual are no longer supported

```
prog_char - a signed char (1 byte) -127 to 128
prog_uchar - an unsigned char (1 byte) 0 to 255
prog_int16_t - a signed int (2 bytes) -32,767 to 32,768
prog_uint16_t - an unsigned int (2 bytes) 0 to 65,535
prog_int32_t - a signed long (4 bytes) -2,147,483,648 to * 2,147,483,647.
prog_uint32_t - an unsigned long (4 bytes) 0 to 4,294,967,295

```

# Answer
You wrote:

```
myChar = pgm_read_byte_near(&Image_1d_Array + i);

```

Here `&Image_1d_Array` is the address of the array. Its type is “pointer to an array of 234 unsigned chars”. When you add `i` to this pointer, per the rules of pointer arithmetic, you are actually adding to the address `i` times the size of the array.

What you actually mean by `&Image_1d_Array` is “the address of the first element of the array”, which can be written `&Image_1d_Array[0]`. Or you could rely on the usual “decay to pointer” semantics, and simply write `Image_1d_Array`, as suggested in Johnny Mopp's comment.

Now you should have noticed that both `Image_1d_Array` and `&Image_1d_Array` behave as pointers to the same memory address, only they have different types. See the C FAQ and references therein for more on this distinction.

Note that the usual way of doing what you want is:

```
myChar = pgm_read_byte_near(&Image_1d_Array[i]);

```
> 0 votes

---
Tags: programming
---


# Question
Title: How to exit a function if conditions are met
Hello I want to exit a function if conditions are meet .

I have this code inside the `loop()`

```
if (t.hour == 7 && t.min == 16) {
  if(moistureOneSensorValue >= 700 ){
     RelayOne();
  }
}

```

If its `true` it will call the `RelayOne()` function and open the solenoid valve inside the `relayOne()` fucntion i have also code for waterflow sensor

below is the relayOne function code for opening the valve and getting data from waterflow

```
 void RelayOne(){

//Serial.println("Valve Open");
digitalWrite(RELAY1, 0); //OPEN VALVE
digitalWrite(WATERFLOW1, HIGH);//READY WATER FLOW FOR SENSING
//WATER FLOW

if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.

    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    //Serial.print(pulseCount);

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.

    oldTime = millis();

   //  Serial.print("::");
    // Serial.print(oldTime);
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.

    flowMilliLitres = (flowRate / 60) * 1000;

    // Serial.print(flowMilliLitres);
    // Add the millilitres passed in this second to the cumulative total

    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL");

    //setPointForN1 = EEPROM.get(0, WATEREQFORN1) / 2;

   if(totalMilliLitres >= setPointForN1 ){
       closeSolenoidValve();

      }

     // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }

  if(flowMilliLitres == 0){
     totalMilliLitres = 0;
  }

}

```

this line of code will supposedly close the valve but its not working

```
`if(totalMilliLitres >= setPointForN1 ){
           closeSolenoidValve();

          }`

```

the problem is that it will wait for 1 minute before closing the valve even tho the set point already reach .

Below is My full code

```
#include <EEPROM.h>

#include <TimeAlarms.h>
#include <Wire.h>
#include <dht.h>
#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);
//RTC_DS1307 rtc;

Time  t;

dht DHT;

//PINS
#define MOISTURE1 A15
#define MOISTURE2 A14

#define RELAY1 7
#define RELAY2 6
#define ALARM 13
#define DHT11_PIN A11

int relayState1 = 1;
int relayState2 = 1;
//WATER FLOW VARIABLES

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorInterrupt2 = 1;  // 0 = digital pin 3
byte  WATERFLOW1 = 2;
byte  WATERFLOW2 = 3;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;

volatile byte pulseCount;
volatile byte pulseCount2;
//For Waterflow sensor pin 13
float flowRate;
float frac;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;

//For Waterflow sensor pin 12
float flowRate2;
float frac2;
unsigned int flowMilliLitres2;
unsigned long totalMilliLitres2;

unsigned long setPointForN1;
unsigned long setPointForN2;

unsigned long oldTime;

unsigned long oldTime2;

///END OF WATER FLOW VARIABLES

unsigned int val;
int DELAYNI = 1000;

//Sensor Variables

int  moistureOneSensorValue;
int  moistureTwoSensorValue;
int  waterLevelSensorValue;
int  humiditySensorValue;
int  tempSensorValue;

//FOR EEPROM
unsigned int WATEREQFORN1;
unsigned int WATEREQFORN2;
unsigned long DELAYINTERVALOFDATA;
unsigned long prevMillis = 0;

unsigned long interval;

// -------------------------------------------------------------------
// SETUP    SETUP    SETUP    SETUP    SETUP    SETUP    SETUP    SETUP
// -------------------------------------------------------------------

void setup() {

  // put your setup code here, to run once:

  // Setup Serial connection
  Serial.begin(9600);
  rtc.begin();
  Wire.begin();

   //EEPROM

  //int eepromSize=EEPROM.length();
  //Serial.print("EEPROM found, size=");
 // Serial.println(eepromSize);
    // Get the last fade value (as an integer)
  //EEPROM.get(0, WATEREQFORN1);
  //Serial.print("Last Value N1: ");
 // Serial.println(WATEREQFORN1);

 // EEPROM.get(3, WATEREQFORN2);
 // Serial.print("Last Value N2: ");
 // Serial.println(WATEREQFORN2);

pinMode(MOISTURE1, INPUT);
pinMode(MOISTURE2, INPUT);
pinMode(WATERFLOW1, INPUT);
pinMode(WATERFLOW2, INPUT);
pinMode(DHT11_PIN, INPUT);
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);

//WATER FLOW
  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;

  oldTime           = 0;
   attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

  pulseCount2        = 0;
  flowRate2          = 0.0;
  flowMilliLitres2   = 0;
  totalMilliLitres2  = 0;

  oldTime2           = 0;
  attachInterrupt(sensorInterrupt2, pulseCounter2, FALLING);

  digitalWrite(RELAY1, 1);
  digitalWrite(RELAY2, 1);
}

void loop() {

  // put your main code here, to run repeatedly:
  t = rtc.getTime();
//DateTime now = rtc.now();
//This will get data send from the Desktop Application
char inc;
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        WATEREQFORN1 = val;

            EEPROM.put(0, WATEREQFORN1);
            //Serial.print("DATA SAVE TO EEPROM");

        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
         WATEREQFORN2 = val;
         EEPROM.put(5, WATEREQFORN2);
         //Serial.print("DATA SAVE TO EEPROM");

        break;
      case 'D':
        Serial.print("Case D got ");
        Serial.println(val);
        DELAYINTERVALOFDATA = val;
        EEPROM.put(10,DELAYINTERVALOFDATA);
        break;

      default :
        ; // handle blanks, returns, etc
      }
      val = 0;  // Set val to zero after any non-digit
    }//END of SWITCH
  }//END of WHILE

   moistureOneSensorValue = analogRead(MOISTURE1);
   moistureTwoSensorValue = analogRead(MOISTURE2);

 // -------------------------------------------------------------------
 // Alarm Every Morning 7 AM Check If The Soil is DRY if DRY it will water
 // -------------------------------------------------------------------
if (t.hour == 0 && t.min == 49) {
  if(moistureOneSensorValue >= 700 ){
     RelayOne();

  }
  //if(moistureTwoSensorValue >= 700 ){
  //  RelayTwo();
 // }
}else{
   digitalWrite(RELAY1, 1); //CLOSE VALVE

}
// -------------------------------------------------------------------
// Alarm Every Afternoon 4 PM and Check if the soil is DRY if DRY it will water
// -------------------------------------------------------------------

if (t.hour == 16 && t.min == 00 && moistureOneSensorValue >= 700 ) {
  if(moistureOneSensorValue >= 700 ){
     RelayOne();
     digitalWrite(RELAY1, 1);
  }
  if(moistureTwoSensorValue >= 700 ){
     RelayOne();
  }
}
 readAllSensorStatus();

//Setting alarm/timer at every 2:32:53pm,
//in other words you can insert t.dow for every Thursday?, t.date for specific date?
//  {Serial.println("RELAY ON");

//Lets say that your component is wired to pin 99 and be switched on for 5 seconds,
//whatever you want to do with it

  // Wait one second before repeating :)
 // delay (1000);
 if(RELAY1 == LOW){
      digitalWrite(RELAY1, 1);
 }
}

void readAllSensorStatus(){
   unsigned long currentMillis = millis();

   interval = EEPROM.get(10,DELAYINTERVALOFDATA);
   if(currentMillis - prevMillis > interval) {
        prevMillis = currentMillis;
  //moistureSensorValue >= 700 DRY
  //
  //moistureSensorValue < 700 && moistuteSensorValue >= 300 Moist soil
  //
  //moistureSensorValue < 300 soggy soil
  //
  //Moisture
 moistureOneSensorValue = analogRead(MOISTURE1);
 moistureTwoSensorValue = analogRead(MOISTURE2);
 //Humidity and Temperature
 int chk = DHT.read11(DHT11_PIN);

 humiditySensorValue = DHT.humidity;
 tempSensorValue = DHT.temperature;
 //Water LEvel

  String LineOne = "-";
  String SensorValue = moistureOneSensorValue + LineOne + moistureOneSensorValue + LineOne + humiditySensorValue + LineOne + tempSensorValue;

  Serial.println(SensorValue);
  Serial.println(t.hour+LineOne+t.min);
   }

}
void closeSolenoidValve(){
   digitalWrite(RELAY1, 1); //Close

}
void RelayOne(){

//Serial.println("Valve Open");
digitalWrite(RELAY1, 0); //OPEN VALVE
digitalWrite(WATERFLOW1, HIGH);//READY WATER FLOW FOR SENSING
//WATER FLOW

if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.

    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    //Serial.print(pulseCount);

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.

    oldTime = millis();

   //  Serial.print("::");
    // Serial.print(oldTime);
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.

    flowMilliLitres = (flowRate / 60) * 1000;

    // Serial.print(flowMilliLitres);
    // Add the millilitres passed in this second to the cumulative total

    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL");

    setPointForN1 = EEPROM.get(0, WATEREQFORN1) / 2;

   if(totalMilliLitres >= setPointForN1 ){
       //closeSolenoidValve();
        digitalWrite(RELAY1, 1); //OPEN VALVE
      return loop();
      }

     // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }

  if(flowMilliLitres == 0){
     totalMilliLitres = 0;
  }

}

void RelayTwo(){

digitalWrite(RELAY2, 0);
digitalWrite(WATERFLOW2, HIGH);//READY WATER FLOW FOR SENSING
//WATER FLOW

if((millis() - oldTime2) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt2);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.

    flowRate2 = ((1000.0 / (millis() - oldTime2)) * pulseCount2) / calibrationFactor;

    //Serial.print(pulseCount);

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.

    oldTime2 = millis();

   //  Serial.print("::");
    // Serial.print(oldTime);
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.

    flowMilliLitres2 = (flowRate2 / 60) * 1000;

    // Serial.print(flowMilliLitres2);
    // Add the millilitres passed in this second to the cumulative total

    totalMilliLitres2 += flowMilliLitres2;

    unsigned int frac2;

    // Print the cumulative total of litres flowed since starting
    //Serial.print("  Output Liquid Quantity: ");             // Output separator
    //Serial.print(totalMilliLitres2);
    //Serial.println("mL");

   setPointForN2 = EEPROM.get(5, WATEREQFORN2) / 2;

   if(totalMilliLitres >= setPointForN2 ){
       Serial.println("Solenoid Close Set Point Reach");
       digitalWrite(RELAY2, 1); //CLOSE VALVE
    }

     // Reset the pulse counter so we can start incrementing again
    pulseCount2 = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt2, pulseCounter2, FALLING);
  }

  if(flowMilliLitres2 == 0){
     totalMilliLitres2 = 0;
  }

}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

void pulseCounter2()
{
  // Increment the pulse counter
  pulseCount2++;
}

```

# Answer
> 2 votes
This may not be a direct answer to the question, in the sense that I cannot tell you where exactly is the bug in your program. But hopefully it will help you getting a program that does work. I tried to find the bug, but it's quite hard. When reading your code, I could not stop asking myself “Why is this so convoluted?”. As a general rule, a simple program is easier to get working than a complex program. So I would ask you: why don't you try something simple instead?

The first thing that stroke me is that it seems you did not realize that the pulse count from the flow sensor is a direct measurement of the volume that went through it. You are timing the pulses in order to convert a pulse count into a pulse rate, then you convert that into a flow rate, then you integrate the flow rate rate to get the volume. All this is unnecessary complication: just count the pulses, the count **is** a water volume, albeit in an unusual unit.

Second thing is the logic of the whole program. It should be clear at first sight under what conditions the watering starts and under what conditions it stops. This is best done with a finite state machine with two state: either we are watering the plants or we are not. The state variable is then a boolean, and the logic could written along those lines:

```
void loop()
{
    // Should we start watering?
    if (!watering) {
        if (some_condition()) {
            start_watering();
            watering = true;
        }
    }

    // Should we stop watering?
    else {
        if (some_other_condition()) {
            stop_watering();
            watering = false;
        }
    }
}

```

Something explicit like this is generally easier to read, to understand and to debug. And likely to be less buggy in the first place.

Third thing, you seems to be doing too much stuff at once: controlling two different pumps, monitoring a DHT sensor, updating the setpoints... You should try to get a *minimal program* working, and only then start to add more stuff. The more functionality you add, the more complex the program gets. Don't expect something complex to just work: you should really get a simple version working first, and only then build on that.

Here is a proposed simplified version for your program. Absolutely not tested: it is just meant to get you started.

```
#include <EEPROM.h>
#include <DS3231.h>

const uint8_t RELAY_PIN = 7;
const uint8_t MOISTURE_PIN = A15;
const uint8_t FLOW_SENSOR_PIN = 2;
const uint8_t SENSOR_INTERRUPT = 0;
const float PULSES_PER_ML = (4.5*60)/1e3;  // 0.27 pulses/mL
const int MOISTURE_THRESHOLD = 700;

uint16_t wateringPulseCount;  // required pulses of water to deliver
DS3231  rtc(SDA, SCL);

/***********************************************************************
 * Handling of pulse counts.
 */

volatile uint16_t pulseCount;

// Interrupt handler.
void pulseCounter()
{
    pulseCount++;
}

// Safely read the current pulse count.
static inline uint16_t getPulseCount()
{
    noInterrupts();
    uint16_t pulseCountCopy = pulseCount;
    interrupts();
    return pulseCountCopy;
}

/***********************************************************************
 * Main program.
 */

void setup()
{
    pinMode(RELAY_PIN, OUTPUT);
    pinMode(MOISTURE_PIN, INPUT);
    pinMode(FLOW_SENSOR_PIN, INPUT);

    // Initialize the watering limit as a pulse count.
    uint16_t wateringVolume;
    wateringPulseCount = EEPROM.get(0, wateringVolume) * PULSES_PER_ML;
}

void loop()
{
    static bool watering;  // are we watering now?

    // Start watering at 07:00 if the soil is dry.
    Time t = rtc.getTime();
    if (!watering && t.hour == 7 && t.min == 0) {
        if (analogRead(MOISTURE_PIN) > MOISTURE_THRESHOLD) {
            pulseCount = 0;
            attachInterrupt(SENSOR_INTERRUPT, pulseCounter, FALLING);
            digitalWrite(RELAY_PIN, LOW);  // open valve
            watering = true;
        }
    }

    // Stop watering after the required volume.
    if (watering) {
        if (getPulseCount() >= wateringPulseCount) {
            digitalWrite(RELAY_PIN, HIGH);  // close valve
            detachInterrupt(SENSOR_INTERRUPT);
            watering = false;
        }
    }
}

```

Note that the pulse count has to be read with interrupts disabled, but you should **not** detach the interrupt handler. Detaching the handler means you will miss pulses, wheres disabling the interrupts only delays their handling until you enable them again. You won't miss pulses unless to keep the interrupts disabled for too long (which you shouldn't do).

---
Tags: arduino-uno
---


title: Advanced I/O shifting bits

text:
# Question
Title: Advanced I/O shifting bits
I wanted to tinker around more with the 8-bit shift register (74HC595) so I tried to make a simple LED display and after reading about some shift commands I got lost and didn't understand much...

Let's start simple...

from what I read -- you can send out Binary data 1s and 0s --- **does the shift regsiter read it as on and off?** the shift register I'm using which is probably the same thing with others but it has 8 pins that can be used as output --- **how does it output the data?** --- does it output (example) 10100110 which shifts to the right as if `00000000 -> 10000000 -> 11000000 -> 01100000 -> 00110000 -> 10011000 -> 0100110 -> 10100110` through the pins one by one? **like pin 1 would get *0* first then *0* will move to pin 2 and pin 1 will get a *1*?** (still using 10100110 by example above ^ )

Also what would the code look like? how does `shiftOut()` and `shiftIn()` work exactly? does all of this have something to do with `pulseIn()`? what do the bitwise operators like `>>` and `<<` or `~` to name a few exactly do?

let's say I made 8 leds hooked up to one of each output pin of the shift-register --- **how do I give data to the register?** what commands should I use to give data? --- from what I understood I can output `01011011` right? if so, **how does the shift-register output it?** and if (Assumingly) it does output it like on and off would it *eventually* turn out as if `LED1 = OFF` `LED2 = ON` `LED3 = OFF` `LED4 = ON` `LED5 = ON` `LED6 = OFF` `LED7 = ON` `LED8 = ON` as if I entered in `01011011`?

***tl;dr***

***how do 8-bit shift registers work and how do you make codes work with them*** xP

# Answer
> 2 votes
For the 74HC595 in combination with the Arduino, the best way to check is to use the default example by Arduino:

ShiftOut

With the ShiftOut you can shift the bits into the IC which will make the correct LEDs light up (or not).

Probably you can lit up a LED when passing a HIGH, but you will know very easily by trying the example and check some values/for loops to make them dynamically lighting.

Probably after playing with the example, it will give you much more insight than describing the details here.

Update:

* Try first with 00000000 and 11111111 and 8 leds, so you know if 0 will be OFF and 1 will be ON.
* Than try with eg 10101010 and 8 leds ... than you know if the first or the last will be on or off.
* pulseIn is unrelated
* The operators \>\> and \<\< are so called bit shift operators. Like 1 \<\< 3 gives 8, the binary value 0000001 is shifted 3 bits left resulting in 00001000 which has value 8.
* ~ is the not operator -\> which reverses bits.
* The shiftOut function can be used to send data to the 74HC595N.
* And to be honest, how does it work ... does it really matter for now? First see what the result is, how to use it. Later you can get into details. Start simple first.

---
Tags: arduino-uno, shift-register
---


# Question
Title: How do I use ultrasound to track a moving object?
I'm trying to create a small scale, dumb-downed version of the pitch tracking systems used to detect the speed and direction of baseballs.

I'm currently working with an HC-SRO4 sensor and an Arduino, but I'm unsure how to expand because a single sensor can't track an object that's not moving linearly (ie rising or falling as it moves). My team's idea was to make a grid of multiple HC-SRO4's connected to one Arduino, but we're worried that the delay will be too large if we try to turn them on sequentially to avoid interference.

How can we use ultrasound to track a moving ball?

# Answer
> 1 votes
Yes you can use ultrasound to track a moving target, but I really doubt it could be done with an Arduino.

You need to be able to ping the object at least 3 times in the time it takes to move your beam width. 3 times because if you know where it is with the centred ping you need to calculate the direction of travel by pinging either side of the centre to see if it is there.

You then need to track it in three dimensions. To do this you will need multiple sensors ideally at least 3 for 2D and 3 for 3D, so at least 6. 3 sensors in a plane will give you a reasonable degree of accuracy, but you beam width is key to this, the narrower the better.

Now you have to triangulate the position of the object, well actually work out the area of probability (for both planes) you never 'know' where it is really.

Oh and all 6 sensors need to have different frequencies to prevent interference, you then need to add in reflection processing to reduce false signals.

Its just much easier to buy a Pixy camera and download the software that they have for visually tracking your balls.

---
Tags: arduino-uno, time, hc-sr04
---


title: analogRead over a certain time

text:
# Question
Title: analogRead over a certain time
I would like to read an analog value using analogRead, save this value and compare it to an analogRead value 5 ms later. How would this code look? Because giving a variable the value of analogRead(A0); would mean it is constantly changing, making it impossible to compare two values.

thanks in advance

# Answer
The simplest and crudest method:

```
int val1 = analogRead(A0);
delay(5);
int val2 = analogRead(A0);

if (val2 > val1) {
    // It went up (for example).
}

```
> 2 votes

# Answer
You just need to copy the value into another before you overwrite it with `analogRead(A0)` and then compare those two variables.

```
int prev_value = 0;
int value = 0;
unsigned long prev_read_time = 0;

void setup() {
    prev_read_time = millis();
    value = analogRead(A0);
}

void loop() {
    if (millis() - prev_read_time > 5) {
        prev_read_time = millis();
        prev_value = value;
        value = analogRead(A0);
        if (prev_value != value) {
            // value changed
        }
    }
}

```
> 0 votes

---
Tags: analogread, software
---


# Question
Title: Arduino Uno as USB to Serial converter (bypass 328p)
I'm trying out computer to computer serial communication using 2 Arduino Unos (both connected to different computers). Right now, I use the Software Serial library, which redirects data from the SoftwareSerial ports to the hardware Serial (over USB to the PC).

Is there any way to bypass the 328p chip, and only use the 16U2, which works as a USB to Serial converter? Will the circuit in the diagram work? By connecting the GND to RST on both the Unos, the 328p gets disabled, which in theory should all me to directly tap into the serial line of the 16U2.

# Answer
> 1 votes
As per your diagram, ground the reset pin on both Arduinos and connect TX to RX on the one to RX to TX on the other. Alternatively, if your Unos have a socketed 328P, you can remove it.

(This answer summarized from the comments above in order to take it off the "unanswered" list.)

# Answer
> 0 votes
The circuit you have drawn will work for PC to PC coms. Essentially your connection diagram looks like this:

`PC1` -(USB)- `Arduino1` -(TTL serial)- `Arduino2` -(USB)- `PC2`

To answer your second question, you can bypass the 328p chip by removing them both as they are not needed. The 16U2 converts the USB to TTL serial which it provides to the Arduino on pins 0 and 1. Since the ATmega328p microcontrollers aren't being used (ie in reset state) then you may as well remove them and use them on another project.

---
Tags: arduino-uno, serial, atmega328, softwareserial, atmega16u2
---


title: NRF24L01+ Issues antenna

text:
# Question
Title: NRF24L01+ Issues antenna
I have 2x NRF24L01+ communicating but they are unreliable. It doesn't matter if they are right night to each other or 100ft away. For some odd reason when I place my hand on the antenna it work perfectly. Why would this be? I have one set up to send and one to receive. All I am sending from one to the other is a 3 digit number to turn on a relay.

# Answer
I found a solution. As the signals where too close I found where I could tone down the signal strength using:

```
   radio.setPALevel(RF24_PA_MIN);

```

Because I didn't want to loose long range capabilities too I send my packet out 4 times at this lower signal and then increase the strength back to max to send out another 4 packets. This way my close range and far range relay will receive the signal.
> 1 votes

---
Tags: arduino-uno, wifi, nrf24l01+, relay
---


# Question
Title: Arduino + L9637 K-Line reader - 10400 baud on SoftwareSerial?
I know this question has been asked many times before in different flavours, but all of the previous questions I have found seem to pre-date the current SoftwareSerial library, which afaik now (unlike when the previous questions were asked) allows any baud rate to be set as it calculates the values for the timings.

So I currently have the L9637 monolithic bus driver connected to pins D0 and D1 of my Arduino Uno. I am trying to create an ECU reader to communicate with my car over the KW1281 protocol, and from testing I have discovered I need to do the 5 baud init and then communicate at 10,400 baud.

First off I want to say I have successfully managed to run the 5 baud init. Now, I realise the pins (D0 & D1) are capable of hardware serial, however when trying to use the hardware serial I couldn't get any connection to the car. I think it's because the hardware serial doesn't like the pin modes to be changed after setup - however this is required to perform the 5 baud init. So I have decided to use the SoftwareSerial library for the following 10,400 baud communication.

With this library I successfully receive three (incorrect) response bytes from the ECU when setting a baud rate of 9600, however the response bytes - despite being correct in the number of them (3) - are wrong in terms of their value and seem to just be zero values.

Now as my car requires 10,400 baud communication, I instead setup the serial port to 10,400 baud. I know from experience that using 9600 baud will give incorrect response bytes and 10400 baud solves this. So I expected this would work and solve my problem, however it didn't. I still get 3 bytes containing 0. Just to be clear the three correct values should be: 55 01 8A

So I was wondering:

1. Am I right in assuming the SoftwareSerial library will work for any baud rate, even 10,400?
2. If yes to point 1, can anyone suggest why I might be getting data bytes containing 0 instead of the correct values?

As the full code is too long to post, the code for setting up the UART at 10,400, and then receiving the bytes is as follows:

```
#include <Wire.h>
#include <SoftwareSerial.h>

SoftwareSerial obd(pinKLineRX, pinKLineTX, false); // RX, TX, inverse logic
obd.begin(baudrate);

uint8_t data = 0;
int recvcount = 0;
char s[3];

while (obd.available())
{
   uint8_t data = obd.read();
   s[recvcount] = data;
   recvcount++;
}

```

And then to print the data I do the following:

```
#include <Adafruit_GFX.h>
#include <UTFTGLUE.h>

UTFTGLUE lcd(0x9488,A2,A1,A3,A4,A0);

char textout[30];
int xVal = 50;
cursorY = 10;
for (int i=0; i < size; i++)
{
  uint8_t data = s[i];

  sprintf(textout, "%i ", data);
  lcd.print(textout, xVal, cursorY);
  xVal += 10;
}

cursorY += 10;

```

The output on the LCD is

> 0 0 0

When it should be

> 55 01 8A

# Answer
> 1 votes
I've found 9600 baud to be the receive limit among *standard* baud rates (transmission can go faster). You're proposing an 8% increase over 9600 which sounds like it has a good chance of working but you'll need to experiment to find out.

You also asked why might your data (on the LCD) be wrong.

You'll do your sanity a big favor and do two separate experiments:

* First, get known data (literal strings or terminal input) to display correctly on your LCD, before you try to use the LCD to confirm or debug your communications.
* Second, get SoftwareSerial running (or find out that it doesn't...) at 10400 baud. In fact try to get up to, say, 12000 baud, or at least push the rate to find out where it starts to fail so you know how much head-room you'll have at 10,400. The simplest way would be to use two Arduinos if you have access to another one. Again, use your terminal or some literal strings on MCU 'A' to send to MCU 'B', MCU 'B' should receive a line and echo it back to 'A', who prints it on its terminal. Printing it on 'B's terminal wouldn't be a bad idea either.

You'll be in a lot better position to combine the two techniques once you have confidence that each one works; especially if you copy-and-paste known-working code segments.

# Answer
> 0 votes
I tried using MIDI data with the software library. However, I also got problems with missing and/or corrupted messages. MIDI has a fixed baudrate of 31,250 baud. As long as I did not sent too much, everything was ok, but sending continuous messages (within the 31,250 baud rate spec) I got into problems. It seems that the input buffer was too full and/or no time to process them.

The default buffer for the serial (software serial) buffer was 64 bytes. I increased it to 128, but saw no difference. Making the buffer higher probably just would delay the time until messages are corrupted.

What you can do is:

* Use a non Arduino device with multiple UARTs (no experience with that)
* There seems to exists a 328PB version of the Uno which has two UARTs (but it maybe a kind of niche device, possibly with support problems)
* What I did was using a Mega, it has 4 UARTs.
* Using multiple Uno's and/or Mega's connected to eachother, giving 1 resp. 4 UARTs

---
Tags: arduino-uno, softwareserial, baud-rate
---


# Question
Title: Switch setting 'running' state boolean doesn't hold
I have a rotary encoder and I want to use the switch to stop the rest of my code running, essentially switching off what I have going on.

I have this

```
boolean running = true;

void setup() {
  pinMode(swPin, INPUT);
  digitalWrite(swPin, HIGH);;
}

void loop() {

  if(digitalRead(swPin) == LOW) {
    running = !running;
  }

  if(running) {
    ...
  }
}

```

When I enter the if statement catching the switch press running does become false and the rest of the code is stopped. However, once released; running is becoming true again and the rest starts again.

I guess it is because the rotary encoder isn't fixed in the LOW state but I expected the running variable to be set to false and remain since it is declared outside of the loop().

Any guidance would be much appreciated!!

# Answer
Thanks to @Manjenko's comment I was able to see my error.

Here is my solution:

```
boolean running = true;
int swReading;
int swPrevious = LOW;

void setup() {
  pinMode(swPin, INPUT);
  digitalWrite(swPin, HIGH);;
}

void loop() {

  swReading = digitalRead(swPin);

  if(swReading == LOW && swPrevious == HIGH) {
    running = !running;
  }
  swPrevious = swReading;

  if(running) {
    ...
  }
}

```
> 0 votes

---
Tags: arduino-uno, rotary-encoder, switch
---


title: Servomotor and music shield

text:
# Question
Title: Servomotor and music shield
I’m trying to make an art sculpture, with an Arduino-uno, a servomotor and a seeduino musicshield v2.0. I’m making the servo motor moving a stick with the attached fans of the servo, and I want to synchronize the servo motor with the music shield and when the motor is stopped(about one minute), the music(about one minute of music) will play and when de motor is moving the music will be stopped.

I'm super noobie with the code. I tried something like this but, is not moving at all, neither my servo or my musicshield when I write this:

```
#include <SD.h>
#include <SPI.h>
#include <arduino.h>
#include <MusicPlayer.h>

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
  Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
}
void loop() {
  mover();
  if ( val == 90) {
    music();
  }
}

void mover () {
  val = 0;// start point
  myservo.write(val);
  delay(800);

  val = 90;
  myservo.write(val);
  delay(60000);//wait for 1 min
}

void music () {

  player.play();
}

```

when I write this my servo moves, but obviously my music wouldn't play

```
#include <SD.h>
#include <SPI.h>
#include <arduino.h>
#include <MusicPlayer.h>

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
 Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
 }

void loop() {
mover();

 }

 void mover () {
val = 0;// start point
myservo.write(val);
delay(800);

val = 90;//
myservo.write(val);
delay(60000);//wait for 1 min
}

void music () {

  player.play();  //do some leisurely job
}

```

And the music will play when I write this, obviously the servomotor don't move, so I'm think I have a problem mixing my servomotor and the musicshield(seeeduino music shield v2.0, and I want the music start when my servo motor is in this point of val=90 delay(60000)

```
 #include <SD.h>
    #include <SPI.h>
    #include <arduino.h>
    #include <MusicPlayer.h>

    #include <Servo.h>
    Servo myservo;

    int val;//for the servo

    void setup() {
      //setup for the music shield
     Serial.begin(9600);
      player.begin();  //will initialize the hardware and set default mode to be normal.
      player.addToPlaylist("a.mp3");
      //setup for the servo
       myservo.attach( 9 );
      }

    void loop() {

   player.play();
     }

    void mover () {
    val = 0;// start point
    myservo.write(val);
    delay(800);

    val = 90;//
    myservo.write(val);
    delay(60000);//wait for 1 min
    }

```

# Answer
> 0 votes
Is this the MusicPlayer.h that you have? https://github.com/Seeed-Studio/Music\_Shield

From the description it says:

> The music player reads data from SD card and then feed into the VS1053 chip via SPI bus. This is done in TIMER1's ISR with a interval of 2ms. This job has a high priority and uses the cpu exclusively. In the spare cpu time, player does some process control, like play/pause.

That's the same timer that Servo.h uses. So the two libraries are not compatible. You could try using ServoTimer2 library or rewriting this library to get the 2ms timer with Timer 2.

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


# Question
Title: Unable to upload to Arduino Due using version 1.6.8 of SAM tools; bossac.exe throwing an error
I can successfully see the Arduino Due when I plug it in. I can compile the code, but when I attempt to upload it to the board I get the following error:

`C:\Users\user\AppData\Roaming\Arduino15\packages\arduino\tools\bossac\1.6.1-arduino/bossac.exe
 -i -d --port=COM4 -U false -e
 -w true
 -b C:\Users\user\AppData\Local\Temp\build6683778295083335366.tmp/_50key_driver.cpp.bin
 -R bossac.exe: extra arguments found
 Try 'bossac.exe -h' or 'bossac.exe --help' for more information`

# Answer
I finally figured out the problem. This occurred on both a Mac and PC (Windows 10).

This error occurred because of the **true** after the **-w** switch. To fix it I modified the package to tell the IDE not to use that switch.

1. Go to: `%USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8` (where `%USER_PROFILE%` is your windows user directory, for me it was `C:\Users\user`) in Windows Explorer.
2. Make a copy of the platform.txt file (I called it platform\_backup.txt).
3. Open the file platform.txt with Word Pad (it had Unix line endings in my environment), search for the string:

`tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w {upload.verify} -b "{build.path}/{build.project_name}.bin" -R`
4. This was 3rd line from the bottom for me, and remove the text between the quotes "{upload.verify}". It should now look like this:

`tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w -b "{build.path}/{build.project_name}.bin" -R`
5. Restart the IDE so it can re-read the file you just edited. You'll now be able to upload to the Due.
> 3 votes

# Answer
Tim's solution is also applicable to Version 1.6.9 of the SAM tools. I just installed it in my Arduino IDE V1.6.8 and had the same parameter problem as originally reported. Following Tim's solution fixed the problem right away. As this is clearly a configuration issue on the Arduino IDE side, it should happen on any supported Windows platform, mine was Windows 7. The only difference I encountered was the path to the SAM tools directory. On my Enterprise version of Win7, the path was not in `AppData\Roaming` but in `AppData\Local` , so `%USER_PROFILE%\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\` for the full pathname.
> 0 votes

# Answer
There's a better option:

(For Windows)

1/ Download the latest IDE release.

2/ Uninstall the IDE completely.

3/ Reboot PC

4/ Go to %USER\_PROFILE%\AppData\Local\Arduino15 and delete it (the entire folder). If the path doesn't match then find it in AppData folder, it's in there somewhere.

5/ Reinstall the IDE, problem fixed.
> 0 votes

# Answer
I tried this solution in linux Fedora, it worked fine, but the location of the file "platform.txt" was `/home/{user}/.arduinoxx/packages/arduino/hardware/sam`
It is a hidden folder, so make it visible so you can handle it. No sudo access was necessary.
> 0 votes

---
Tags: arduino-due
---


# Question
Title: My button stays on high if I press it once, what did I do wrong?
If I press my button once, I get characters on all of the 32 character places and I get an infinite tone with my piezo. Can someone help me with this?

```
#include <LiquidCrystal.h>

const int buttonPin = A0;
int buttonState = 0;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte run1c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B01110,
  B11100,
  B01110,
  B10010,
};

byte run2c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B11100,
  B01110,
  B11100,
  B10010,
};

byte jumpc[8] = {
  B01100,
  B01100,
  B00000,
  B11110,
  B01101,
  B11111,
  B10000,
  B00000,
};

byte jumpLowerc[8] = {
  B01110,
  B11100,
  B01110,
  B10000,
  B00000,
  B00000,
  B00000,
  B00000,
};

byte groundc[8] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
};

byte rightGroundc[8] = {
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
};

byte leftGroundc[8] = {
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
};

void setup() {
  lcd.createChar(0, run1c);
  lcd.createChar(1, run2c);
  lcd.createChar(2, jumpc);
  lcd.createChar(3, jumpLowerc);
  lcd.createChar(4, groundc);
  lcd.createChar(5, rightGroundc);
  lcd.createChar(6, leftGroundc);
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    tone(8, 400);
    lcd.setCursor(1,0);
    lcd.write(byte(2));
    digitalWrite(buttonState, LOW);
  } else {
    lcd.setCursor(1,1);
    lcd.write(byte(0));
  }
}

```

# Answer
> 0 votes
From what I can tell from your drawing, you have both sides of your button tied to 5V. The green wire on one side and the blue wire through the resistor on the other. So yes, the button will always read HIGH.

Instead, remove the resistor, tie one side of the button to the pin and the other side to ground. Use INPUT\_PULLUP in your pinMode cal instead of just INPUT. Now a pressed button will read LOW and not pressed will read HIGH, so you'll have to reverse your logic in your code. But the wiring will be much nicer.

# Answer
> 0 votes
In your code you check the button state and if it is high you set the tone.

In the else section you do nothing with the tone.

Hence, once on, it will always stay on.

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


# Question
Title: Can I include a header file into a new header file?
Can I include a header file into a new header file that I created? I put `#include <MCP23S17.h>`. I want to create a another header file.

# Answer
Why not just include both in the final program?

Happens all the time.

DHT.h needs AdaFruit\_Sensor.h, for instance, so you just include both.

First AdaFruit then DHT
> 3 votes

# Answer
Yes, a header can include another header. But if you are using the Arduino IDE and the headers aren't in the same folder, then you'll also need an #include line for it in the .ino file.
> 2 votes

---
Tags: arduino-uno, programming
---


# Question
Title: Can i create a function inside of void setup()?
Can i create a function inside of void setup() to recall in loop() function

# Answer
No. You do not create functions within functions.

You can create a function, and then call it both from `setup()` and `loop()` if you so wish.
> 4 votes

# Answer
Defining a function within a function is not supported in C or C++. If it were supported in a way consistent with the rest of the language, the inner function would be local to the outer function, just as local variables are, so not callable or even visible from outside the outer function.

Your loop() function (or any other function) could, however, call the setup() function as long as you want to execute setup() again in its entirety. That means that any initialization you perform in setup() would be repeated each time you call it.
> 1 votes

# Answer
You can create functions within a function if the particular c compiler supports it - gcc, the compiler used by arduino, does. But not all c compilers support that.

Whether you can create a function within a function that recalls loop() depends on your meaning of "recall".
> 0 votes

# Answer
You have asked two questions here. In the title, can you define a function inside of setup(): Yes.

But that is the "scope" of where it can be used.

In Loop() it won't exist, ("xxx undefined in this scope") so the answer to what you ask in the text is No.
> 0 votes

---
Tags: arduino-uno, programming
---


# Question
Title: Johnny-five driving LCD Matrix or call Arduino library from Johnny-five
I would like to know if it's possible to drive an LED Matrix like this one with johnny-five. If not, how can i call Arduino library/code from johnny-five.

If I Write method on sketch into the Arduino, can I call them from J5 REPL?

# Answer
> 1 votes
After research, it can't be done, as J5 use firmata to drive the Arduino, the only way is to write a library to use with.

---
Tags: arduino-uno, rgb-led, johnny-five
---


title: Programming Arduino via ICSP

text:
# Question
Title: Programming Arduino via ICSP
I'm trying to programming Arduino Nano with another Arduino Nano via ICSP. I have a 6-pin cable directly connected to the ICSP's pin of the second board:

```
ICSP NANO ISP 1
pin1 pin2 pin3
pin4 pin5 pin6

ICSP NANO 2 (to be programmed)
pin1 pin2 pin3
pin4 pin5 pin6

```

I have correspondingly wired pin 1 (ICSP) of nano1 to pin 1 (ICSP) Nano 2, pin 2 (ICSP) of nano 1 to pin 2 (ICSP) Nano 2, etc.

I make this step before flashing: getting the Arduino ISP with example sketch ArduinoISP, plug off the Arduino ISP and attach the 6-pin cable to the ICSP port of the second board, plug Arduino ISP to the USB port, in the *Tools* menu select *Arduino as ISP*, load with external programmer, and fail...

This is the log:

```
avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM12
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x000000 (retrying)

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

avrdude: Device signature = 0x000000 (retrying)

Errore durante il caricamento dello sketch
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

# Answer
> 1 votes
I suggest you to try and read the Arduino page about ArduinoISP.

Particularly, you will notice that pins 11, 12, 13 and Vcc and GND are all common, BUT the reset pin is not common to both boards. So I suggest you to detach the pin 5 of ICSP from the ArduinoISP board and connect it to its pin 10. Or, if you prefer, connect

```
ISP - Target
+5V - +5V
GND - GND
11  - 11
12  - 12
13  - 13
10  - RST

```

Then try again

---
Tags: programming, icsp
---


# Question
Title: Read only selected Packet SoftwareSerial
I am reading data from RS485 which is in the following format:

```
void sendkwh()
{
  RS485Serial.write((byte)0x01); // Meter Address
  RS485Serial.write((byte)0x03); // Read Function Code
  RS485Serial.write((byte)0x40); // Register Address Variable (Start address high bit)
  RS485Serial.write((byte)0x34); // Register Address Variable (Start address low bit)
  RS485Serial.write((byte)0x00); // Register Quantity (High Bit)
  RS485Serial.write((byte)0x02); // Register Quantity (Low Bit)
  RS485Serial.write((byte)0x90); // CRC check code (CRC code Low bit)
  RS485Serial.write((byte)0x05); // CRC check code (CRC code High bit)
}

```

and I need to read only the 4th and 5th frame of the packet. I am doing it the following way:

```
RS485Serial.listen();
  if (RS485Serial.available() > 0)
   {

    if(RS485Serial.read() == 0x01)
    {
    for(int i=0; i<4; i++) {

   byte discard = RS485Serial.read();

   }
    byteReceived = RS485Serial.read(); // 4th frame
    byteReceived2 = RS485Serial.read(); // 5th frame

```

which is working fine. I wanted to know if there is a method to discard the packets without loop?

As in I have changed the `sendkwh()` as below:

```
byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };
RS485Serial.write(SendKWh, sizeof(SendKWh));

```

But don't know how to proceed with tapping the 4th and the 5th frame. Your help is appreciated.

# Answer
> 3 votes
Your reading methodology is flawed from the start and you need to completely change how you do things. First off, you wait until there is *at least* one byte in the incoming buffer, then if that byte is `0x01` you then try and read 5 more bytes - even if there is only (say) 2 bytes in the buffer.

Instead you need to set up a *sliding window* for receiving the data. A sliding window is basically an array that is the same size as the data you are receiving, and as bytes become available they work their way down from the "top" to the "bottom" of the array. When the contents of the array match a certain pattern you know it is a "good" packet and you can use the data form it.

For example, you may have something like:

```
uint8_t window[8];

void loop() {
    if (RS485Serial.available()) {
        uint8_t b = RS485Serial.read();
        // Slide the contents of the array down
        for (uint8_t i = 0; i < 7; i++) {
            window[i] = window[i+1];
        }
        // Insert at the top
        window[7] = b;

        // If the array starts with 0x01,0x03,0x40,0x34...
        if ((window[0] == 0x01) && (window[1] == 0x03) &&
            (window[2] == 0x40) && (window[3] == 0x34)) {
            // Do something with window[4] and window[5]
        }
    }
}

```

You could also add checking the CRC to that by comparing the calculated CRC for the incoming packet (however that is done in this protocol) with the last two bytes of the array.

---
Tags: arduino-nano, softwareserial
---


# Question
Title: Decoupling cap for self-powered LED matrix and LED strip
Should I add a decoupling capacitor to my RGB 16x32 LED matrix powered directly via the 5V pin?

When I display a spectrogram, the current load is fluctuating quickly in the **100-250 mA** range (on average, the full range is 50-300 mA).

If yes, which capacitor should I pick for this purpose?

I have 0.01 μF, 0.1 μF ceramic and 1 μF, 2.2 μF, 4.7 μF, 10 μF, 100 μF electrolytic caps.

EDIT: I'm also interested to know about this WS2812B LED strip i've connected to the 5 V pin to another Arduino.

After reducing the brightness it has similar current consumption and fluctuation of the LED matrix.

In this tutorial they suggest to add a 1000 μF cap, but in my case the currents are much smaller.

# Answer
> 0 votes
No, there is no need. The matrix already has plenty of decoupling on it, including a large electrolytic for the incoming power and a small ceramic on each of the chips.

---
Tags: power, led, capacitors
---


# Question
Title: After update via ICSP can't use usb for Serial Reading and Usb for programming board
after update software on my arduino Nano board via ICSP i can't use USB for serial monitor and update software, why?

# Answer
> 4 votes
Assuming you have reprogrammed the Arduino Nano's Atmel processor (an ATmega328) directly using the processor's ICSP pins, you may have erased the Arduino boot loader from the processor. In such a case you no longer have an Arduino. Rather you have an ATmega328 processor surrounded by some hardware.

To recover you need to reprogram the ATmega328 processor with the Arduino boot loader.

---
Tags: arduino-nano, icsp
---


title: Issue with Speck cipher on Arduino UNO

text:
# Question
Title: Issue with Speck cipher on Arduino UNO
I found a library for the Speck cipher here: https://github.com/Chien-Ning/ArduinoCrypto

And I'm trying to use but haven't had much luck. My code is the following:

```
#include <SPECK_AVR.h>
#include <SPECK_spec.h>

#include "SPECK_AVR.h"

void setup() {
  // put your setup code here, to run once:

  SpeckTxtLen = 32;
  SpeckKeyLen = 64;
  speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

  speckKey();
  speckEnc();

  Serial.println("");
  for (int i = 0; i < SpeckTxtLen/8; i++){
  Serial.print(speckTxtKey[i], HEX);
  Serial.print(", ");
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

```

And I'm getting this error:

```
error: lvalue required as left operand of assignment

```

and

```
error: expected primary-expression before ']' token

```

Do you think I'm missing something in the usage of this library?

Thanks in advance

# Answer
> 3 votes
```
speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

```

That's not how you assign an array.
And you never defined a type for the array.

It sould be:

```
byte speckTxtKey[] = {0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00};

```

**EDIT**:

I checked the source of the library to figure out how to use it, but it doesn't seem the library is meant for actual use.

`SpeckTxtLen` and `SpeckKeyLen` are macros inside *SPECK\_AVR.h*, which are supposed to be changed there, not in your code.

The library also defines `speckTxtKey` inside *SPECKenc\_AVR.cpp* with predefined test data based on the chosen length.

This library looks like a test implementation of the speck cipher, which was just dumped onto GitHub.

---
Tags: arduino-uno
---


# Question
Title: Pass changing analog value from void loop to library .h file
How would I go about passing a void loop analog read value to a library .h file? I've tried it but it only reads the pot position as soon as I plug the arduino in and does not change once booted up.

arduino main sketch file code;

```
#include "Arduino.h"
#include "common.h"
#include "synth.h"
#include "serial-in.h"
#include "audio-out.h"

void setup() {
  Synth<0>::initialize();
  SerialIn<0>::open();
  AudioOut<0>::open();
}

void loop() {
  int val = analogRead(A0);
  int val1 = analogRead(A1);
  int val2 = analogRead(A2);
  int val3 = analogRead(A3);
  int val4 = analogRead(A4);
  while (true) {
    if (SerialIn<0>::available()) {
      uint8_t b = SerialIn<0>::read();
      Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
  }
}

```

.h file code

```
#pragma once

// #define private public  // for tests

#include "common.h"

// associations of units
#define IOsc        Osc
#define IFilter     Filter
#define IAmp        Amp
#define IEG         EG
#define IVoice      Voice
#define ISynthCore  SynthCore

#include "osc.h"
#include "filter.h"
#include "amp.h"
#include "eg.h"
#include "voice.h"
#include "synth-core.h"

template <uint8_t T>
class Synth {
public:
  INLINE static void initialize() {
    ISynthCore<0>::initialize();
    int val = analogRead(A0);
    int val1 = analogRead(A1);
    int val2 = analogRead(A2);
    int val3 = analogRead(A3);
    int val4 = analogRead(A4);
    // Preset
    ISynthCore<0>::control_change(OSC_MODE      , 0  );
    ISynthCore<0>::control_change(OSC_COLOR     , val);
    ISynthCore<0>::control_change(MOD_RATE      , 8  );
    ISynthCore<0>::control_change(MOD_DEPTH     , val1);
    ISynthCore<0>::control_change(LPF_CUTOFF_ENV, val2);
    ISynthCore<0>::control_change(LPF_RESONANCE , val3);
    ISynthCore<0>::control_change(ENV_A         , val4 );
    ISynthCore<0>::control_change(ENV_D_R       , 1 );
  }

  INLINE static void receive_midi_byte(uint8_t b) {
    ISynthCore<0>::receive_midi_byte(b);
  }

  INLINE static int8_t clock() {
    return ISynthCore<0>::clock();
  }
};

```

# Answer
> 0 votes
First of all, the `while(true)` loop in the `loop` function is wrong. You will need to put in the `loop` only the code which needs to be repeatedly called. So

```
void loop() {
  if (SerialIn<0>::available()) {
    uint8_t b = SerialIn<0>::read();
    Synth<0>::receive_midi_byte(b);
  }

  int8_t level = Synth<0>::clock();
  AudioOut<0>::write(level);
}

```

Then, I haven't understood where the analog read values are used. Moreover the fact that in the initialization you read the analog values and in the loop you expect them to be passed is inconsistent. From what I read, the values should be passed to `control_change`; you can do one of these things, in my opinion:

1) manage the analog reading from the main:

```
void setup() {
    Synth<0>::initialize(analogRead(A0), analogRead(A1), analogRead(A2), analogRead(A3), analogRead(A4));
    SerialIn<0>::open();
    AudioOut<0>::open();
}

void loop() {
    Synth<0>::change_OSC_COLOR(analogRead(A0));
    Synth<0>::change_MOD_DEPTH(analogRead(A1));
    ...

    if (SerialIn<0>::available()) {
        uint8_t b = SerialIn<0>::read();
        Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
}

// in h file

INLINE static void initialize(int val, int val1, int val2, int val3, int val4) {
    ISynthCore<0>::initialize();

    change_OSC_MODE(0);
    change_OSC_COLOR(val);
    change_MOD_RATE(8);
    change_MOD_DEPTH(val1);
    change_LPF_CUTOFF_ENV(val2);
    change_LPF_RESONANCE(val3);
    change_ENV_A(val4);
    change_ENV_D_R(1);
}

INLINE static void change_OSC_MODE(int value) {
    ISynthCore<0>::control_change(OSC_MODE, value);
}

INLINE static void change_OSC_COLOR(int value) {
    ISynthCore<0>::control_change(OSC_COLOR, value);
}

INLINE static void change_MOD_RATE(int value) {
    ISynthCore<0>::control_change(MOD_RATE, value);
}

...

```

or, alternatively,

```
...
void loop() {
    Synth<0>::change_param(OSC_COLOR, analogRead(A0));
    Synth<0>::change_param(MOD_DEPTH, analogRead(A1));
    ...

}

// in h file

INLINE static void initialize(int val, int val1, int val2, int val3, int val4) {
    ISynthCore<0>::initialize();

    change_param(OSC_MODE, 0);
    change_param(OSC_COLOR, val);
    ...
}

INLINE static void change_param(uint8_t param, int value) {
    ISynthCore<0>::control_change(param, value);
}

```

(I prefer the firsti since you can prevent the user from using some parameters)

2) manage the analog reading from the library:

```
void setup() {
    Synth<0>::initialize();
    SerialIn<0>::open();
    AudioOut<0>::open();
}

void loop() {
    Synth<0>::updateAnalog();

    if (SerialIn<0>::available()) {
        uint8_t b = SerialIn<0>::read();
        Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
}

// in h file
INLINE static void initialize() {
    ISynthCore<0>::initialize();
    updateAnalog();
}

INLINE static void updateAnalog() {
    int val = analogRead(A0);
    int val1 = analogRead(A1);
    int val2 = analogRead(A2);
    int val3 = analogRead(A3);
    int val4 = analogRead(A4);
    ISynthCore<0>::control_change(OSC_MODE      , 0  );
    ISynthCore<0>::control_change(OSC_COLOR     , val);
    ISynthCore<0>::control_change(MOD_RATE      , 8  );
    ISynthCore<0>::control_change(MOD_DEPTH     , val1);
    ISynthCore<0>::control_change(LPF_CUTOFF_ENV, val2);
    ISynthCore<0>::control_change(LPF_RESONANCE , val3);
    ISynthCore<0>::control_change(ENV_A         , val4 );
    ISynthCore<0>::control_change(ENV_D_R       , 1 );
}

```

Each method has advantages or disadvantages... You should pick the one more suitable for you

# Answer
> 0 votes
> How would I go about passing a void loop analog read value to a library .h file?

What you wanted to do makes little sense. But it is certainly doable. The simplest would be to use an "extern" variable as a bridge.

---
Tags: library, analogread
---