# Question
Title: How do I check if a password is right? (keypad input)
Im having a problem with my arduino code.Im trying to make an alarm system with a pir sensor.So when the pir activates and the buzzer starts buzzing i want to be able to type a set password in the keypad and the buzzer should stop buzzing. since my passcode is 4-digit (1331) I wrote this code, but it\`s not working.

```
 while(i<=4,i++)
{
char key = keypad.getKey();

pass.append(key);
}
if(pass.evaluate())
{
  digitalWrite(buzzer, LOW);
    keypad.waitForKey();
    delay(6000);
}

```

My idea is that the program checks 4 times for the pressed key and adds it to the guessed password (im using the password library and the password is defined as well as int i=0;) But for some reason when I type 1331 the buzzing continues. Please help me with that project and excuse my grammar, English is not my native language.

edit: the full code:

```
#include <Password.h>
Password pass = Password( "1331" );

#include <Keypad.h>
int sensor = 11;
int buzzer = 10;
int i = 0;

const byte rows = 4; //four rows
const byte cols = 4; //four columns
char keys[rows][cols] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup() {
pinMode(sensor, INPUT);
pinMode (buzzer, OUTPUT);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
keypad.waitForKey();
digitalWrite(buzzer,HIGH);
  delay(125);
  digitalWrite(buzzer, LOW);
  delay(6000);

}

void loop() {

  char state = digitalRead(sensor);
  if (state == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    while(i<4,i++)
    {
    char key = keypad.getKey();
    //keypad.waitForKey(); not sure if i should use that

    pass.append(key);
    }
    if(pass.evaluate())
    {
      digitalWrite(buzzer, LOW);
        keypad.waitForKey();
        delay(6000);
    }

  }
      }

```

# Answer
1. Without knowing how the pass.\* works, it will be impossible to pinpoint the problem.
2. 'key' gets an ASCII value. Is that would you are expecting?
3. Does pass.\* reset (start over) once 4 digits?
4. Just a guess, but I believe that \*.waitForKey() does not consume the key.
5. The algorithm only *gets* the key four times; then, it checks.
> 1 votes

# Answer
This is completely the wrong way of doing a loop. Since Arduino uses C++ I made this test program:

```
#include <stdio.h>

int main (void)
  {
  printf ("starting\n");
  int i = 0;
  while(i<=4,i++)
     {
     printf ("%i\n", i);
     }
  printf ("done\n");
  return 0;
  }

```

This prints:

```
starting
done

```

Note that the loop is executed **zero** times. This is because you used the "comma operator".

From https://en.wikipedia.org/wiki/Comma\_operator you can see:

> In the C and C++ programming languages, the **comma operator** (represented by the token `,`) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

In other words, your loop adds one to `i` and checks if it is zero (before adding one). Thus the loop terminates immediately.

A better construct would be:

```
for (i = 0; i < 4; i++)
   {
   // whatever
   }

```

That is the standard C/C++ way of doing a loop a fixed number of times.

---

Also, most keypad libraries return `NO_KEY` if the user hasn't pressed a key.

You should test if `keypad.getKey()` returns `NO_KEY` and if so do nothing.

All your code would have done (if it had executed 4 times) was get 4 times `NO_KEY` (in a few microseconds) which would not be the correct password.
> 1 votes

# Answer
This is classical indexing problem:

while with \<= 4 actually runs five (5) rounds.

So, use \< 4.
> 0 votes

# Answer
In case anyone was wondering, heres the code I came up with and now it works.

```
#include <Keypad.h>
int sensor = 11;
int buzzer = 10;
int red = 12;
int i = 0;
String Pass = "1331";
String tempPass = "";

const byte rows = 4; //four rows
const byte cols = 4; //four columns
char keys[rows][cols] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup() {
pinMode(sensor, INPUT);
pinMode (buzzer, OUTPUT);
StartingBuzz();
keypad.waitForKey();
digitalWrite(red,HIGH);
digitalWrite(buzzer,HIGH);
  delay(200);
  digitalWrite(buzzer, LOW);
  delay(60000);
}

void StartingBuzz()
{
digitalWrite(buzzer, HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer, HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
  }

void UnlockBuzz()
{
  delay(200);
       tone(buzzer,3250,200);
       delay(300);
       tone(buzzer,3500,200);
       delay(300);
       tone(buzzer,4000,200);
  }

void loop() {
  i=0;//resets the password-checking loop.
  tempPass = "";//resets the guessed password.
  char state = digitalRead(sensor);
  if (state == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    A:
    {
    while(i < 4)
    {
    char key = keypad.getKey();
    if(key != NO_KEY)
    {
      tempPass += key;
      i++;
      }
    }
    }
    if(Pass == tempPass)
    {
      digitalWrite(buzzer, LOW);
      digitalWrite(red, LOW);
      UnlockBuzz();
      keypad.waitForKey();
      digitalWrite(buzzer,HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      digitalWrite(red, HIGH);
      delay(60000);
    }
    else
    { tempPass = "";
       i=0;
      goto A;
      }

  }
}

```
> 0 votes

---
Tags: input
---


title: fast reacting color sensor

text:
# Question
Title: fast reacting color sensor
I want to recognize the color of passing by objects. The speed of the objects is quite fast, arround 1 meters per second maybe a bit slower. The objects can have only two colors, as an example red or green and the distance between the sensor and the passing by objects is only a few millimeter.

I want to use a color sensor or multiple sensors of the same type bheind each other and timed so that at least one of them take a measurement of the object. But I dont know which sensor I should take.

# Answer
I don't think this question has anything to do with Arduinos, at least not the way its currently written, but the answer is very simple look at the Pixie Cam. http://charmedlabs.com/default/pixy-cmucam5/
> 1 votes

---
Tags: sensors
---


title: Arduino Uno R3 USB is not working

text:
# Question
Title: Arduino Uno R3 USB is not working
I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is *on* and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.

I tried `lsusb` and I checked `/dev/ ports`. Also, I couldn't find \`ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.

I thought it was a bootloader problem, and I got a *new ATmega328P chip board*. It is getting power on and the LED is blinking, but the port is not mounted. I tried with `lsusb` and also `ls /dev/ttyACM*` with no result.

# Answer
You could try to flash the firmware of the USB controller.

General steps for Arduino R3 are:

1. Put the Arduino in DFU mode (the R3 does *not* require soldering for that)
2. Flash the firmware using:

```
dfu-programmer atmega16u2 erase
dfu-programmer atmega16u2 flash Arduino-usbserial-atmega16u2-Uno-Rev3.hex
dfu-programmer atmega16u2 reset

```

The package "dfu-programmer" is most likely available for your distribution.

If you have to build it from source, because your DFU programmer does not know the ATmega16U2 yet, you will need to install libusb-dev (on Debian-based systems).

Useful links for that:

A useful search term for that is `Arduino R3 DFU-programmer`.
> 3 votes

# Answer
Maybe you need to "reflash" the FTDI firmware. Sorry, I'm very bad in Linux. To do this, you'll need some software and a HEX file. Check this video on YouTube:

*ARDUINO- Upgrading USB FIRMWARE using FLIP*

And download the *arduino\_usbtoserial.hex* file.

If it doesn't work, and if your Arduino Uno has the ATmega328P chip as DIP, try to change the ATmega328P chip in the board. Remove this chip carefully. Put another chip in with the bootloader and test.
> -1 votes

---
Tags: arduino-uno, atmega328, linux
---


title: Reading multiple cases on Serial

text:
# Question
Title: Reading multiple cases on Serial
I am using a Leonardo board and am testing the APIs in the `Serial` type. The board is talking to a screen using serial.

The pseudo code is as follows (I show code relevant to Serial):

```
void setup(void) {
    Serial.begin(115200);
}

void loop(void) {

    if(Serial.available())
    {

        if (Serial.find(0x30))
        {
             func1();
        }

        if (Serial.find(0x31))
        {
             func2();
        }

    }

 }

 void func1()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

 void func2()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

```

I test using the Arduino IDE (1.8.0) and its Serial Monitor. When I send 0x30 over serial, the first if case gets triggered to invoke `func1`, but when I send 0x31, I cannot get the second if case (`func2`) to get triggered. This even happens when I test 0x31 first; the second if case never gets triggered. Can someone tell what I am doing wrong here and what is the right way to use serial ?

**Edit** For testing, one can use the pseudo code itself; I tested using different number of LED blinks in func1 & func2, and the problem still holds.

**Edit 2** Based on Dave's answer, I tried a test with serial using sample code from

I did another test where I used the sample loop code for read (https://www.arduino.cc/en/Serial/Read) and tried typing 0 or 1 through serial monitor. I observed the following:

```
// Typed 0
I received: 48
I received: 13
I received: 10
// Typed 1
I received: 49
I received: 13
I received: 10

```

# Answer
> 1 votes
It is looping faster than the serial is delivered, so each time there is a byte delivered, it tests it against 0x30 until nothing is left, and then drops out, leaving nothing .available() for the next if(), so it fails out as well and starts up the loop() again.

I'd read a byte at a time and work with that:

```
int incomingByte = 0;   // for incoming serial data

void loop(void) {

if(Serial.available())
{
    incomingByte=Serial.read();

    if (incomingByte == 0x30)
    {
         func1();
    }

    if (incomingBute == 0x31)
    {
         func2();
    }

}

```

---
Tags: serial, arduino-leonardo
---


# Question
Title: Unable to read and write serial data between two arduino's (hc-05 paired) when using a sensor
What I did was that I wrote a piece of code that will-in-fact move a servo motor when a clap is detected using a sound impact sensor (fc-04). The code for this is seen here and in fact does work:

```
#include "Arduino.h"
#include <Servo.h>
Servo myservo;//create servo object to control a servo
enum {
    SERIAL_BAUD        = 9600,
    SENSOR_DIGITAL_PIN =    2,
    SOUND_DELAY        =   1500, /* Delay to avoid duplicate detection */
};

void setup() {
    Serial.begin(SERIAL_BAUD);
    pinMode(SERIAL_BAUD, INPUT);
    myservo.attach(9);//attachs the servo on pin 9 to servo object
    myservo.write(0);//back to 0 degrees
    delay(1000);//wait for a second
}

void loop() {
    if (digitalRead(SENSOR_DIGITAL_PIN) == LOW) {
        static int count;

        Serial.print("Sound detected: ");
        Serial.println(++count);
        myservo.write(170);//goes to 15 degrees
        delay(3000);//wait for 3 seconds
        myservo.write(10);//back to 0 degrees
        delay(1000);//wait for a second

        // Wait a short bit to avoid multiple detection of the same sound.
        delay(SOUND_DELAY);
    }
}

```

On a seperate occasion I paired two arduinos together using two hc-05 bluetooth modeules making one a slave and another a master, the initial code I used for both of them are listed here:

```
//                 == SLAVE CODE ==

#include <Servo.h>
#define button 8

Servo myServo;
int state = 20;
int buttonState = 0;

void setup() {
  pinMode(button, INPUT);
  myServo.attach(9);
  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
 // Controlling the servo motor
 myServo.write(state);
 delay(10);

 // Reading the button
 buttonState = digitalRead(button);
 if (buttonState == HIGH) {
   Serial.write('1'); // Sends '1' to the master to turn on LED
 }
 else {
   Serial.write('0');
 }
}

```

and

```
//                == MASTER CODE ==

#define ledPin 9

int state = 0;
int potValue = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
 // Controlling the LED
 if (state == '1') {
  digitalWrite(ledPin, HIGH); // LED ON
  state = 0;
 }
 else if (state == '0') {
  digitalWrite(ledPin, LOW); // LED ON
  state = 0;
 }
 // Reading the potentiometer
 potValue = analogRead(A0);
 int potValueMapped = map(potValue, 0, 1023, 0, 255);
 Serial.write(potValueMapped); // Sends potValue to servo motor
 delay(10);
}

```

I attempted to use the master and slave code with the one with the servo and fc-04 so that the sound sensor will be on the master and the servo on the slave so that when ever I clap it will move the servo on the other arduino.

The new master and slave code that I used are :

```
//New slave
#include "Arduino.h"
#include <Servo.h>
int state = 0;
Servo myservo;

void setup() {
  Serial.begin(38400); // Default communication rate of the Bluetooth module
  myservo.attach(9);//attachs the servo on pin 9 to servo object
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
  }

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
// Controlling the servo
 if (state == '1') {
  myservo.write(170);//goes to 15 degrees
  delay(3000);//wait for 3 seconds
  myservo.write(10);//back to 0 degrees
  delay(1000);//wait for a second
  state = 0;
 }
 else if (state == '0') {
  state = 0;
  }
}

//new Master
#include "Arduino.h"
#include <SoftwareSerial.h>
int state = 0;
SoftwareSerial BTserial(1, 0); // RX | TX

void setup() {
    Serial.begin(9600);
    pinMode(9600, INPUT);
    BTserial.begin(38400);

}

void loop() {
    if (digitalRead(2) == LOW) {
        static int count;
        BTserial.write('1');
        delay(1500);
    }
    else {
      BTserial.write('0');
    }
}

```

However the slave and master code for the servo and fc-04 is not working at all despite knowing that all the conponents work individually. What I am aware of is that the fc-04 uses serial communication to transfer data and so does the hc-05 bluetooth modules. This causes an issue because I believe from experience is that you can not have two serial communications being transmitted from the arduino at the same time which I need. I have been at this for days and It is driving me nuts. If I could have some help at all I will be much appreciated.

# Answer
> SoftwareSerial BTserial(1, 0); // RX | TX

Well, there's your problem. You are starting `SoftwareSerial` on the `Serial` pins. Don't do that!

For best results, hook your BT to pins 8 & 9 and use AltSoftSerial. It is *much* more efficient than `SoftwareSerial`, and it will not interfere with `Serial` reads and writes.

If you really can't use those pins, pick two other pins and use my NeoSWSerial. It is almost as efficient, and it works on any PinChange interrupt pins at 9600, 19200 or 38400 baud rates.
> 1 votes

---
Tags: serial, bluetooth, softwareserial, hc-05
---


# Question
Title: How get assembler/preprocessed code for library
I am using https://github.com/sudar/Arduino-Makefile project with https://github.com/ladislas/Bare-Arduino-Project to compile my Arduino projects from Linux command line. I put as much as possible functionality to libraries for reuse (and use the same libraries from many projects too).

Now I had run to some problems and I am not sure, if I am using the language (C/wiring/...) properly, as a lot of `#define` macros are used. I think, that seeing the resulting code would help me greeatly in finding, wheather some specific lines are compiled into what I want them to be compiled. I am interested mainly in the **library** code, even if it would mean to dump full program together with all used standard libraries. (I can find my way in large files.)

I would prefere intermediate files, as I suppose they could contain more info than just dissassembled .HEX file, but if this assumption is not correct, and I can get the same from .HEX, than I can use that way as well.

**Question**: How to get intermediate files (Ideally both "plain C" after preprocessing all macros AND "plain ASM" after compiling the code) ideally with corresponding lines of original code as comments inside.

**Subquestion**: In the above, how to disable optimalisation as much as possible, to get the code more verbatim similar to original C (I know, that it would hurt both speed and size and I do not care - I just want to be sure compiler does undertand my code the same way as I myself and if not, then see, where I made mistakes)

Thanks for all suggestions :)

# Answer
> 1 votes
One method I've used for creating assembly listings for Arduino sketches when using the Arduino IDE is as follows:
• Click Verify to compile the sketch
• Locate the the temporary build directory
• Use `avr-objdump` with `-CSI...` switches to decode the ELF file

Here are some commands you can put into a shell file to automate that procedure, on a Linux system:

```
item=*.ino
[ -z "$item" ] && echo ino file not found && exit
BDIR=/tmp/$(ls -t /tmp | egrep -m1 build.*tmp)
BASE=$(basename $item .ino)
avr-objdump -CSI$PWD $BDIR/$BASE.cpp.elf > $BASE.ino.asm

```

The above assumes the current working directory (ie, `$PWD`) is the directory with the sketch in it; variable `item` is the sketch name; variable `BASE` is the basename of the sketch, with `.ino` stripped off; `$BDIR` is the most-recently-used temporary build directory (which, on Ubuntu Linux systems, has a path that starts with `/tmp/build`); and the resulting deassembly is placed in `$BASE.ino.asm` for viewing.

To try this manually, as you may need to do on systems where the above shell commands don't work, say

```
avr-objdump -CSIddd bbb/sss.cpp.elf > sss.ino.asm

```

in a shell or at a command console, replacing `ddd` with the sketch's source directory name; `bbb` with the temporary build directory's name; and `sss` with the sketch's name.

---

*Edit 2:* Using Sudar's Arduino Makefile probably is the best starting point for looking at source code that has been pre-processed, or that has been compiled (into assembly language). This makefile system is fairly easy to install and use.

When you have the makefile system installed and working, you can generate pre-processed code (code that's been run through the pre-processor to incorporate `#include` files and to expand macros) by adding the following line within a makefile:

```
CPPFLAGS += -E

```

The `-E` switch tells avr-gcc to stop after preprocessing. According to `man gcc` its effect is:

> Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output.

To generate assembly language, add the following line within a makefile:

```
CPPFLAGS += -S

```

The `-S` switch tells avr-gcc to stop after compiling. According to `man gcc` its effect is:

> Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified. ... By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.

If you are skilled at makefile writing, it may be possible to add a target with rules to generate assembly or pre-processed code for inspection. Actually, Sudar's Arduino Makefile appears to have assembly-listing targets and rules already (as below for .pde; others for .ino and .cpp) although I haven't gotten them to work:

```
# generated assembly
$(OBJDIR)/%.s: %.pde $(COMMON_DEPS) | $(OBJDIR)
        @$(MKDIR) $(dir $@)
        $(CXX) -x c++ -include $(ARDUINO_HEADER) -MMD -S -fverbose-asm $(CPPFLAGS) $(CXXFLAGS) $< -o $@

```

\[I now see that Edgar Bonet has mentioned this too.\]

# Answer
> 1 votes
You can get the generated assembly by passing the `-S` option to avr-g++. The makefile you are using has a rule for that, so you would just type

```
make build-*/my_file.s

```

to get the assembly for `my_file.cpp`.

For the pre-processed C++, you use the `-E` option. There is no rule for that in the makefile, so you will have to write yo own, or manually invoke the compiler. At a minimum:

```
avr-g++ -mmcu=my_mcu -E my_file.cpp > my_file.i

```

You may want to add `-DF_CPU=... -DARDUINO=...` just like the makefile does when compiling the same file.

---
Tags: compile, linux, assembly
---


# Question
Title: Playing a pcm file through a speaker with arduino
I'm trying to play an audio file through a speaker with arduino. However, I do not want to use pre-constructed libraries such as the tmrpcm library.

I was instructed to perhaps even recreate the tmrpcm library, and my process so far is that I managed to extract the data chunk from the wav file in integers, and I also managed to turn the wav file into a pcm file.

I am currently studying http://playground.arduino.cc/Code/PCMAudio this link in order to gain more insight about how I might play the pcm file with the speaker. However, I'm stuck with the general concept of the code. In fact, I'm confused with the general concept of playing the pcm file through the speaker.

In my understanding, playing a music through the speaker works by outputting series of voltages to the speaker, so that the current in accordance with the magnetic field creates an outward force onto the voice coil with a certain frequency that creates the sound.

So my question is, what does the data in the pcm file actually mean? The integers cannot be frequencies, and by graphing it I can see that they are amplitudes in a waveform, but what kind of input they are continues to elude me.

So summing up my questions,

1. What is the theoretical aspect behind the link :http://playground.arduino.cc/Code/PCMAudio
2. What does the data in a pcm file (or even a wav file) actually represent?

Thank you so much.

# Answer
You are right that the values in a wav file are amplitudes. 16 bit signed values to be precise.

And that amplitude is just a voltage. Negative values are normally a negative voltage, but they don't have to be. They can be just a voltage below a pre-determined mid voltage around which the wave swings (known as a DC offset).

To play the waveform you just have to generate the corresponding voltages at the right times. That is usually done using a timer so you get the frequency right. For instance a 44100Hz file has to have a sample voltage generated 44100 times per second. 44100 samples will be a sound clip lasting 1 second.

But of course the Arduino cannot generate a voltage, so instead PWM is used instead. Filtered through a low-pass filter it turns into a voltage. It also uses 50% duty cycle as "zero" for the waveform, which is scaled to fit into the resolution of the PWM. The PWM has to be running at a considerably higher frequency than the sample frequency of the waveform so it has a chance to represent a voltage before it is asked to change again.
> 3 votes

---
Tags: pwm, frequency, tmrpcm
---


# Question
Title: MPU6050 Sending Bad values for Angular Velocity
The mpu gives me perfectly fine values for the yaw, pitch, and roll position of the chip, but when I use `mpu.getRotation(&gx, &gy, &gz)` to obtain the current angular velocity of the chip, the values returned are awful. I wrote a program in *Processing* to graph the data from my Arduino, and this is what it looks like:

I suggest you click on the picture and zoom in a bit because it's difficult to see. The green line represents zero (0), the Pink line represents the angular position of the mpu6050 chip, obtained from `mpu.getYawPitchRoll...`, and the Blue line represents the angular velocity on the same rotational axis.

A few extra things to note:

* The scale between the Pink and the Blue lines is slightly off, but that shouldn't matter for this purpose.
* The time-frame for this graph is about 16s.
* Before being graphed, the raw gx value is divided by the gyro's sensitivity scale factor, 131, and then converted from radians to degrees. In addition to this, it is also put through a complementary filter, so the whole formula looks like this: `rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI));`

As you can see, the measurements for angular velocity (Blue) make almost no sense when graphed next to the angular position (Pink).

My question is this: **What can I do to clean-up/filter these angular velocities and get rid of all the errors?** I need these values to be accurate enough to be used in something like a drone PID.

Things I have tried:

* Complementary filters of various proportions.
* Adjusting the MPU's built in low-pass filter.

Thanks for any suggestions.

# Answer
> 1 votes
At last! I have discovered the solution.

**Quick Solution** for those who don't like reading: Amend the previous `rollRate` formula to `rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);`. Or, if you don't want the filter, `rollRate = -1 * gx / 16.4;`

The problem starts with the function `mpu.getRotation(&gx, &gy, &gz)` which accepts `int16_t` types for `gx`, `gy`, and `gz`. Since `int16_t` is a 16 bit integer, it has a maximum range of -32,768...+32767. The reason this integer type is used is because the output range for the gyro is -32750...+32750, which fits nicely into the 16-bit integer's range.

The problem was that when I converted these values to a readable angular velocity (and complementarily filtered) using `rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI));` , the `gx` value was multiplied by -180 in part of the calculation. This means that if `gx` was high enough initially, it would have rolled over to -32786 and ruined the whole calculation, causing the horrible spikes in the graph.

At the same time I discovered this problem, I also realized that converting from radians to degrees was unnecessary, as the gyro output was already in units of degrees (just scaled by a sensitivity factor). After that big face-palm, I revised my rate formula to the following: `rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);`. You will notice the scale factor has changed from 131 to 16.4. That is because the gyro range is actually +/-2000 deg/s by default, not 250 deg/s. I tried to change it back to +/-250 with `mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);`, but after examining the graph, it appeares that `mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);` does not account for this setting change, and resulted in the ypr overshooting and then leveling out to its correct value after a delay. I decided not to mess around with the quaternion container, `q`, and just accepted the lower sensitivity.

Like the previous image, I suggest zooming in.

---
Tags: mpu6050, signal-processing, gyroscope
---


# Question
Title: MPU-9250 IMU on SPI, external sensor or magnetometer using I2C master
I'm trying (for sport...) to use an MPU-9250 in SPI mode as it should be faster, and wasn't able to talk to the embedded magnetometer in my code.

I've gone through the documentation (RM-MPU-9250A-00 v1.4) which is a bit spartan on that subject but gives the rough idea, it should work by enabling the built-in I2C master feature and using "proxy" I2C registers; I've tried to "do as it says" to communicate with the magnetometer; I'm querying the magnetometer identification register, and I only see 0x00 in there.

I searched in nature, and couldn't find an example of F/LOSS software using an external sensor plugged on the MPU.

Perhaps I've done something wrong but I can't see it, so here's a bottle in the ocean :)

# Answer
It turns out that my mistake was in the SPI communication code, but nevertheless here is some info because it's not very obvious.

I went over the top and:

* Review the electrical interface to see whether by any chance, my chip was badly hooked-up. Everything was fine.
* Enabled register read-back and saw that... owww, it was bad.
* Reviewing *PS-MPU-9250A-01 § 7.5 SPI Interface* I saw that I had made a stupid copy&paste error in my code... when copying my read code over to the write I forgot to adjust the MSB of the first spi byte.

Then:

* I2C\_MST\_P\_NSR=1 seems important or we get zeros
* basic config in there, currently using the I2C proxy to read the magnetometer, and I don't like having a sleep to wait for I2C transfers to happen or not, but this is a WIP and the code won't go anywhere.
> 1 votes

---
Tags: i2c, spi, mpu6050, magnetometer
---


# Question
Title: Can an Arduino power itself off [not low power mode] via software?
I'm working on a sketch where an Arduino UNO performs no useful work after the first 10 minutes following power on. It is not needed again until power to it is shut down, then re-enabled. This may not happen for hours or even days. No wake-up function is required, or deemed useful.

Of course, the Arduino could simply be left on as long as it's connected to its power source, but it will be placed remotely, and it seems \[to me\] safer to have it powered off. when not in use.

In essence, the Arduino is powered by a wall wart and plugged in with other devices fed by a switchable 120v power source.

I found a couple of possible hardware/software solutions to the problem but it isn't clear whether they would work in this situation. Power consumption is not the issue here.

# Answer
In general, an Arduino by itself has no control over its power input. It can, of course, enter various Sleep modes, such as the Power-down mode with watch-dog-timer off, which uses 0.1 μA.

It isn't clear from the question what will turn the Arduino back on after it is off for a while, but if you have either a push-button or a signal to turn it back on, the Pololu 2808 Mini Pushbutton Power Switch will work as an Arduino-controlled off switch. This board has On, Off, Ctrl, and button-contacts inputs. If your Arduino raises the Off input, power shuts off cleanly. To turn it back on, either connect the button-contacts inputs together, or raise the On input, or pulse the Ctrl input.
> 3 votes

# Answer
A battery-powered Arduino can go into deep sleep mode where it can use as little as 100 nA, and still be woken by a switch closure if required.

There doesn't seem to be much point to me to power down a mains-powered Arduino. What would be the purpose of that? The small amount of current it would use via the wall-wart would be trivial. If you are worried about voltage spikes (eg. lightning) then you should protect the input pins (or your power supply) whether or not it is powered off.

It seems to me that you may as well do whatever you need to do, and then go into an infinite loop. Once the Arduino is re-powered it will do it again. You aren't saving much by attempting to power it off, indeed that introduces an extra point which might fail.

> but it will be placed remotely, and it seems \[to me\] safer to have it powered off. when not in use.

Safer in what way? Any extra hardware you introduce to make the Arduino "safer" might itself introduce safety issues. It reminds me of the days when we had a UPS (Uninterruptable Power Supply). The UPS would fail more-or-less as often as the power did. In other words, you replaced one possible failure (the power failure) with another possible failure (the UPS failure).
> 3 votes

---
Tags: power
---


# Question
Title: What is the point of a adafruit data logger
In order to play an audio file, I was suggested to get an Adafruit data logger, yet right now I am stuck with the project and I realized that I'm not using the data logger to its full potential.

Yet I am unable to comprehend the purpose of a data logger ; all I'm using it for is to read SD Cards, and I can do that with a SD Card reader. I did read the whole documentation, data sheet, etc, and I can see that it has some cool functions, but my question is still, why data logger?

I know this might be a stupid question, but I genuinely don't get what the data logger is supposed to be a huge help of. Please help me.

# Answer
Are you referring to this?

That is a shield that has an SD card interface (with appropriate level-shifting for the SD card) plus a real-time clock.

The rest is "prototyping" area for you to install your own devices.

> In order to play an audio file, I was suggested to get an Adafruit data logger

I don't see how this helps play audio files, however you might read the audio file from the SD card. Then you need to send it to a DAC (digital-to-analog converter) to convert the digital information to analogue.

The Adafruit data logger is fine for recording data (for example, temperatures) but I don't see why someone would recommend it for playing audio files (apart from the SD card interface).

> my question is still, why data logger?

Better ask the person that recommended it, eh?
> 2 votes

---
Tags: adafruit, datalogging
---


title: Reading Json object name in arduino

text:
# Question
Title: Reading Json object name in arduino
How do I read the Json object name in arduino? For { "pi" : "3.14" }, I want the arduino to automatically read the object name "pi" and then th value "3.14" I'm using arduino Uno.

# Answer
There is a brilliant JSON library called ArduinoJSON. It can be installed using the arduino library manager.

See https://bblanchon.github.io/ArduinoJson/doc/decoding/ for further details.

To loop through the keys, you can use: https://bblanchon.github.io/ArduinoJson/api/jsonobject/begin\_end/

or if you know the key, you can do jsonObject\["pi"\] to get the value
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Burning a bootloader onto my Arduino MEGA 2560 without another arduino board, or isp board
My youtube video explains it. It's starting to get on my nerves.

# Answer
> 0 votes
You need a programmer (isp or Arduino board as programmer). It is not possible to burn a bootloader without it. The USBasp version 2 plus a 10 to 6 pin adapter cost about 2 dollars.

---
Tags: arduino-mega, bootloader
---


title: Arduino Debounce Sketch

text:
# Question
Title: Arduino Debounce Sketch
I want to use 4 Push Buttons and 4 leds in my project. What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds? So my sketch is only for one push button and one led. So tell me how I can solve this problem.

Here is the code:

```
const int buttonPin =2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}

void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}

if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:

// if the button state has changed:
if (reading != buttonState) {
  buttonState = reading;

  // only toggle the LED if the new button state is HIGH
  if (buttonState == HIGH) {
    ledState = !ledState;
  }
  }
  }

  // set the LED:
 digitalWrite(ledPin, ledState);
 lastButtonState = reading;
 }

```

# Answer
Well you declared only one pushbutton and one led. Now do like push1, push2, push3, push4 and led1, led2, led3, led4, and so on. You can also do that with your buttonStates1... Do not forget to declare them as INPUTs or OUTPUTs. Copy paste will help you with this task.
> 1 votes

# Answer
> What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds?

easy:

1) study your code to understand how it debounces one input;

2) isolate those parameters / variables used to debounce that specific input;

3) group those parameters / variables into a struct and pass a pointer to that struct to your code;

4) rewrite your code so that it takes the pointer to that struct and debounces accordingly;

5) use that code on as many inputs as you wish.

that's the general approach you take to coding any task.

hope it helps.
> 1 votes

# Answer
I hope this will work for you.

```
const int buttonPin1 = 2; // Button 1
const int buttonPin2 = 3; // Button 2
const int buttonPin3 = 4; // Button 3
const int buttonPin4 = 5; // Button 4

const int ledPin1 = 6; // LED 1
const int ledPin2 = 7; // LED 2
const int ledPin3 = 8; // LED 3
const int ledPin4 = 9; // LED 4

int ledState1 = HIGH;
int ledState2 = HIGH;
int ledState3 = HIGH;
int ledState4 = HIGH;

int buttonState1, buttonState2, buttonState3, buttonState4;

int lastButtonState1 = LOW;
int lastButtonState2 = LOW;
int lastButtonState3 = LOW;
int lastButtonState4 = LOW;

long lastDebounceTime1 = 0;
long lastDebounceTime2 = 0;
long lastDebounceTime3 = 0;
long lastDebounceTime4 = 0;

long debounceDelay1 = 50;
long debounceDelay2 = 50;
long debounceDelay3 = 50;
long debounceDelay4 = 50;

void setup()
{
  pinMode(buttonPin1, INPUT);
  pinMode(ledPin1, OUTPUT);
  digitalWrite(ledPin1, ledState1);

  pinMode(buttonPin2, INPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, ledState2);

  pinMode(buttonPin3, INPUT);
  pinMode(ledPin3, OUTPUT);
  digitalWrite(ledPin3, ledState3);

  pinMode(buttonPin4, INPUT);
  pinMode(ledPin4, OUTPUT);
  digitalWrite(ledPin4, ledState4);
}

void loop()
{
  led1Fun();
  led2Fun();
  led3Fun();
  led4Fun();
}

void led1Fun()
{
  int reading1 = digitalRead(buttonPin1);

  if(reading1 != lastButtonState1)
  {
    lastDebounceTime1 = millis();
  }

  if((millis() - lastDebounceTime1) > debounceDelay1)
  {
    if(reading1 != buttonState1)
    {
      buttonState1 = reading1;

      if(buttonState1 == HIGH)
      {
        ledState1 = !ledState1;
      }
    }
  }

  digitalWrite(ledPin1, ledState1);
  lastButtonState1 = reading1;
}

void led2Fun()
{
  int reading2 = digitalRead(buttonPin2);

  if(reading2 != lastButtonState2)
  {
    lastDebounceTime2 = millis();
  }

  if((millis() - lastDebounceTime2) > debounceDelay2)
  {
    if(reading2 != buttonState2)
    {
      buttonState2 = reading2;

      if(buttonState2 == HIGH)
      {
        ledState2 = !ledState2;
      }
    }
  }

  digitalWrite(ledPin2, ledState2);
  lastButtonState2 = reading2;
}

void led3Fun()
{
  int reading3 = digitalRead(buttonPin3);

  if(reading3 != lastButtonState3)
  {
    lastDebounceTime3 = millis();
  }

  if((millis() - lastDebounceTime3) > debounceDelay3)
  {
    if(reading3 != buttonState3)
    {
      buttonState3 = reading3;

      if(buttonState3 == HIGH)
      {
        ledState3 = !ledState3;
      }
    }
  }

  digitalWrite(ledPin3, ledState3);
  lastButtonState3 = reading3;
}

void led4Fun()
{
  int reading4 = digitalRead(buttonPin4);

  if(reading4 != lastButtonState4)
  {
    lastDebounceTime4 = millis();
  }

  if((millis() - lastDebounceTime4) > debounceDelay4)
  {
    if(reading4 != buttonState4)
    {
      buttonState4 = reading4;

      if(buttonState4 == HIGH)
      {
        ledState4 = !ledState4;
      }
    }
  }

  digitalWrite(ledPin4, ledState4);
  lastButtonState4 = reading4;
}

```
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: Enabling pins of Arduino Due with direct port manipulation
I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used `PIOB->PIO_PER = 1<<27;` to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.

Here's my complete code:

```
#include <asf.h>

int main (void) {
  // Insert system clock initialization code here (sysclk_init()).
  board_init();
  sysclk_init();
  delay_init(sysclk_get_cpu_hz());
  PIOB->PIO_PER = 1<<27;
  PIOB->PIO_OER = 1<<27;
  while(1) {
    REG_PIOB_ODSR = 1<<27;
    delay_ms(1000);
    REG_PIOB_ODSR = 0<<27;
    delay_ms(1000);
  }
}

```

Can anyone tell me how I can get this to work?

# Answer
I suggest the following test: Use `REG_PIOB_SODR = 1<<27;` to set the bit, and `REG_PIOB_CODR = 1<<27;` to clear it. If that works ok, see about enabling synchronous data output via the port's PIO\_OWSR register. (If it doesn't work ok, perhaps review section 31.6, “I/O Lines Programming Example”, on page 629 of Atmel document 11057, the Cortex datasheet.)

Section 31.5.5, “Synchronous Data Output”, on page 623 says in part:

> After reset, the synchronous data output is disabled on all the I/O lines as PIO\_OWSR resets at 0x0.

I imagine that writes to REG\_PIOB\_SODR and REG\_PIOB\_CODR should have effect after you enabled output by setting bits in PIOB-\>PIO\_PER and PIOB-\>PIO\_OER, which you did. However, with the bit in PIO\_OWSR being clear, synchronous data output isn't available, so writes to REG\_PIOB\_ODSR have no effect.
> 0 votes

# Answer
```
    #define Led_ON  REG_PIOB_ODSR |= 0x8000000
    #define Led_OFF REG_PIOB_ODSR &= ~0x8000000
    //for Arduino Due
    PIOB->PIO_PER |= 0x8000000;//led
    PIOB->PIO_OER |= 0x8000000;//led

```

And then call Led\_ON and Led\_OFF
> 0 votes

---
Tags: arduino-due, port-mapping
---


title: Arduino with 2 echo sensors

text:
# Question
Title: Arduino with 2 echo sensors
For a project I'm doing I need the Arduino to be connected to two echo sensors (I have the HC-SR04). Currently I have 4 sensors that I can use, but I will need only 2 or 3.

I have almost no knowledge of coding and the Arduino, but I figured out how to connect it to one echo sensor, and that is working, which is great.

But now I need it to connect to two. I found example code with 3 echo sensors, but whenever I connect them my Arduino shuts down. I guess it is because it takes up too much power, my teacher said something like that. All lights turn off all of the sudden, and it doesn't reset. Only when I remove some the wires for the power, it works again.

So 3 isn't going to work. I figured I'd stick to two. Now the problem: Whenever I try to edit the code to two echo sensors (I basically just removed the `trigPin3` and `echoPin3` in the first part of the code, and the `SonarSensor(trigPin3, echoPin3))`, it doesn't work anymore. The monitor doesn't show any values anymore, while it did with the first code. It just shows zeroes now.

So my question is, how can I edit the example code so that it works with 2 echo sensors?

This is the code I found for the 3 echo sensors:

```
#define trigPin1 3
#define echoPin1 2
#define trigPin2 4
#define echoPin2 5
#define trigPin3 7
#define echoPin3 8

long duration, distance, RightSensor,BackSensor,FrontSensor,LeftSensor;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);
}

void loop() {
  SonarSensor(trigPin1, echoPin1);
  RightSensor = distance;
  SonarSensor(trigPin2, echoPin2);
  LeftSensor = distance;
  SonarSensor(trigPin3, echoPin3);
  FrontSensor = distance;
  Serial.print(LeftSensor);
  Serial.print(” – “);
  Serial.print(FrontSensor);
  Serial.print(” – “);
  Serial.println(RightSensor);
}

void SonarSensor(int trigPin,int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
}

```

And this is the one that IS working, but with 1 echo sensor:

```
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200;
int minimumRange = 0;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  if (distance >= maximumRange || distance <= minimumRange) {
    /* Send a negative number to computer and Turn LED ON
    to indicate "out of range" */
    Serial.println("-1");
    digitalWrite(LEDPin, HIGH);
  } else {
    /* Send the distance to the computer using Serial protocol, and
    turn LED OFF to indicate successful reading. */
    Serial.println(distance);
    digitalWrite(LEDPin, LOW);
  }
  //Delay 50ms before next reading.
  delay(50);
}

```

I hope someone can help me!

Many thanks, Leah.

# Answer
* In the 1 sensor program all the delays added together account for 62ms between samples.
* In the 3 sensor program the sample code contains delays which likely exceed 12ms (delays plus code execution). So each sensor will not be sampled faster than once every 36ms.
* After you removed 1 sensor from the 3 sensor program, you increased the sampling rate to about every 23ms.
* It is likely a minimum amount of time is necessary between samples in order for the HC-SR04 to recover.
> 1 votes

# Answer
Try this one. I hope this will work for you.

```
int trigPin1 = 2;                        //Sensor Trip pin connected to Arduino pin 2
int echoPin1 = 3;                        //Sensor Echo pin connected to Arduino pin 3

int trigPin2 = 4;                        //Sensor Trip pin connected to Arduino pin 4
int echoPin2 = 5;                        //Sensor Echo pin connected to Arduino pin 5

float pingTime1;                         //time for ping to travel from sensor to target and return
float targetDistance1;                   //Distance to Target in centi meters

float pingTime2;                         //time for ping to travel from sensor to target and return
float targetDistance2;                   //Distance to Target in centi meters

float speedOfSound = 760.5583392985;     //Speed of sound in miles per hour.

void setup()
{
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
}

void loop()
{
  ultrasonicFun1();
  ultrasonicFun2();
}

void ultrasonicFun1()
{
  digitalWrite(trigPin1, LOW);         //Set trigger pin low
  delayMicroseconds(2000);             //Let signal settle
  digitalWrite(trigPin1, HIGH);        //Set trigPin high
  delayMicroseconds(15);               //Delay in high state
  digitalWrite(trigPin1, LOW);         //ping has now been sent
  delayMicroseconds(10);               //Delay in high state

  pingTime1 = pulseIn(echoPin1, HIGH);             //pingTime is presented in microceconds
  pingTime1 = pingTime1 / 1000000;                 //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime1 = pingTime1 / 3600;                    //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance1 = speedOfSound * pingTime1;      //This will be in miles, since speed of sound was miles per hour
  targetDistance1 = targetDistance1 / 2;           //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance1 = targetDistance1 * 160934.4;    //Convert miles to inches by multipling by 160934.4 (centi meters per mile)
}

void ultrasonicFun2()
{
  digitalWrite(trigPin2, LOW);          //Set trigger pin low
  delayMicroseconds(2000);              //Let signal settle
  digitalWrite(trigPin2, HIGH);         //Set trigPin high
  delayMicroseconds(15);                //Delay in high state
  digitalWrite(trigPin2, LOW);          //ping has now been sent
  delayMicroseconds(10);                //Delay in high state

  pingTime2 = pulseIn(echoPin2, HIGH);             //pingTime is presented in microceconds
  pingTime2 = pingTime2 / 1000000;                 //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime2 = pingTime2 / 3600;                    //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance2 = speedOfSound * pingTime2;      //This will be in miles, since speed of sound was miles per hour
  targetDistance2 = targetDistance2 / 2;           //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance2 = targetDistance2 * 160934.4;    //Convert miles to inches by multipling by 160934.4 (centi meters per mile)
}

```
> 1 votes

# Answer
Try this:

```
void loop() {

RightSensor = SonarSensor(trigPin1, echoPin1);

LeftSensor = SonarSensor(trigPin2, echoPin2);

FrontSensor = SonarSensor(trigPin3, echoPin3);

Serial.print(LeftSensor);

Serial.print(” – “);

Serial.print(FrontSensor);

Serial.print(” – “);

Serial.println(RightSensor);

}

long SonarSensor(int trigPin,int echoPin)
{

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

return distance;

}

```
> 0 votes

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


# Question
Title: Is ATmega 328 on Arduino UNO already bootloaded?
I've seen many tutorials on programming a ATmega 328 via Arduino. If i'm right, the atmega need to be bootloaded. I thought to remove the atmega present on the arduino board. But to bootloading atmega we need another atmega on the arduino board. I can't buy a new one. After bootloading we need only one IC. So, can I remove the atmega which is present on the arduino and directly program it? Can I consider it as a bootloaded one?

# Answer
> 2 votes
Arduino controllers are usually already bootloaded with Arduino. So yeah, you can use the chip on the arduino. Or you can buy a programmer to bootloaded empty chips.

# Answer
> 4 votes
In Arduino board, arduino controller means ATMEGA328P-PU already bootloaded. So, you can use directly. But if you buy only ATMEGA328P-PU chip or any other ATMEGA chip then you have to do bootloading for that.

# Answer
> 2 votes
Arduino boards come with the bootloader already installed. You only need to flash a bootloader to it if something damaged the original one. When you buy replacement chips, you generally have a choice of "factory fresh" ones (no bootloader) or ones that already have a bootloader installed, at a small difference in price.

---
Tags: arduino-uno, atmega328, bootloader
---


# Question
Title: Why would uninitialized SD-card module without card disable CAN-Bus shield?
(I am able to successfully initialize CAN-Bus shield and SD-card module w/ card in it.)

Now I have removed all code related to the SD-card module, yet I left the module (without the card in it) physically connected. **This results in the CAN-Bus shield initialization failing.**
When I insert the card into the SD-card module the CAN-Bus shield initializes successfully. (I am still not doing SD-card module initialization.)

Of course, I can just disconnect the SD-card module or leave the card in it... But I am trying to understand this black magic.

I have connected the SD-card module CS to pin 8, the CAN-Bus shield clone CS is connected to pin 10. I tried to set the SD-card module CS pin to OUTPUT and to HIGH. That had no effect.

the CAN-Bus shield + schematics: http://www.elecfreaks.com/estore/can-bus-shield.html \[Resource -\> Schematics\]
the SD-card module: https://ebay.com/itm/161366316226?\_trksid=p2057872.m2749.l2649

# Answer
> 2 votes
Without seeing schematics this is purely supposition:

My guess is that the SD shield contains bi-directional level shifting. The MISO pin, which connects the DO pin of the SD card to the MCU, will have a 3.3V -\> 5V level translator on it. This, with no SD card inserted, will be floating (flapping around in the breeze) causing the output of the level translator to randomly produce digital signals on the MISO pin. These signals interfere with the MISO signals from your CAN shield.

How best to cure the problem very much depends on what level shifting is in the circuit and how it is controlled and wired. For that we will need to see schematics of both the CAN and SD card shields.

---
Tags: arduino-uno
---


title: Line Following Robot

text:
# Question
Title: Line Following Robot
I have written a code and it works OK with the robot on straight, curved, intersections. But the robot just moves forward in the current direction whenever it comes across an acute angle turn. I am attaching the code in the description ....can anyone please guide me through the necessary changes or the troubleshoot procedures?

```
#define left_pwm 6
#define right_pwm 3
#define left_1 5
#define left_2 7
#define right_1 4
#define right_2 2
const int ledPin1 = 9;

int left1;
int left2;
int left3;
int left4;
int right1;
int right2;
int right3;
int right4;
int lc=1;
int sc=0;

float Kp=120, Kd=130;
float error=0, P=0, D=0, PID_value=0;
float initial_motor_speed_l=100;
float initial_motor_speed_r=100;
float left_motor_speed=0, right_motor_speed=0;
float previous_error=0;

int left=0;
int right=0;

void setup()
{

  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(A2,INPUT);
  pinMode(A3,INPUT);
  pinMode(A4,INPUT);
  pinMode(A5,INPUT);
  pinMode(11,INPUT);
  pinMode(10,INPUT);

  pinMode(right_pwm,OUTPUT);
  pinMode(right_1,OUTPUT);
  pinMode(right_2,OUTPUT);
  pinMode(left_1,OUTPUT);
  pinMode(left_2,OUTPUT);
  pinMode(left_pwm,OUTPUT);
  pinMode(ledPin1,OUTPUT);

}
void loop()
{
    line_follow();
 if (right4==lc && left==lc)
 {
  brake();
 }
 else {
  forward();
 }

    if(right3==lc && left3==lc)
  {
    digitalWrite(9,HIGH);
  }
   else
  {
    digitalWrite(9,LOW);
  }
}
void pid()
{
    if((left1==lc)&&(right1==lc))
   {
    error=0;
   }
   else if(right1==lc)
   {
    error=0.5;
   }
   else if((right1==lc)&&(right2==lc))
   {
    error=1;
   }
   else if(right2==lc)
   {
    error=1.5;
   }
   else if((right2==lc)&&(right3==lc))
   {
    error=2;
   }
   else if(right3==lc)
   {
    error=2.5;
   }
   else if((right3==lc)&&(right4==lc))
   {
    error=3;
   }
   else if(right4==lc)
   {
    error=3.5;
   }
   else if(left1==lc)
   {
    error=-0.5;
   }
   else if((left1==lc)&&(left2==lc))
   {
    error=-1;
   }
   else if(left2==lc)
   {
    error=-1.5;
   }
   else if((left2==lc)&&(left3==lc))
   {
    error=-2;
   }
   else if(left3==lc)
   {
    error=-2.5;
   }
   else if((left3==lc)&&(left4==lc))
   {
    error=-3;
   }
   else if(left4==lc)
   {
    error=-3.5;
   }

   P = error;
   D = previous_error-error;
   PID_value = (Kp*P) + (Kd*D);
   previous_error=error;
   left_motor_speed = initial_motor_speed_l+PID_value;
   right_motor_speed = initial_motor_speed_r-PID_value;
   if(left_motor_speed>=255)
   {
    left_motor_speed=255;
   }
   if(left_motor_speed<=0)
   {
    left_motor_speed=0;
   }
   if(right_motor_speed>=255)
   {
    right_motor_speed=255;
   }
   if(right_motor_speed<=0)
   {
    right_motor_speed=0;
   }
   analogWrite(left_pwm, left_motor_speed);
   analogWrite(right_pwm, right_motor_speed);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}
void line_follow()
{
    left4=digitalRead(A0);
    left3=digitalRead(A1);
    left2=digitalRead(A2);
    left1=digitalRead(11);
    right1=digitalRead(10);
    right2=digitalRead(A3);
    right3=digitalRead(A4);
    right4=digitalRead(A5);

    if(left4!=0)
    {
     left=0;
    }
    if(right4!=0)
    {
     right=0;
    }
    if((left4==0)&&(left3==0)&&(left2==0)&&(left1==0)&&(right1==0)&&(right2==0)&&(right3==0)&&(right4==0))
    {
      if((left>150)&&(right<150))
      {
            left1=digitalRead(11);
          right1=digitalRead(10);
          while((right1==0)&&(left1==0))
      {
        right_turn();
        left1=digitalRead(11);
            right1=digitalRead(10);
       }

      }
      else if((left<150)&&(right>150))
      {
            left1=digitalRead(11);
            right1=digitalRead(10);

            while((left1==0)&&(right1==0))
        {
         left_turn();
         left1=digitalRead(11);
             right1=digitalRead(10);
            }
          }
        }
     pid();
     left=left+1;
     right=right+1;
     if(left>20000)
     {
       left=1000;
     }
     if(right>20000)
     {
       right=1000;
     }

}
void right_turn()
{
   analogWrite(left_pwm,75);
   analogWrite(right_pwm,75);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,HIGH);
   digitalWrite(right_2,LOW);
}
void left_turn()
{
   analogWrite(left_pwm,75);
   analogWrite(right_pwm,75);
   digitalWrite(left_1,LOW);
   digitalWrite(left_2,HIGH);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}
void brake()
{
   analogWrite(left_pwm, 0);
   analogWrite(right_pwm, 0);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,HIGH);
   digitalWrite(right_1,HIGH);
   digitalWrite(right_2,HIGH);
}
void forward()
{
   analogWrite(left_pwm,100);
   analogWrite(right_pwm,100);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}

```

# Answer
> 1 votes
There are some lines in `pid()` that will never be called.

```
else if (right2 == lc)
{
    error = 1.5;
}
else if ((right2 == lc) && (right3 == lc))
{
    error = 2;
}

```

if `right2 == lc` then the second `else if` will never be called.

You need to refactor this function, its horrid. Firstly the right and left values for error only differ in sign, so you could right a function that took 4 values in and returned an absolute number. If you called it for left then make the result negative. Something like this is actually better, but will prevent the error you had.

```
else if (right3 == lc)
{
      if (right4 == lc)
        error = 3.0;
      else
        error = 2.5;
}
else if (right4 == lc)
{
      error = 3.5;
}

```

---
Tags: arduino-uno
---


title: Arduino play many piezo at once

text:
# Question
Title: Arduino play many piezo at once
I need to play sound on 10 piezos at once. How to do that without `delay()` function.

# Answer
Use the Timer library.

You can attach up to 10 events to each `Timer` object you declare. That will suit your use case.
> 1 votes

---
Tags: arduino-mega, piezo
---


title: What is this green board?

text:
# Question
Title: What is this green board?
Hi I'm new to arduino and robotics itself. I have no idea what this giant green board is in the middle of the robot. I really need help!

# Answer
> 5 votes
The green board is probably a custom PCB that controls the vehicle. Unfortunately, the image does not have enough quality to determine much else.

# Answer
> 1 votes
It's a sheet of FR-4 clad in copper, with much of the copper etched off to form a PCB. That is then coated in green UV cured paint (solder resist) and components are attached.

Other things are then plugged into it.

What function it performs depends on what the designer designed it to do.

---
Tags: robotics
---


# Question
Title: Using Arduino Uno as ISP to program Mega 2560
I'm trying to use Arduino Uno as ISP to program Arduino Mega 2560 using this Pin connections (Uno-\>Mega):

slave reset: 10: -\> RESET on target

MOSI: 11: -\> 51

MISO: 12: -\> 50

SCK: 13: -\> 52

It runs perfectly when I "Burn Bootloader" from Arduino IDE and LED starts blinking on target. So I assume my pin connections are correct.

However, when I open the Blink example and perform "Upload Using Programmer" in Sketch tab after choosing "Arduino as ISP" in Tools\>Programmer it uploads the code but LED on Mega doesn't blink.

I'm afraid that I have problem in my Mega Bootloader hex file and think it's not configuring Pin 13 as a LED pin. But in this case I shouldn't have seen the led blinking after burning the bootloader.

What am I missing here? I appreciate your help. -Bex

# Answer
Find the file called "boards.txt" located in your Arduino installation directory. In my case, the path is "arduino-1.6.5/hardware/arduino/avr/boards.txt". Open it with your favourite text editor and locate the ATMEGA2560 section. (not in notepad, it breaks the file format, notepad++ my choice)

in boards.txt

* back-up the file incase you break it,
* find the line : mega.menu.cpu.atmega2560.bootloader.high\_fuses=0xD8
* and change it with : mega.menu.cpu.atmega2560.bootloader.high\_fuses=0xD9

Source : http://soc.ninja/documentation/programming-atmega2560-with-arduino-uno-or-mega/#rating-74
> 1 votes

---
Tags: arduino-uno, arduino-mega, arduinoisp
---


# Question
Title: Arduino + motor driver (L293D) power consumption
Please help me on this question.

Original question : My chip consists of 1 arduino nano and 3 L293D motor driver. This chip is for controlling motors and other equipments. My question is about how to calculate power consumption of my chip. I searched for about voltage settings of arduiono nano and L293D motor driver, but there are many phusical thinks that i cannot understand. How many hours 2000 mah battery enough for.

Note : Motors and other equipments will have own power supply. That i say it is just for Arduino Nano, Bluetoot adapter for arduino (HC-05) and 3 motor driver (L293D).

# Answer
> 1 votes
To calculate L293D power usage, you need to lookup the datasheet and check the Voh and Vol. These are the High level voltage and Low level voltage.

On Texas Instruments datasheet, we have:

So you will lose about 1.4V when your output is -0.6A, and 1.2V when your output is 0.6A. If your motor uses 2 outputs (bi-directional) then you have to add the losses.

Then, to get the power dissipated on the power side of the L293D, you take this voltage drop and multiply by the motor´s current.

**Example:**
Lets say your motor is using 0.6Amps and your power source is 5V + 24V @ 25°C (just like in the datasheet).

The power loss in the L293D is aprox.: (1.4V + 1.2V) x 0.6A = 1,56W.
Since you´ve lost 2.6V in the L293D, your motor will use: (24V - 2.6V) x 0.6A = 12,84W.

To measure this directly on your real circuit, use a multimeter in Ampere mode to measure current, and Volt mode to measure the voltage on the motor terminals when it is on.

As for the arduino, your battery has 2000mAh and I assume it is a 7,4V battery. So it has 2000mAh x 7,4V = 14800mWh of energy stored in it.

If you are running your arduino at 5V, then: 14800mWh / 5V = 2960mAh at 5V.
Now let´s say your arduino and it´s modules, the L293D´s and the motors are using 500mA average, then your battery will last: 2960mAh / 500mA = 5.92 hours in theory.
Why "in theory"? because in real life it is impossible to extract all the energy from inside a battery. A minimum ammount of energy has to remain inside it and some power is lost when you extract it´s energy.

Of course, this is a very raw calculation. In reality, you have to calculate power used in every component. But by calculating the "big guns" first you can get an idea of where you stand.

Basic power loss calculation is done by multiplying voltage drop by the current in each circuit. Voltage drop is the difference between your volts before and after the component.

---
Tags: power, motor, battery
---


# Question
Title: Read all relay output (high or low) from Bluetooth through Android app
I have written the following code for Arduino:

```
#define relay2 2
#define relay3 3
#define relay4 4
#define relay5 5
#define relay6 6
#define relay7 7
#define relay8 8
#define relay9 9
byte val;
void setup() {
  Serial.begin(9600);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  pinMode(relay7, OUTPUT);
  pinMode(relay8, OUTPUT);
}

void loop() {
  int a = 0;
  if (Serial.available()) {
    val = Serial.read();
    Serial.println(int(val));
    //Display received value on Serial Monitor
    //ASCII VALUES
    if (int(val) == 49) //Turn Light1 ON 1
      digitalWrite(relay2, HIGH);
    else if (int(val) == 50) //Turn Light1 OFF 2
      digitalWrite(relay2, LOW);
    if (int(val) == 51) //Turn Light2 ON
      digitalWrite(relay3, HIGH);
    else if (int(val) == 52) //Turn Light2 OFF
      digitalWrite(relay3, LOW);
    if (int(val) == 53) //Turn Light3 ON
      digitalWrite(relay4, HIGH);
    else if (int(val) == 54) //Turn Light3 OFF
      digitalWrite(relay4, LOW);
    if (int(val) == 55) //Turn AC ON
      digitalWrite(relay5, HIGH);
    else if (int(val) == 56) //Turn AC OFF
      digitalWrite(relay5, LOW);
    if (int(val) == 57) //Lock the DOOR
      digitalWrite(relay6, HIGH);
    else if (int(val) == 48) //Unlock the DOOR
      digitalWrite(relay6, LOW);
  }
}

```

Now on the Android side I have written the following code:

```
 //Bluetooth connection code ....
  mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

  mmSocket.connect();
  mmOutputStream = mmSocket.getOutputStream();
  mmInputStream = mmSocket.getInputStream();

  int byteCount = mmInputStream.available();
  if (byteCount > 0) {
    byte[] rawBytes = new byte[byteCount];
    mmInputStream.read(rawBytes);
    String string = new String(rawBytes);
    Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
  }

```

Now it works perfectly when I press a button to turn the light on/off. But I want to read all relay current status (high/low) when a Bluetooth connection is made.

So basically after connecting to the Bluetooth module I want all relay status.

How can I do that?

# Answer
> 2 votes
It's rather undocumented, but you can actually use `digitalRead(relay2);` on a pin (ex *relay2*) that is set to `OUTPUT`. I discovered it accidentally, and it worked exactly as expected, so i looked it up and it's legit. This is very handy to check an output pin's hi/lo state from a non-connected part of the code.

There is a tiny performance dip compared to reading just a variable, but it usually won't be noticed. If you need top performance, wrap the digitalWrite() with your own function, and set a variable with the new state:

```
int myState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

void digitalWrite2(int pin, int value){
   myState[pin] = value; // copy setting to a global array
   digitalWrite(pin, value); // apply the setting as intended
}

```

Now, you can instantly get all the relay states from the *myState* array, provided they've been set with `digitalWrite2`. The other advantage to an array is that you can easily persist it to SPIFFs or EEPROM as-needed and recover the relay states on the next boot.

# Answer
> 0 votes
Changing the mode of the pins would be a pain, so you might be better to store the state of the relays within you Arduino code (a bool array) as long as you know what state they start in, then send the data back over the serial connection.

Define an array of pin numbers, an array of Boolean states and rework your code to change both arrays at the same time when a number comes in.

---
Tags: arduino-uno, bluetooth, relay
---


title: Help with struct variable

text:
# Question
Title: Help with struct variable
I made a struct like this:

```
typedef struct {
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
} buttons;

```

and a variable like this:

```
button test[1] =
{
  {{0,0,0},{0,0,100,100},"getSomething",setSomething}
}

```

In loop() I call test\[i\].color, test\[i\].position normally.

Problems start when I want to execute a function.

I made two attemps, one with string and one with a function statement. With the string I have no problems using a strcmp() but it's not what I want.

I need to know how I can store 2 different functions in the struct and how I can execute.

Thanks in advance!

# Answer
> 2 votes
The typedef is no longer needed, using the 'struct' with a name declares the type.

```
// Arduino Uno

struct buttons
{
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
};

// Declare the functions here, or use prototyping
void func1();
void func2();

buttons test[] =
{
  { {0,0,0},    {0,0,100,100}, "getSomething",  func1 },
  { {40,40,40}, {50,50,10,10}, "somethingElse", func2 },
};

void setup()
{
  Serial.begin(9600);
  Serial.println("Calling the functions:");

  test[0].fn();
  test[1].fn();
}

void loop()
{
}

void func1()
{
  Serial.println("func1");
}

void func2()
{
  Serial.println("func2");
}

```

---
Tags: variables, struct
---


# Question
Title: Controlling Arduino through Internet and Bluetooth
I have an Arduino sketch that controls an LED through the Internet, and another through Bluetooth. The thing is I want to combine both sketches so that I can control my Arduino LED by Bluetooth as well as through the Internet. Is it possible to do that?

# Answer
> 2 votes
If I were you, I would separate the "hardware" from the "software". This is quite an interesting "pattern". It's used by almost every Operating System, to assure compatibility with devices all around the world.

But how?

**Layers**

The "OSI-model" typically describes a few layers. But to me, the most interesting part is the difference between "Host layer" and "Media layer".

**Media Layer**

The media layer(s) typically handle the transportation of your bits, addressing and data collision. In "the internet" you can 'simply' change from copper to glasfiber without it being noticeable in your end application (apart from being faster).

**Host layer**

The same for the host layers, whatever PC or network adapter you have, your program will run fine (if this abstraction/integration is done well).

**Applying this**

So how do we apply this? In a basic, small application.

We want our Host to not care too much about which Media(layer) it is using. The Arduino has to be able to be configured or detect which media layer it is using.

Something like this is neccesary (this is not actual code, more pseudo code):

```
String messageBuffer = "";

void Setup(){
   setupWifi(pin1,pin2);
   setupBluetooth(pin3,pin4);
}

void Loop(){
   messageBuffer = getWifiMessage();
   handleMessage(messageBuffer);
   messageBuffer = getBluetoothMessage();
   handleMessage(messageBuffer);
}

```

If you set up this correctly, you'll only have to write the buffer handling code once. Which is very useful! Handling buffers along with all the logic/effects it will cause, should be solid. You (probably) don't want different behaviour when you use bluetooth as when you use WiFi. Imagine your web-browser only working when you use copper, but not when you use glasfiber :)

***Protocol***

Your message should be exactly the same for WiFi and bluetooth. This way you won't have to deal with two different protocols and it will be easier to implement this at the other (control) side.

A good protocol/message can be this:

"@12#13,255,255,0;"

* I use the @ as an start indication. This is very usefull for receiving, since you know where to start (obviously?).
* You'll have to make rules for what will follow (maybe a set amount of characters, in my example, between @ and # it will indicate an "address". When you send it to multiple devices, you only want (in my example) device 12 to react. This often is handled by the bluetooth or wifi already, but it can be good to have some sort of unique header. So that random messages (which might look alike) won't be seen as one of your messages.
* An message ID is useful, you kinda want to have different types of messages, for either "LED brightness" or "debug request" or "set output".
* Each message could have an x amount of parameters, it's often better to separate these. It's important that you specify the maximal amount of parameters and what behavior they will cause.
* Some protocols use a set length, but an end delimiter ";" is often the best way to let the other device know your message is completely received.

*Some notes*

* Try to aim for existing protocols, it will be cool if your device is compatible and creating yet another protocol isn't particularly useful.
* Mind that possible transmitted text does not include your start/end delimiters. You could use the message length or exclusions/inclusions in this case.
* Be wary that the protocol adds overhead. But usually being able to "read" a message will make it much more easier to program a handler or generally work with it.
* Check if the message is fully received and does not have errors. If you have an error, be sure your system can handle it and will respond with a message telling so. In no way your system should lock down on error or not provide a reaction (which makes debugging a pain).

**The server**

From whatever device you're sending your stuff, it should have bluetooth and/or WiFi. Bluetooth is fairly easy and should get you started quite fast.

If you're using WiFi, you should check if your device can make a TCP/IP connection. TCP/IP is basically a "shell" around your message, to shoot it over the internet ;D it comes with some neat addressing and error checking built in (but you can't be 100% sure there will be no error between your receiver and arduino).

**But why?**

Not only is it useful to learn how to do this, having to write the handler and protocol specification for both the Wifi and bluetooth (and possible usb, rf, ethernet etc). Apart from that, in embedded systems, you want to be sure that something works, using different handlers for different physical layers will create vague specific errors and might rip up your program logic. Also, if your protocol/application is used/reviewed by more people, you'll be more certain that it works well.

# Answer
> 1 votes
*Judging from your reaction, you don't want to use a WiFi/Bluetooth/Ethernet shield*

Arduino has no built-in Bluetooth or Ethernet. The question is shifting a little towards software, but okay.

**1. Using your PC as Ethernet/Bluetooth receiver**

You can (and I believe you want to) use your PC as the receiver.

Talking in network terms, your phone has to become a "client" and your PC will become a "server".

I would advise using Processing on your PC as a "Server". Within processing you can easily set up a connection to your Arduino.

And even use your PC's bluetooth or you might just set up a "bluetooth COM port" which makes your Bluetooth device look like a serial device like the Arduino.

There is a little catch though. Processing can easily set up a TCP/IP connection. On your phone this might be a little less trivial. Your browser generally uses HTTP(s) to connect.

So you should either implement HTTP in Processing or make/use an app that supports TCP/IP message sending.

# Answer
> 0 votes
You use MIT App Inventor (http://appinventor.mit.edu/explore/ or alternatively http://www.appinventor.org/), create your own app and after that you can access all the results of Arduino on your smartphone.

---
Tags: bluetooth, web
---


title: 3 buttons digital inputs

text:
# Question
Title: 3 buttons digital inputs
I have 3 digital button inputs, I want to do a continuous scan of 3 of them until a button is pressed and to know which button has been pressed. Please help, I'm new to programming and arduino. Thanks

# Answer
> 0 votes
Try out this code. You can see result on Serial Monitor. I hope it will help you.

```
const int kPinBtn1 = 2;  // Button 1
const int kPinBtn2 = 3;  // Button 2
const int kPinBtn3 = 4;  // Button 3

void setup()
{
  pinMode(kPinBtn1, INPUT); // Button 1 as Input
  pinMode(kPinBtn2, INPUT); // Button 2 as Input
  pinMode(kPinBtn3, INPUT); // Button 3 as Input

  digitalWrite(kPinBtn1, HIGH); // Pullup
  digitalWrite(kPinBtn2, HIGH); // Pullup
  digitalWrite(kPinBtn3, HIGH); // Pullup

  Serial.begin(9600);
}

void loop()
{
  if(digitalRead(kPinBtn1) == LOW)      // If button 1 pressed
  {
    Serial.println("Button 1 pressed"); // Print "Button 1 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn2) == LOW)      // If button 2 pressed
  {
    Serial.println("Button 2 pressed"); // Print "Button 2 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn3) == LOW)      // If button 3 pressed
  {
    Serial.println("Button 3 pressed"); // Print "Button 3 pressed" on Serial Monitor
  }
}

```

---
Tags: digital, input
---


# Question
Title: Difference between print() and println()
What is the difference between print( ) and println( )?
I see none when I run a code.

# Answer
print() prints whatever you send in.
println() does the same thing, only after using println, anything new that is printed gets printed in next line, I.e. a new line is formed.
> 6 votes

# Answer
An easy way to see the difference is using `Serial.print();`/`Serial.println();`.

```
print();

```

will print out whatever you input wherever the cursor currently is. For example:

```
Serial.print("Test");
Serial.print("Words");

```

This will print:

```
TestWords_

```

The underscore marks where the cursor is (and therefore where the next print command will start). In contrast, the code:

```
Serial.println("Test");
Serial.println("Words");

```

will print the following:

```
Test
Words
_

```

You can also print multiple statements and then follow with `println` like so (note the space at the end/beginning of the strings):

```
Serial.print("These ");
Serial.print("Test");
Serial.println(" Words.");

```

to get the following output:

```
These Test Words.
_

```

You can also use `println();` to add a newline character in general. If you would print a variable that doesn't return a newline character, `println();` can be used for formatting. Example:

```
int x = 50;
Serial.print(x);
Serial.println();

```

This will print:

```
50
_

```

Finally, you can add in special characters like a tab `\t` inside your quotes for formatting. Example:

```
Serial.println("Test\tTest")

```

This will return:

```
Test    Test
_

```
> 8 votes

# Answer
The print("aString") method prints just the string "aString", but does not move the cursor to a new line. Hence, subsequent printing instructions will print on the same line.

The println("aString") method prints the string "aString" and moves the cursor to a new line.

The println() method can also be used without parameters, to position the cursor on the next line.

Regards
> 1 votes

# Answer
print() print which you want but in one line.

For example,

```
Serial.print("Hello");

```

Then output in Serial Monitor look like,

```
HelloHelloHelloHelloHello

```

println() print same things but in new line.

For example,

```
Serial.println("Hello");

```

Then output in Serial Monitor look like,

```
Hello
Hello
Hello
Hello
Hello

```
> 1 votes

---
Tags: arduino-ide
---


title: Input-Output Circuit Issue

text:
# Question
Title: Input-Output Circuit Issue
I have design a circuit with 2 led (red and UV) and 2 button.So, the circuit supposed to work like this: If i press the button for red led, the red led lights up and the uv led turn off, and if i press the button for uv led the uv led lights up and the red led turn off.

But the circuit is not work like that, when i upload the code, the uv led suddenly turn on without touching the button.The red led had no issue.The red led turn on when the button is push.And turn off when the button is unpress.But when i push the red button, the uv led does not turn off.It stay glow.The uv led turn on whatever i push the button or not.

Here is the code :

```
int red = 8;
int uv = 9;
int redbutton = 2;
int uvbutton = 3;
int redbutcondition = 0;
int uvbutcondition = 0;

void setup()
{
  pinMode (red, OUTPUT);
  pinMode (uv, OUTPUT);
  pinMode (redbutton, INPUT);
  pinMode (uvbutton, INPUT);
}

void loop()
{
  redbutcondition = digitalRead(redbutton);
  uvbutcondition = digitalRead(uvbutton);

  if (redbutcondition == HIGH)
  {
    digitalWrite(red, HIGH);
    digitalWrite(uv, LOW);
  }
  else if(uvbutcondition == HIGH);
  {
    digitalWrite(uv, HIGH);
    digitalWrite(red, LOW);
  }
}

```

# Answer
Try out this schematic. It will work.

So code will be :

```
int red = 8;
int uv = 9;
int redbutton = 2;
int uvbutton = 3;
int redbutcondition = 0;
int uvbutcondition = 0;

void setup()
{
  pinMode (red, OUTPUT);
  pinMode (uv, OUTPUT);
  pinMode (redbutton, INPUT_PULLUP);
  pinMode (uvbutton, INPUT_PULLUP);
}

void loop()
{
  redbutcondition = digitalRead(redbutton);
  uvbutcondition = digitalRead(uvbutton);

  if (redbutcondition == LOW)
  {
    digitalWrite(red, HIGH);
    digitalWrite(uv, LOW);
  }
  else if(uvbutcondition == LOW)
  {
    digitalWrite(uv, HIGH);
    digitalWrite(red, LOW);
  }
}

```
> 1 votes

---
Tags: arduino-uno, programming, led, input
---


# Question
Title: Is it possible to digitally stop a moving motorbike using an Arduino module?
I am working on a bike protection project that is supposed to be part of my CS syllabus. Although I got most of the things worked out, there is one thing that bugs me; that is to how to stop a moving bike using an Arduino built into the bike, possibly from a remote system, like another Arduino or Android app.

Is it possible to do it using an Arduino and some other modules maybe?

# Answer
> 1 votes
Assuming that you simply want to stop the engine, Gerben's comment has the answer: Put a relay in series with the ignition. Control the relay with the Arduino.

Opening the relay breaks the circuit. Ignition is now off, and the engine will no longer run.

Of course, the bike can still roll without engine power. If you want to completely immobilize the bike, you need to engage the brakes, or lock the wheels in some other way. And that takes a whole lot more hardware.

---
Tags: arduino-uno, android, project
---


# Question
Title: Correct connections: 7-segment, 4-digit display with common anode
I see this connections for 4-digit display.

All used pins set up on output. But, really, is it correct connections?

Why it used A\* input pins, and, digital pins set up on output, it is right?

Maybe all pins need used by digital pins with NPN transistors? Collector is 5V, Base - Arduino digital pin, emitter - resistor with display anode, next, collector is display segment pin, Base - Arduino digital pin, emitter - Ground.

What resistance is needed for the resistor? I think, more than 220 Ohm?

Sorry, but I'm really a beginner in electronics.

# Answer
> 0 votes
That circuit looks OK to me. It will allow you to light (reliably) a single segment at a time. The A\* pins will be used in digital output mode.

The A\* pins are connected to the four anodes of the digits - each digit has common anodes for all the segments. They should be driven HIGH to 'select' a digit.

The D\* pints are connected to the cathodes of each segment. They should be driven LOW to light that segment.

For example, to light the 'A' segment of the first digit, you would set:

* A1 HIGH, to drive the anode of the first segment
* A2, A3, A3 LOW, so that the other three segments are not driven
* D5 LOW, so that current flows from A1 to D5, lighting the digit
* D6-D12 HIGH so that no current flows from A1 through any of the other segments.

The expectation is that you will cycle around (very fast), lighting each required segment on each required digit in turn.

Without a (proper) data sheet we can't tell you what the correct resistor value is, but the 220R shown is probably OK.

---
Tags: display, 7-segment
---


# Question
Title: Is there a way to setup an interrupt to trigger at n number of clock cycles from now?
I currently have an nRF transmitter/receiver pair setup on my desk. The transmitter is sending a single byte (0xAA) every 5ms. The receiver sets an LED high to indicate that it received the byte, which is about 10us (+/-2) after the byte was sent. I want to use this nRF pulse for a precise timing/sync application with +/-0.5us accuracy so I need to filter these receiver pulses such that I can estimate the time the transmitter actually sent the byte and the time the next one *should* arrive. I created an algorithm that uses past nRF pulse times (measured in clock cycles using Teensy's ARM\_DWT\_CYCCNT register) to estimate the next pulse and it seems to be working reasonably well - though I can't say yet if I'll get the 0.5us accuracy I want.

Now I want to take that estimate and have my microcontroller set an output pin high as soon as the clock count reaches the estimated clock value. Currently I do this by waiting in a while loop and polling the register, but the loop itself takes up several hundred clock cycles which reduces my accuracy. Is there a way to instead have an interrupt trigger when the clock cycle counter reaches my estimated value? I would somehow need to set this interrupt after computing each estimate.

Thanks!

# Answer
> 1 votes
1. Use a timer to count the system clock and preload the counter with an offset that overflows in the desired cycles.
2. Use a timer to count the system clock and set a compare match a desired number of cycles out.

To expand the number of cycles, you can do fancier processing in thee Isr but the basic gist IS the same.

Other approaches also exist but the two outlined here are easier.

---
Tags: timers, teensy
---


# Question
Title: Fading from color to color using for-loop FastLEDs
I'm attempting to fade a strip of ws2812 7 pixels in length. Below I am using a for loop to increment the color red. I can fade it to red (from blue) but it will do it one pixel at a time or it just stays blue, depending where I move my r for-loop to. I need it to fade from color to color all 7 LEDs at once.

I get no errors.

I don't understand the process of getting NUM\_LEDS leds all into x then proceeding with my color changing. Seems like I'm grabbing one pixel, fading it to red, then another...

fastLeds 3.03 library, arduino 1.0.6

```
#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define BRIGHTNESS 45
#define COLOR_ORDER GRB
#define g 50
#define b 100
int r;
CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);
}

void loop(){
  for(int x = 0; x < NUM_LEDS; x++){
    delay(10);
    leds[x] = CRGB(r,g,b);
  }
  FastLED.show();
  delay(10);

  //-------------------------

  for(int x = 0; x < NUM_LEDS; x++){
    for(int r = 0; r < 254; r++) {

```

if NUM\_LEDS is holding the number 7 why can't I just do it like this below: leds\[NUM\_LEDS\]?

```
      leds[x] = CRGB(r,g,b);
      FastLED.show();
      delay(100);
    }
  }
}

```

# Answer
> 6 votes
If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

```
#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

  for( int colorStep=0; colorStep<256; colorStep++ ) {

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}

```

# Answer
> 0 votes
Here is the initial 0-255 rainbow. I dunno if this is what you are trying to achieve but i took initiative from @bigjosh's answer. This just cycles thru each rgb from 0-255. @bigjosh does start red at 0-255 allowing for more for red colors.

```
void loop(){

//start from red
  for( int colorStep=0; colorStep <= 255; colorStep++ ) {

  int r = 255;
  int g = 0;
  int b = colorStep;

  // Now loop though each of the LEDs and set each one to the current color
  for(int x = 0; x < LED_COUNT; x++){
      leds[x] = CRGB(r,g,b);
  }

  // Display the colors we just set on the actual LEDs
      delay(10);
      FastLED.show();
      }

    //into blue
      for( int colorStep=255; colorStep >= 0; colorStep-- ) {

      int r = colorStep;
      int g = 0;
      int b = 255;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(10);
  FastLED.show();
  }

//start from blue
  for( int colorStep=0; colorStep <= 255; colorStep++ ) {

      int r = 0;
      int g = colorStep;
      int b = 255;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(10);
  FastLED.show();
  }

//into green
  for( int colorStep=255; colorStep >= 0; colorStep-- ) {

      int r = 0;
      int g = 255;
      int b = colorStep;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(wait_time);
  LEDS.show();
  }

//start from green
  for( int colorStep=0; colorStep <= 255; colorStep++ ) {

      int r = colorStep;
      int g = 255;
      int b = 0;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(wait_time);
  LEDS.show();
  }

//into yellow
  for( int colorStep=255; colorStep >= 0; colorStep-- ) {

      int r = 255;
      int g = colorStep;
      int b = 0;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(wait_time);
  LEDS.show();
  }

} //end main loop

```

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


# Question
Title: Two function Reset button - long/short press
I am trying to make a circuit using an ATmega328, that has a reset button that behaves like many consumer devices:

1. A short press just restarts the micro-controller
2. A long press (5 seconds?) causes the settings to be restored to default

What is the best way to achieve this behaviour? I imagine it is going to require two pins? Can it be done just using passive components?

Thanks!

# Answer
It can be done with one button, one resistor, one capacitor and one GPIO pin (in addition to the RESET pin):

simulate this circuit – Schematic created using CircuitLab

Pressing the button causes a LOW pulse on the RESET pin (in the exact same way as the USB interface does).

During your startup procedure you read the GPIO pin you have chosen. If it's LOW the button is still being pressed in. If it's HIGH it has been released.

If you are using an Arduino with the normal bootloader the bootloader itself imposes a 2 second delay (which may be enough for you). Alternatively you will need to have your own delay in your program before reading the button to ensure that you have plenty of time to release the button so you don't accidentally reset your settings.
> 7 votes

# Answer
You can set the ***RSTDISBL*** (bit 7 on the *HIGH fuse*) to disable the external reset and use the *reset* pin as PC6 to manage the reset behavior from your program.

The second part is to capture when reset button is pressed: put some code in the **ISR for PCINT1 handler** when the pin changes (*PCINT14* pin function). If you are programming an Arduino board, the reset button is pulled up (press becomes LOW and release becomes HIGH).

Detecting long press or short press is a timer affair. According to your requirements, you will restore some EEPROM values or external state to **factory defaults** before the microcontroller resets with a long press.

This C snippet will reset the microcontroller after the short or long press (watchdog timer feature):

```
#include <avr/wdt.h>

    // ...
    wdt_enable(WDTO_15MS);
    for (;;) {}

```
> 1 votes

# Answer
Use a state machine to detect thee king presses. Once done, you can either trigger a hardware or a software reset, or to simulate one by jumping to the reset vector - you will need to write the code to support that, like an explicit initialization of variables, etc.
> 0 votes

---
Tags: atmega328, reset
---


title: Arduino to Beaglebone black

text:
# Question
Title: Arduino to Beaglebone black
I have an Arduino uno3 which gets data from a digital caliper and shows the data in serial monitor. Now I should make a connection between this Arduino and my Beaglebone black through SPI to get the data sent from caliper in Beaglebone black. and I don't know what to do and how to create codes related to this purpose.

# Answer
Have a look at the first several links from googling for *Arduino and my Beaglebone black through SPI*. Here are a few comments on those first few links:

SPI - Beaglebone Black Master Arduino Uno Slave (forum.arduino.cc topic 446924.0) – This page asks your question in more detail, and includes Beaglebone master code and Arduino Slave code. However, the poster makes an egregious error in the Arduino code by saying `Serial.println("SPI");` within the SPI interrupt service routine.

Communicate Beaglebone Black and Arduino via SPI (ulasdikme.com) – This page addresses your question in rather more detail, and apparently shows working code. It also explains how to enable SPI in the Beaglebone device tree. Note, this poster too makes an egregious error in the Arduino code by saying `Serial.println(c);` within the SPI interrupt service routine.

SPI communication: BeagleBone Black (as Master) to 4 Arduinos (as Slaves) (adurthi.com) – This page covers level shifting and device tree setup and provides ok code. It seems to cover BeagleBone concerns nicely, and has ok Arduino code as well.

One or two of the above also make reference to Nick Gammon's excellent SPI pages:

SPI - Serial Peripheral Interface - for Arduino (gammon.com.au forum id=10892) – This page is where you should start if you have questions about how SPI works. After you are familiar with SPI basics, scroll down to the “How to make an SPI slave” heading, and set up the master-slave example with two Arduinos. When you have that working, you can substitute or add a BeagleBone as master. Other code examples further down the page include “How to get a response from a slave”, slave SS pin interrupt examples, SPI via USART, speed settings, SPI on ATtinys, sending data structures, and (under the heading “SPI under IDE 1.6.0 and later”), exegesis of SPI library methods.

Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329) – This page illustrates master-slave communication between two Arduinos, using one as a slave to forward information sent from a system being debugged. Also illustrates use of I2C for similar purpose. Note, Debugging The Arduino With The SPI Interface Instead Of Serial.println() (utopiamechanicus.com) is a follow-on article, by another author, about this debugging technique.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: What is difference between analog and digital input and output, and when should i use anlog or digital (input or output)?
How should i determine whether to use input as analog or digital and same for output too?

# Answer
You will use digital pin modes when dealing with signals that are either "on" or "off", such as an LED, a switch, or another digital IC.

Analog inputs are used when you want to read the voltage potential of something. This is typically used to read analog sensors. Analog outputs are not really analog at all on the Arduino. Instead, the Arduino uses something called PWM to create a pseudo-analog signal.

You can read more about analog and digital here: https://learn.sparkfun.com/tutorials/analog-vs-digital
> 5 votes

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