title: Seeburg Consolette Jukebox

text:
# Question
Title: Seeburg Consolette Jukebox
I am working on a Seeburg Jukebox wall unit, I have it playing one track at a time form a SD card no problem. But what I need help with being new to programming is: 1. The code is long because it can play 160 songs. 2. would be nice to have it line up the next selection if possible. Any help with this code would be appreciated.

```
#include <SD.h>
#include <SPI.h>
#include <Adafruit_VS1053.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin
Adafruit_VS1053_FilePlayer musicPlayer =
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

int opto = 18;

void setup() {
  Serial.begin(9600);
  if (! musicPlayer.begin()) {}
  if (!SD.begin(CARDCS)) {}

  musicPlayer.setVolume(1,1);

  pinMode(opto, INPUT); //initialize the digital pin as an input from the opto-isolator.
  digitalWrite(opto, HIGH);} //turns on the internal pull up resistor.

void loop() {

  int number = 0;  // counts the alphabet pulses
  int letter = 0;  // counts the digit pulses.
  int buffer[4] = {1,1,1,1}; // buffer for reading input. If 4 reads in a row are all the same it is valid input.
  int buffndx = 0;
  int pausecnt = 0; // counts the number of HIGHs read in.
  int maxpause = 30; // when pausecnt reaches maxpause we are at the pause between alpa and numeric or else we are at the end of transmission.
  int countpause = false;
  buffer[0] = 1;
  buffer[1] = 1;
  buffer[2] = 1;
  buffer[3] = 1;

Serial.println("SEEBURG CONSOLETTE JUKEBOX");

  //Number loop//
  while( pausecnt < maxpause ) {
     buffer[buffndx] = digitalRead(opto); // read the input pin
     if(buffer[buffndx] != 1){}
    delay(8); // space out the reads a little.
     buffndx++;
     if (buffndx == 4) buffndx = 0; // rotate the buffer index.
     if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        number++; //increment the number counter.
        while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
    if (countpause == true) pausecnt++;}} // else no valid input

  // Letter Loop//
    pausecnt = 0;   // Reset the pausent counter. Ready for the next stream of pulses to arrive.
    countpause = false; // loop forever until a pulse is recieved.
    while( pausecnt < maxpause ) { // Begin the digit loop
    buffer[buffndx] = digitalRead(opto); // read the input pin
    delay(8);
    buffndx++;
    if (buffndx == 4) buffndx = 0; // rotate the buffer index.
    if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        letter++; //increment the aphabet counter.
        while(! ((buffer[0] == 1) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
     if (countpause == true) pausecnt++;} // else no valid input// else no valid input

  }

 //change signal//
    {number = 10 - number;
    letter = 21 - letter;}

  String signal = "";

  if(letter == 1) signal += "A";
  if(letter == 2) signal += "B";
  if(letter == 3) signal += "C";
  if(letter == 4) signal += "D";
  if(letter == 5) signal += "E";
  if(letter == 6) signal += "F";
  if(letter == 7) signal += "G";
  if(letter == 8) signal += "H";
  if(letter == 9) signal += "J";
  if(letter == 10) signal += "K";
  if(letter == 11) signal += ("L");
  if(letter == 12) signal += ("M");
  if(letter == 13) signal += ("N");
  if(letter == 14) signal += ("P");
  if(letter == 15) signal += ("Q");
  if(letter == 16) signal += ("R");
  if(letter == 17) signal += ("S");
  if(letter == 18) signal += ("T");
  if(letter == 19) signal += ("U");
  if(letter == 20) signal += ("V");

  signal += String(number);
  Serial.println(signal);
  delay(1000);

        //////////A////////////
   if(letter == 1 && number == 1);
   {musicPlayer.playFullFile("A1.mp3");}

   if(letter == 1 && number == 2);
   {musicPlayer.playFullFile("A2.mp3");}

   if(letter == 1 && number == 3);
   {musicPlayer.playFullFile("A3.mp3");}

   if(letter == 1 && number == 4);
  {musicPlayer.playFullFile("A4.mp3");}

   if(letter == 1 && number == 5);
  {musicPlayer.playFullFile("A5.mp3");}

   if(letter == 1 && number == 6);
  {musicPlayer.playFullFile("A6.mp3");}

   if(letter == 1 && number == 7);
  {musicPlayer.playFullFile("A7.mp3");}

   if(letter == 1 && number == 8);
   {musicPlayer.playFullFile("A8.mp3");}

           //////////B////////////
   if(letter == 2 && number == 1);
   {musicPlayer.playFullFile("B1.mp3");}

   if(letter == 2 && number == 2);
   {musicPlayer.playFullFile("B2.mp3");}

   if(letter == 2 && number == 3);
   {musicPlayer.playFullFile("B3.mp3");}

   if(letter == 2 && number == 4);
   {musicPlayer.playFullFile("B4.mp3");}

   if(letter == 2 && number == 5);
   {musicPlayer.playFullFile("B5.mp3");}

   if(letter == 2 && number == 6);
  {musicPlayer.playFullFile("B6.mp3");}

   if(letter == 2 && number == 7);
   {musicPlayer.playFullFile("B7.mp3");}

   if(letter == 2 && number == 8);
   {musicPlayer.playFullFile("B8.mp3");}

    //////////C////////////
   if(letter == 3 && number == 1);
   {musicPlayer.playFullFile("C1.mp3");}

   if(letter == 3 && number == 2);
   {musicPlayer.playFullFile("C2.mp3");}

   if(letter == 3 && number == 3);
   {musicPlayer.playFullFile("C3.mp3");}

   if(letter == 3 && number == 4);
   {musicPlayer.playFullFile("C4.mp3");}

   if(letter == 3 && number == 5);
   {musicPlayer.playFullFile("C5.mp3");}

   if(letter == 3 && number == 6);
    {musicPlayer.playFullFile("C6.mp3");}

   if(letter == 3 && number == 7);
    {musicPlayer.playFullFile("C7.mp3");}

   if(letter == 3 && number == 8);
    {musicPlayer.playFullFile("C8.mp3");}

       //////////D////////////
   if(letter == 4 && number == 1);
   {musicPlayer.playFullFile("D1.mp3");}

   if(letter == 4 && number == 2);
   {musicPlayer.playFullFile("D2.mp3");}

   if(letter == 4 && number == 3);
   {musicPlayer.playFullFile("D3.mp3");}

   if(letter == 4 && number == 4);
   {musicPlayer.playFullFile("D4.mp3");}

   if(letter == 4 && number == 5);
   {musicPlayer.playFullFile("D5.mp3");}

   if(letter == 4 && number == 6);
   {musicPlayer.playFullFile("D6.mp3");}

   if(letter == 4 && number == 7);
   {musicPlayer.playFullFile("D7.mp3");}

   if(letter == 4 && number == 8);
   {musicPlayer.playFullFile("D8.mp3");}

       //////////E////////////
   if(letter == 5 && number == 1);
   {musicPlayer.playFullFile("E1.mp3");}

   if(letter == 5 && number == 2);
   {musicPlayer.playFullFile("E2.mp3");}

   if(letter == 5 && number == 3);
   {musicPlayer.playFullFile("E3.mp3");}

   if(letter == 5 && number == 4);
   {musicPlayer.playFullFile("E4.mp3");}

   if(letter == 5 && number == 5);
   {musicPlayer.playFullFile("E5.mp3");}

   if(letter == 5 && number == 6);
   {musicPlayer.playFullFile("E6.mp3");}

   if(letter == 5 && number == 7);
   {musicPlayer.playFullFile("E7.mp3");}

   if(letter == 5 && number == 8);
   {musicPlayer.playFullFile("E8.mp3");}

          //////////F////////////
   if(letter == 6 && number == 1);
   {musicPlayer.playFullFile("F1.mp3");}

   if(letter == 6 && number == 2);
   {musicPlayer.playFullFile("F2.mp3");}

   if(letter == 6 && number == 3);
   {musicPlayer.playFullFile("F3.mp3");}

   if(letter == 6 && number == 4);
   {musicPlayer.playFullFile("F4.mp3");}

   if(letter == 6 && number == 5);
   {musicPlayer.playFullFile("F5.mp3");}

   if(letter == 6 && number == 6);
   {musicPlayer.playFullFile("F6.mp3");}

   if(letter == 6 && number == 7);
   {musicPlayer.playFullFile("F7.mp3");}

   if(letter == 6 && number == 8);
   {musicPlayer.playFullFile("F8.mp3");}

          //////////G////////////
   if(letter == 7 && number == 1);
  {musicPlayer.playFullFile("G1.mp3");}

  if(letter == 7 && number == 2);
  {musicPlayer.playFullFile("G2.mp3");}

  if(letter == 7 && number == 3);
  {musicPlayer.playFullFile("G3.mp3");}

  if(letter == 7 && number == 4);
  {musicPlayer.playFullFile("G4.mp3");}

  if(letter == 7 && number == 5);
  {musicPlayer.playFullFile("G5.mp3");}

  if(letter == 7 && number == 6);
  {musicPlayer.playFullFile("G6.mp3");}

  if(letter == 7 && number == 7);
  {musicPlayer.playFullFile("G7.mp3");}

  if(letter == 7 && number == 8);
  {musicPlayer.playFullFile("G8.mp3");}

            //////////H//////////;//
   if(letter == 8 && number == 1);
  {musicPlayer.playFullFile("H1.mp3");}

  if(letter == 8 && number == 2);
  {musicPlayer.playFullFile("H2.mp3");}

  if(letter == 8 && number == 3);
  {musicPlayer.playFullFile("H3.mp3");}

  if(letter == 8 && number == 4);
  {musicPlayer.playFullFile("H4.mp3");}

  if(letter == 8 && number == 5);
  {musicPlayer.playFullFile("H5.mp3");}

  if(letter == 8 && number == 6);
  {musicPlayer.playFullFile("H6.mp3");}

  if(letter == 8 && number == 7);
  {musicPlayer.playFullFile("H7.mp3");}

  if(letter == 8 && number == 8);
  {musicPlayer.playFullFile("H8.mp3");}

            //////////J//////////;//
   if(letter == 9 && number == 1);
  {musicPlayer.playFullFile("J1.mp3");}

  if(letter == 9 && number == 2);
  {musicPlayer.playFullFile("J2.mp3");}

  if(letter == 9 && number == 3);
  {musicPlayer.playFullFile("J3.mp3");}

  if(letter == 9 && number == 4);
  {musicPlayer.playFullFile("J4.mp3");}

  if(letter == 9 && number == 5);
  {musicPlayer.playFullFile("J5.mp3");}

  if(letter == 9 && number == 6);
  {musicPlayer.playFullFile("J6.mp3");}

  if(letter == 9 && number == 7);
  {musicPlayer.playFullFile("J7.mp3");}

  if(letter == 9 && number == 8);
  {musicPlayer.playFullFile("J8.mp3");}

            //////////K////////////
   if(letter == 10 && number == 1);
  {musicPlayer.playFullFile("K1.mp3");}

  if(letter == 10 && number == 2);
  {musicPlayer.playFullFile("K2.mp3");}

  if(letter == 10 && number == 3);
  {musicPlayer.playFullFile("K3.mp3");}

  if(letter == 10 && number == 4);
  {musicPlayer.playFullFile("K4.mp3");}

  if(letter == 10 && number == 5);
  {musicPlayer.playFullFile("K5.mp3");}

  if(letter == 10 && number == 6);
  {musicPlayer.playFullFile("K6.mp3");}

  if(letter == 10 && number == 7);
  {musicPlayer.playFullFile("K7.mp3");}

  if(letter == 10 && number == 8);
  {musicPlayer.playFullFile("K8.mp3");}

              //////////L////////////
   if(letter == 11 && number == 1);
  {musicPlayer.playFullFile("L1.mp3");}

  if(letter == 11 && number == 2);
  {musicPlayer.playFullFile("L2.mp3");}

  if(letter == 11 && number == 3);
  {musicPlayer.playFullFile("L3.mp3");}

  if(letter == 11 && number == 4);
  {musicPlayer.playFullFile("L4.mp3");}

  if(letter == 11 && number == 5);
  {musicPlayer.playFullFile("L5.mp3");}

  if(letter == 11 && number == 6);
  {musicPlayer.playFullFile("L6.mp3");}

  if(letter == 11 && number == 7);
  {musicPlayer.playFullFile("L7.mp3");}

  if(letter == 11 && number == 8);
  {musicPlayer.playFullFile("L8.mp3");}

              //////////M////////////
   if(letter == 12 && number == 1);
  {musicPlayer.playFullFile("M1.mp3");}

  if(letter == 12 && number == 2);
  {musicPlayer.playFullFile("M2.mp3");}

  if(letter == 12 && number == 3);
  {musicPlayer.playFullFile("M3.mp3");}

  if(letter == 12 && number == 4);
  {musicPlayer.playFullFile("M4.mp3");}

  if(letter == 12 && number == 5);
  {musicPlayer.playFullFile("M5.mp3");}

  if(letter == 12 && number == 6);
  {musicPlayer.playFullFile("M6.mp3");}

  if(letter == 12 && number == 7);
  {musicPlayer.playFullFile("M7.mp3");}

  if(letter == 12 && number == 8);
  {musicPlayer.playFullFile("M8.mp3");}

              //////////N////////////
   if(letter == 13 && number == 1);
  {musicPlayer.playFullFile("N1.mp3");}

  if(letter == 13 && number == 2);
  {musicPlayer.playFullFile("N2.mp3");}

  if(letter == 13 && number == 3);
  {musicPlayer.playFullFile("N3.mp3");}

  if(letter == 13 && number == 4);
  {musicPlayer.playFullFile("N4.mp3");}

  if(letter == 13 && number == 5);
  {musicPlayer.playFullFile("N5.mp3");}

  if(letter == 13 && number == 6);
  {musicPlayer.playFullFile("N6.mp3");}

  if(letter == 13 && number == 7);
  {musicPlayer.playFullFile("N7.mp3");}

  if(letter == 13 && number == 8);
  {musicPlayer.playFullFile("N8.mp3");}

              //////////P////////////
   if(letter == 14 && number == 1);
  {musicPlayer.playFullFile("P1.mp3");}

  if(letter == 14 && number == 2);
  {musicPlayer.playFullFile("P2.mp3");}

  if(letter == 14 && number == 3);
  {musicPlayer.playFullFile("P3.mp3");}

  if(letter == 14 && number == 4);
  {musicPlayer.playFullFile("P4.mp3");}

  if(letter == 14 && number == 5);
  {musicPlayer.playFullFile("P5.mp3");}

  if(letter == 14 && number == 6);
  {musicPlayer.playFullFile("P6.mp3");}

  if(letter == 14 && number == 7);
  {musicPlayer.playFullFile("P7.mp3");}

  if(letter == 14 && number == 8);
  {musicPlayer.playFullFile("P8.mp3");}

              //////////Q////////////
   if(letter == 15 && number == 1);
  {musicPlayer.playFullFile("Q1.mp3");}

  if(letter == 15 && number == 2);
  {musicPlayer.playFullFile("Q2.mp3");}

  if(letter == 15 && number == 3);
  {musicPlayer.playFullFile("Q3.mp3");}

  if(letter == 15 && number == 4);
  {musicPlayer.playFullFile("Q4.mp3");}

  if(letter == 15 && number == 5);
  {musicPlayer.playFullFile("Q5.mp3");}

  if(letter == 15 && number == 6);
  {musicPlayer.playFullFile("Q6.mp3");}

  if(letter == 15 && number == 7);
  {musicPlayer.playFullFile("Q7.mp3");}

  if(letter == 15 && number == 8);
  {musicPlayer.playFullFile("Q8.mp3");}

              //////////R////////////
   if(letter == 16 && number == 1);
  {musicPlayer.playFullFile("R1.mp3");}

  if(letter == 16 && number == 2);
  {musicPlayer.playFullFile("R2.mp3");}

  if(letter == 16 && number == 3);
  {musicPlayer.playFullFile("R3.mp3");}

  if(letter == 16 && number == 4);
  {musicPlayer.playFullFile("R4.mp3");}

  if(letter == 16 && number == 5);
  {musicPlayer.playFullFile("R5.mp3");}

  if(letter == 16 && number == 6);
  {musicPlayer.playFullFile("R6.mp3");}

  if(letter == 16 && number == 7);
  {musicPlayer.playFullFile("R7.mp3");}

  if(letter == 16 && number == 8);
  {musicPlayer.playFullFile("R8.mp3");}

              //////////S////////////
   if(letter == 17 && number == 1);
  {musicPlayer.playFullFile("S1.mp3");}

  if(letter == 17 && number == 2);
  {musicPlayer.playFullFile("S2.mp3");}

  if(letter == 17 && number == 3);
  {musicPlayer.playFullFile("S3.mp3");}

  if(letter == 17 && number == 4);
  {musicPlayer.playFullFile("S4.mp3");}

  if(letter == 17 && number == 5);
  {musicPlayer.playFullFile("S5.mp3");}

  if(letter == 17 && number == 6);
  {musicPlayer.playFullFile("S6.mp3");}

  if(letter == 17 && number == 7);
  {musicPlayer.playFullFile("S7.mp3");}

  if(letter == 17 && number == 8);
  {musicPlayer.playFullFile("S8.mp3");}

              //////////T////////////
   if(letter == 18 && number == 1);
  {musicPlayer.playFullFile("T1.mp3");}

  if(letter == 18 && number == 2);
  {musicPlayer.playFullFile("T2.mp3");}

  if(letter == 18 && number == 3);
  {musicPlayer.playFullFile("T3.mp3");}

  if(letter == 18 && number == 4);
  {musicPlayer.playFullFile("T4.mp3");}

  if(letter == 18 && number == 5);
  {musicPlayer.playFullFile("T5.mp3");}

  if(letter == 18 && number == 6);
  {musicPlayer.playFullFile("T6.mp3");}

  if(letter == 18 && number == 7);
  {musicPlayer.playFullFile("T7.mp3");}

  if(letter == 18 && number == 8);
  {musicPlayer.playFullFile("T8.mp3");}

              //////////U////////////
   if(letter == 19 && number == 1);
  {musicPlayer.playFullFile("U1.mp3");}

  if(letter == 19 && number == 2);
  {musicPlayer.playFullFile("U2.mp3");}

  if(letter == 19 && number == 3);
  {musicPlayer.playFullFile("U3.mp3");}

  if(letter == 19 && number == 4);
  {musicPlayer.playFullFile("U4.mp3");}

  if(letter == 19 && number == 5);
  {musicPlayer.playFullFile("U5.mp3");}

  if(letter == 19 && number == 6);
  {musicPlayer.playFullFile("U6.mp3");}

  if(letter == 19 && number == 7);
  {musicPlayer.playFullFile("U7.mp3");}

  if(letter == 19 && number == 8);
  {musicPlayer.playFullFile("U8.mp3");}

            //////////V////////////
   if(letter == 20 && number == 1);
  {musicPlayer.playFullFile("V1.mp3");}

  if(letter == 20 && number == 2);
  {musicPlayer.playFullFile("V2.mp3");}

  if(letter == 20 && number == 3);
  {musicPlayer.playFullFile("V3.mp3");}

  if(letter == 20 && number == 4);
  {musicPlayer.playFullFile("V4.mp3");}

  if(letter == 20 && number == 5);
  {musicPlayer.playFullFile("V5.mp3");}

  if(letter == 20 && number == 6);
  {musicPlayer.playFullFile("V6.mp3");}

  if(letter == 20 && number == 7);
  {musicPlayer.playFullFile("V7.mp3");}

  if(letter == 20 && number == 8);
  {musicPlayer.playFullFile("V8.mp3");}
}

```

# Answer
> 3 votes
This answer only involves help for the first problem:

1. The code is long because it can play 160 songs

Also, you can align your code by selecting it and press Ctrl-K.

I will go part by part to improve it (leaving the manual work to you):

**Align code**

```
#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)

```

Align this code, making all the values under each other nicely and comments starting at the same column.

**Use for loop**

```
  buffer[0] = 1;
  buffer[1] = 1;
  buffer[2] = 1;
  buffer[3] = 1;

```

You can use a for loop, like:

```
for (int n = 0; n < 4; n++)
{
    buffer[n] = 1;
}

```

However, you can remove this code, since the values are already initialized in:

```
int buffer[4] = {1,1,1,1}; // buffer for reading input. If 4 reads in a row are all the same it is valid input.

```

**Prevent almost identical duplicate code**

In the number/letter loop part:

```
//Number loop//
  while( pausecnt < maxpause ) {
     buffer[buffndx] = digitalRead(opto); // read the input pin
     if(buffer[buffndx] != 1){}
    delay(8); // space out the reads a little.
     buffndx++;
     if (buffndx == 4) buffndx = 0; // rotate the buffer index.
     if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        number++; //increment the number counter.
        while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
    if (countpause == true) pausecnt++;}} // else no valid input

  // Letter Loop//
    pausecnt = 0;   // Reset the pausent counter. Ready for the next stream of pulses to arrive.
    countpause = false; // loop forever until a pulse is recieved.
    while( pausecnt < maxpause ) { // Begin the digit loop
    buffer[buffndx] = digitalRead(opto); // read the input pin
    delay(8);
    buffndx++;
    if (buffndx == 4) buffndx = 0; // rotate the buffer index.
    if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        letter++; //increment the aphabet counter.
        while(! ((buffer[0] == 1) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
     if (countpause == true) pausecnt++;} // else no valid input// else no valid input

  }

```

First add brackets and align them (I do it for the Number part):

```
 while( pausecnt < maxpause )
 {
   buffer[buffndx] = digitalRead(opto); // read the input pin

   if(buffer[buffndx] != 1)
   {
   }

   delay(8); // space out the reads a little.
   buffndx++;

   if (buffndx == 4)
   {
     buffndx = 0; // rotate the buffer index.
   }

   if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) )
   {
     // we got valid input so proccess it.
     pausecnt = 0; // we got our pulse so restart the clock for the next one.
     number++; //increment the number counter.
     while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) )
     {
        //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index

        if (buffndx == 4)
        {
          buffndx = 0;
        }
      } // rotate the buffer index.

      countpause = true; //we are receiving input so start counting pauses instead of looping forever.
      continue;
    }
    else
    {
      if (countpause == true)
      {
        pausecnt++;
      }
    } // else no valid input

```

Note it is longer, but much clearer (clear code is more important than short code).

Now because the code starting from:

```
buffer[buffndx] = digitalRead(opto); // read the input pin
...

```

Until the end of the number loop code is almost equal to the letter loop code, try to find the differences between the two parts: only the `number` and `letter` variable. So you make a new function (e.g. `processKey`), you pass the number or the letter (so for the number call `processKey(number)` and for the letter call `processKey(letter)`. Note that both are integers. The new function will be:

```
int processKey(int key) // Item is a number or letter
{
    ...
    return key;
}

```

You return a key (which is the possibly increased value (because of `number++` in the original code. A slightly advanced way is to pass it as pointer:

```
void processKey(int* key) // Item is a number or letter

```

and change the key with `(*key)++;` and call the functions with `processKey(&number)` and `processKey(&letter)`.

**Use define**

Note that instead of 4, it's better to use a #define.

```
     if(buffer[buffndx] != 1){}

```

**Remove dead code**

This line does not anything; to make this clear, always align brackets:

```
     if(buffer[buffndx] != 1)
     {
     }

```

**Always use brackets { }**

```
if (buffndx == 4) buffndx = 0; // rotate the buffer index.

```

Use:

```
if (buffndx == 4)
{
    buffndx = 0; // rotate the buffer index.
}

```

**Avoid code duplication**

```
     if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        number++; //increment the number counter.
        while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH

```

In this part you check twice to see if values are 0 or 1, make a function for this (e.g. areAllValues(buffer, 0) for the first call and areAllValues(buffer, 1) for the next. If 0 and 1 are the only values use a boolean (True/False).

```
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.

```

Use here the same #define that I proposed above.

**Do not check against true/false**

```
    if (countpause == true) pausecnt++;}} // else no valid input

```

It is not needed to check against true:

```
    if (countpause) ...

```

**Use correct casing**

Also it's better to use always correct casing, so `countPause` instead of `countpause`.

**Avoid repetition of if statements (1)**

```
  if(letter == 1) signal += "A";
  if(letter == 2) signal += "B";
  if(letter == 3) signal += "C";
  if(letter == 4) signal += "D";
  if(letter == 5) signal += "E";
  if(letter == 6) signal += "F";
  if(letter == 7) signal += "G";
  if(letter == 8) signal += "H";
  if(letter == 9) signal += "J";
  if(letter == 10) signal += "K";
  if(letter == 11) signal += ("L");
  if(letter == 12) signal += ("M");
  if(letter == 13) signal += ("N");
  if(letter == 14) signal += ("P");
  if(letter == 15) signal += ("Q");
  if(letter == 16) signal += ("R");
  if(letter == 17) signal += ("S");
  if(letter == 18) signal += ("T");
  if(letter == 19) signal += ("U");
  if(letter == 20) signal += ("V");

```

Instead of this, use the ASCII character value.

```
 if ((letter >= 1) && (letter <= 20))
 {
     signal += (char) ((int)('A') + letter - 1);
 {

```

**Avoid repetition of if statements (2)**

For your largest part:

```
 if(letter == 1 && number == 1);
   {musicPlayer.playFullFile("A1.mp3");}

   if(letter == 1 && number == 2);
   {musicPlayer.playFullFile("A2.mp3");}

 ...

```

Use two if statements, filling in the first and second character of the file name.

```
char[] fileName = "XX.mp3";

if ((letter >= 1) && (letter <= 20))
{
    if ((number >= 1) && (number <= 8))
    {
       fileName[0] = (char) ((int)('A') + letter - 1);
       fileName[1] = (char) ((int)('0') + number - 1);
       musicPlayer.playFullFile(fileName);
    }
}

```

**Start with 0**

Btw, for software engineers, it is more common to start arrays/counters etc. with 0 instead of 1; that saves some `- 1` conversions.

---
Tags: programming, code-review
---


# Question
Title: changing state of an LED using a pushbutton leads to unstable result
I am trying to run this code:

```
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);

  if (buttonState = HIGH && lastButtonState != buttonState) {
    flag = !flag;
    if (flag){
      digitalWrite(ledPin13, LOW);
    } else {
      digitalWrite(ledPin13, HIGH);
    }
  }
}

```

on this SimulIDE model:

```
<circuit reactStep="50" animate="0" type="simulide_0.1" noLinStep="10" noLinAcc="5" speed="1000000">

Node-16:
<item labelrot="0" y="-204" valLabRot="0" valLabelx="0" valLabely="0" hflip="1" vflip="1" x="-220" labelx="-16" labely="-24" Show_id="false" objectName="Node-16" itemtype="Node" id="Node-16" rotation="0"/>

Arduino Uno-4:
<item hflip="1" Show_id="true" valLabely="0" itemtype="Arduino" vflip="1" labelx="0" objectName="Arduino Uno-4" labely="-20" y="-244" Ser_Port="false" labelrot="0" rotation="0" Program="../../Google Drive/Active projects/SRL/Students/Damian2019/Simulation/20190409/noDelay_20190409/noDelay_20190409.ino.standard.hex" Ser_Monitor="false" id="Arduino Uno-4" valLabelx="0" Mhz="16" valLabRot="0" x="-148"/>

Resistor-3:
<item Unit=" O" hflip="1" Show_id="false" valLabely="6" itemtype="Resistor" Show_res="true" vflip="1" labelx="-12" objectName="Resistor-3" labely="-24" y="-164" labelrot="0" rotation="-90" Resistance="100" id="Resistor-3" valLabelx="-16" valLabRot="0" x="-220"/>

Push-2:
<item labelrot="0" y="-308" valLabRot="0" valLabelx="0" valLabely="0" hflip="1" vflip="1" x="-100" labelx="-16" labely="-24" Show_id="false" objectName="Push-2" itemtype="Push" id="Push-2" rotation="0"/>

Connector-5:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Resistor-3-lPin" labelx="-16" objectName="Connector-5" labely="-24" y="-148" endpinid="Arduino Uno-4-GND0" enodeid="Circ_eNode-6" labelrot="0" pointList="-220,-148,-220,-108,-140,-108" rotation="0" id="Connector-5" valLabelx="0" valLabRot="0" x="-220"/>

Connector-11:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Push-2-rnod" labelx="-16" objectName="Connector-11" labely="-24" y="-308" endpinid="Arduino Uno-4-V5V" enodeid="Circ_eNode-12" labelrot="0" pointList="-84,-308,44,-308,44,-148,4,-148" rotation="0" id="Connector-11" valLabelx="0" valLabRot="0" x="-84"/>

Connector-9:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Push-2-lnod" labelx="-16" objectName="Connector-9" labely="-24" y="-308" endpinid="Node-16-0" enodeid="enode-15" labelrot="0" pointList="-116,-308,-220,-308,-220,-204" rotation="0" id="Connector-9" valLabelx="0" valLabRot="0" x="-116"/>

Connector-15:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Arduino Uno-4-PD7" labelx="-16" objectName="Connector-15" labely="-24" y="-172" endpinid="Node-16-1" enodeid="enode-15" labelrot="0" pointList="-140,-172,-172,-172,-172,-204,-220,-204" rotation="0" id="Connector-15" valLabelx="0" valLabRot="0" x="-140"/>

Connector-17:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Node-16-2" labelx="-16" objectName="Connector-17" labely="-24" y="-204" endpinid="Resistor-3-rPin" enodeid="enode-15" labelrot="0" pointList="-220,-204,-220,-180" rotation="0" id="Connector-17" valLabelx="0" valLabRot="0" x="-220"/>

PlotterWidget-13:
<item modal="false" childrenRect="" normalGeometry="" baseSize="" geometry="" sizeIncrement="" windowOpacity="1" windowModified="false" enabled="true" maximumSize="" childrenRegion="" maximumHeight="200" inputMethodHints="0" mouseTracking="false" minimumSize="" frameGeometry="" sizeHint="" windowIconText="" locale="" minimumSizeHint="" height="200" isActiveWindow="true" x="0" accessibleName="" layoutDirection="0" autoFillBackground="false" width="200" windowFilePath="" windowModality="0" maximized="false" sizePolicy="" MinVolt="-500" fullScreen="false" windowTitle="" windowIcon="" maximumWidth="1000" objectName="PlotterWidget-13" toolTip="" toolTipDuration="-1" focus="false" MaxVolt="500" palette="" font="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" whatsThis="" pos="" minimumWidth="200" minimumHeight="200" size="" focusPolicy="0" itemtype="Plotter" updatesEnabled="true" accessibleDescription="" y="0" rect="" frameSize="" minimized="false" acceptDrops="false" styleSheet="" cursor="" visible="false" statusTip="" contextMenuPolicy="1"/>

SerialPortWidget-14:
<item modal="false" childrenRect="" normalGeometry="" SettingsProp="COM1,0,3,0,0,0" baseSize="" geometry="" sizeIncrement="" windowOpacity="1" windowModified="false" enabled="true" maximumSize="" childrenRegion="" maximumHeight="170" inputMethodHints="0" mouseTracking="false" minimumSize="" frameGeometry="" sizeHint="" windowIconText="" locale="" minimumSizeHint="" height="141" isActiveWindow="true" x="0" accessibleName="" layoutDirection="0" autoFillBackground="false" width="313" windowFilePath="" windowModality="0" maximized="false" sizePolicy="" fullScreen="false" windowTitle="Settings" windowIcon="" maximumWidth="450" objectName="SerialPortWidget-14" toolTip="" toolTipDuration="-1" focus="false" palette="" font="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" whatsThis="" pos="" minimumWidth="0" minimumHeight="0" size="" focusPolicy="0" itemtype="SerialPort" updatesEnabled="true" accessibleDescription="" y="0" rect="" frameSize="" minimized="false" acceptDrops="false" styleSheet="" cursor="" visible="false" statusTip="" contextMenuPolicy="1"/>

</circuit>

```

and I expect the LED to be turned on-off everytime I push the button, however the result is unstable:

```

```

I would appreciate if you could help me know if there is something wrong with my code or circuit and I should expect the same behavior on an actual hardware, or this is a simulation issue?

**P.S.1.** All file can also be downloaded from here.

**P.S.2.** I'm using this example from Arduino.org website.

**P.S.3.** I also tried using an actual Arduino, also implementing the suggestions below. However the issue is not resolved. You may see the video here.

# Answer
Certain Changes in your code:

```
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH && lastButtonState != buttonState) {
    lastButtonState = buttonState;
    flag =!flag;
    if (flag){
      digitalWrite(ledPin13, LOW);
    } else {
      digitalWrite(ledPin13, HIGH);
    }
  }
}

```

Secondly your hardware model is not good. ANODE of LED must be connected to PIN13 and Cathode to GND. And switch must be placed between 3.3 V and Pin7 only. In your model by closing switch you are shorting 3.3V and GND. If you had provided an external pullup then you should use at minimum a 4.7K resistor value. 100ohm never works.

I don't have software for Design so I used Paint and made a sketch for you.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

# Answer
I identify a few problems here:

* The 100 Ohm pulldown resistor for the button is way too low. 1 kOhm to 100 kOhm is typically used here.
* `if( buttonState = HIGH )` does not *compare*, it *assigns* buttonState to HIGH (overwriting the value read with `digitalRead(buttonPin)`). Use the compare-for-equality operator `==` here, otherwise the `if` just checks if buttonState has been assigned a "truthlike" value (incidentally, HIGH is one of them).
* As others have already commented, lastButtonState must be set somewhere after the `if`-block!

Since many Arduinos do have pullup resistors built in, I'd say: drop the resistor completely, instead initialize the button input pin (7) to use its built-in pullup resistor ... this will invert the logic and you'll have to connect the button between pin 7 and GND (i.e. swapping button and resistor), though:

```
    pinMode(buttonPin, INPUT_PULLUP);

```

This will have the same result as if you replaced the 100 Ohm resistor with a 20 kOhm resistor after swapping button and resistor -- but that resistor is now inside the Arduino. (Take care if you use "Arduino-compatible" boards; sometimes they lack the pullup resistors or have them fixed!).

There still is one problem: bouncing. Pressing a mechanical button leads to the contacts inside the button to bounce a bit against each other, leading to a *very* fast HIGH-LOW-HIGH-LOW-etc signal before it settles on the target state. You can alleviate this a bit by adding a `delay(5)` at the end of your `loop()`, but using a button library (e.g. Button, available in the Arduino IDE Library Manager) that debounces the signal will lead to better results most of the time.

This will lead to this code (also including the ternary operator hint by Michel Keijzers):

```
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW && lastButtonState != buttonState) {
    flag = !flag;
    digitalWrite(ledPin13, flag ? LOW : HIGH);
  }

  lastButtonState = buttonState;
  delay(5);
}

```

This should do the trick (I didn't try it, though).
> 2 votes

# Answer
There are already great answers, but I also found out about the interrupt functionality:

```
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

```

some point:

* no matter using interrupt or the methods above tho process will not achieve stable / deterministic result. The issue lies in the hardware of the push-button and there will be fluctuations which can be interpreted by the MCU. One way to alleviate is to use delay.
* The
* `attachInterrupt` has four modes `LOW`, `Change`, `FALLING` and `RISING`. The `FALLING` and `RISING` modes are the one to be used. the other two also lead to very unpredictable result.
* Only pins `1` and `2` can be used for interrupts.
* There is also the option to mix the two methods which you can see here, but I'm not sure if it will improve the stability.

I used this video and information on this page.
> 1 votes

# Answer
This is a comment (but could not use text alignment in a comment):

Instead of

```
if (flag){
  digitalWrite(ledPin13, LOW);
} else {
  digitalWrite(ledPin13, HIGH);
}

```

You can use:

```
digitalWrite(ledPin13, flag ? LOW : HIGH);

```

(It is functionally 100% equal though).
> 0 votes

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


title: expected `}' at end of input

text:
# Question
Title: expected `}' at end of input
```
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup() {
    Serial.begin(9600);
    pinMode(6, OUTPUT);
    pinMode(9, OUTPUT);
 }
void loop(){
 sensorVal = analogRead(A1);

 Serial.print("Sensor Value: ");
 Serial.print(sensorVal);

 float voltage = (sensorVal*5.0)/1024.0;
    Serial.print("Volts: ");
    Serial.print(voltage);

 float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
 float pressure_bar = pressure_pascal/10e5;
   Serial.print("Pressure = ");
   Serial.print(pressure_bar);
   Serial.println(" bars");
   Serial.print("Pressure = ");
   {
 for(int a = 255; a>=0;a--)
 {
   analogWrite(6,a);
 if (pressure_bar = 1600){
   analogWrite (6, a);
 if (pressure_bar > 1600){
   analogWrite (6, a);
 }
 for(int a = 0; a<256; a++)
 {
  analogWrite(6, a);
 {
 if(pressure_bar < 1600){
  analogWrite (6, a);
 }
 for(int b = 255; b>=0;b--)
 {
 analogWrite(9, b);
 {
 if (pressure_bar == 1600){
   analogWrite (9, b);
 if(pressure_bar < 1600){
   analogWrite (9, b);
}
 for(int b = 0; b<256; b++)
 {
   analogWrite(9, b);
 {
if (pressure_bar > 1600){
   analogWrite (9, b);
   }
  }

```

# Answer
Some guidelines for programming:

**Start each statement on a new line**

```
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup() {
Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
} void loop(){
sensorVal = analogRead(A1);

Serial.print("Sensor Value: "); Serial.print(sensorVal);

float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: "); Serial.print(voltage);

float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
float pressure_bar = pressure_pascal/10e5;
Serial.print("Pressure = ");
Serial.print(pressure_bar);
Serial.println(" bars");
Serial.print("Pressure = "); {
for(int a = 255; a>=0;a--) {
analogWrite(6,a);
if (pressure_bar = 1600){
analogWrite (6, a);
if (pressure_bar > 1600){
analogWrite (6, a); }
for(int a = 0; a<256; a++) {
analogWrite(6, a); {
if(pressure_bar < 1600){
analogWrite (6, a); }
for(int b = 255; b>=0;b--) {
analogWrite(9, b); {
if (pressure_bar == 1600){
analogWrite (9, b);
if(pressure_bar < 1600){
analogWrite (9, b); }
for(int b = 0; b<256; b++) {
analogWrite(9, b); {
if (pressure_bar > 1600){
analogWrite (9, b);
} }

```

**Use brackets and align them**

.. so each pair of { and } is on the same column and align code with brackets to be indented 2, 3 or 4 spaces

```
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");
  {
    for(int a = 255; a>=0;a--)
    {
      analogWrite(6,a);
      if (pressure_bar = 1600)
      {
        analogWrite (6, a);
        if (pressure_bar > 1600)
        {
          analogWrite (6, a);
        }
        for(int a = 0; a<256; a++)
        {
          analogWrite(6, a);
          {
            if(pressure_bar < 1600)
            {
              analogWrite (6, a);
            }
            for(int b = 255; b>=0;b--)
            {
              analogWrite(9, b);
              {
                if (pressure_bar == 1600)
                {
                  analogWrite (9, b);
                  if(pressure_bar < 1600)
                  {
                    analogWrite (9, b);
                  }
                  for(int b = 0; b<256; b++)
                  {
                    analogWrite(9, b);
                    {
                      if (pressure_bar > 1600)
                      {
                        analogWrite (9, b);
                      }
                    }

```

**Remove superfluous brackets**

As you can see, you are having some superfluous/missing brackets. What you want is probably something like:

```
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");

  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar = 1600)
    {
      analogWrite (6, a);
    }
    if (pressure_bar > 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar < 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar == 1600)
    {
      analogWrite (9, b);
    }
    if(pressure_bar < 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar > 1600)
    {
      analogWrite (9, b);
    }
  }
}

```

**Remove duplicate code**

In the if statement, you perform twice the same code (both you send an `analogWrite` with the same value, so the code (from the for loops can be reduced to:

```
  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar >= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar <= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar <= 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar >= 1600)
    {
      analogWrite (9, b);
    }
  }
}

```

**Unclear**

What is unclear why you first write an analog value, and directly afterward (in each if) you write the same value. I'm not sure what you really want here. Either you want to write to a different pin, or you want a delay (to have the value having some effect), I'm just not sure.
> 3 votes

# Answer
Look at your open brackets { vs closing brackets, }. You need the same number of each. If have this in the Arduino IDE and use CTRL-T, they are somewhat easy to find. I just looked, and I can spot them pretty easily.

```
int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
}
void loop()
{
sensorVal = analogRead(A1);
Serial.print("Sensor Value: ");
Serial.print(sensorVal);
float voltage = (sensorVal*5.0)/1024.0;
Serial.print("Volts: ");
Serial.print(voltage);
float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
float pressure_bar = pressure_pascal/10e5;
Serial.print("Pressure = ");
Serial.print(pressure_bar);
Serial.println(" bars");
Serial.print("Pressure = ");
{                            << bracket for what?
for(int a = 255; a>=0;a--) { << missing closing bracket
  analogWrite(6,a);
  if (pressure_bar = 1600){   << missing closing bracket
   analogWrite (6, a);
     if (pressure_bar > 1600){
     analogWrite (6, a);
     }
  for(int a = 0; a<256; a++) {
    analogWrite(6, a);
    {                      << wrong direction
    if(pressure_bar < 1600){
       analogWrite (6, a);
    }
  for(int b = 255; b>=0;b--) {
    analogWrite(9, b);
   {                           << wrong direction
    if (pressure_bar == 1600){ << missing closing bracket
      analogWrite (9, b);
      if(pressure_bar < 1600){ << missing closing bracket
        analogWrite (9, b);
    }
   for(int b = 0; b<256; b++) {
     analogWrite(9, b);
   {                            << wrong direction
   if (pressure_bar > 1600){
     analogWrite (9, b);
   }
}  << closing bracket for loop

```
> 1 votes

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


title: Please answer this

text:
# Question
Title: Please answer this
what is the difference between transmitting and receiving leds(circled) connected to sensor board and ir emitter and receiver diode shown in second pic?Will the output change it i replace the former leds by latter?if yes then how? Second pic is from https://www.amazon.in/CENTIoT-Universal-Infrared-Emission-Receiver/dp/B071NK3KD4/ref=sr\_1\_10?keywords=ir+leds&qid=1554913735&s=gateway&sr=8-10

# Answer
The dark coated LED has a filter, that filters out other wavelengths except for the one, that it is specified for. The clear one doesn't have this coating, since it is used for sending. If you replace the coated one by an uncoated version, the results may get worse, when other IR sources are present (like the sun).

Also the specifications of the LEDs might be different, we can only speculate about that without knowing the part numbers of the used LEDs.

All in all it might not be a good idea to exchange the LEDs for one another. You haven't stated, why you want to do this.
> 0 votes

---
Tags: sensors
---


# Question
Title: What is the purpose of Serial.println() without an argument?
I am attempting to control a stepper motor with Sparkfun's Big Easy Driver, and I see the line "Serial.println();" they put in the example code. Why is there no argument and what function does this serve?

```
//Declare pin functions on Arduino
#define stp 2
#define dir 3
#define MS1 4
#define MS2 5
#define MS3 6
#define EN  7

//Declare variables for functions
char user_input;
int x;
int y;
int state;

void setup() {
  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
  pinMode(MS1, OUTPUT);
  pinMode(MS2, OUTPUT);
  pinMode(MS3, OUTPUT);
  pinMode(EN, OUTPUT);
  resetBEDPins(); //Set step, direction, microstep and enable pins to default states
  Serial.begin(9600); //Open Serial connection for debugging
  Serial.println("Begin motor control");
  Serial.println();
  //Print function list for user selection
  Serial.println("Enter number for control option:");
  Serial.println("1. Turn at default microstep mode.");
  Serial.println("2. Reverse direction at default microstep mode.");
  Serial.println("3. Turn at 1/16th microstep mode.");
  Serial.println("4. Step forward and reverse directions.");
  Serial.println();
}

```

# Answer
It simply prints a newline to the serial monitor. Just for spacing.
> 2 votes

# Answer
To complement jose can u c's answer: the Arduino Serial object uses CRLF as the end-of-line marker. That's an ASCII CR (carriage return, or `'\r'` in C) followed by ASCII LF (line feed, `'\n'` in C). Thus,

```
Serial.println();

```

is equivalent to

```
Serial.print("\r\n");

```
> 2 votes

---
Tags: serial, arduino-mega
---


# Question
Title: Can I daisychain multiple Arduino Nanos to a single USB port (specialized purpose)
I need to have several Nanos on one USB port. They will have separate power, so power constraints won't be a concern. I need them all to go through the same serial port. They will never get anything sent to them, and should never send data simultaneously. Each one is connected to a switch, and upon pressing the switch, will send an 8-digit serial number over serial. I want to have a VB.NET application which listens over this shared serial COM for numbers, and collects them all, displaying them in a history list. Can this work?

# Answer
> 1 votes
For a USB topology to operate one needs a USB controller which knows about all the different USB protocols necessary to communicate with all the different USB peripherals (this is why a USB controller is usually a fully capable computer) all connected through a USB hub. It is unlikely a USB network could be created using only peripheral USB devices which were wired directly together.

To communicate between several Arduinos and a computer it would be much easier to use a serial bus made for multiple drops like RS485. There are many RS485 to USB converters available like this one for computers that do not have an RS485 port.

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


# Question
Title: W5100 Ethernet Shield to Custom Board Problem
I've been using an Arduino Ethernet shield and an Arduino Mega in my project, but now I'm trying to migrate all the components onto my own PCB. My board uses a W5100 same as the Arduino, but nothing shows up when I connect Ethernet to my computer. Even if there is no communication with the MCU the W5100 should show up as a network device and starting pinging.

I have spent A LOT of time troubleshooting this issue, and I would like to confirm one thing. Using the factory default register settings, I should be able to just connect the W5100 to my computer, and it will start pinging back and forth and be identified as a network device . . . assuming I have the circuit set up correctly just like the Ethernet shield. I used a combination of the recommendations from Wiznet and the Arduino Ethernet shield schematic to make mine.

Edit: Here is my schematic for the Ethernet module. The question I'm really trying to get answered first is regarding the default state of the W5100. Do I need to set some registers or something to get the W5100 in the same state it is in on the Arduino shield?

# Answer
> 2 votes
A bit late to the party but... it may be that you are using pins 1, 2, 3 and 4 instead of 1, 2, 3 and 6 on the RJ45. It is unclear whether you are connecting via a header, in which case you my disregard this, or straight to the RJ45, in which case you need to change your pin:

```
1. white/orange
2. orange
3. white/green
6. green

```

# Answer
> 1 votes
You need to connect the SCS pin of W5100 to Arduino mega 2560 PB4 pin (pin number 23 raw IC pin number). Then only the W5100 will be selected in active mode. for reference: https://www.arduino.cc/en/Reference/Ethernet "Arduino communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. **On both boards, pin 10 is used as SS.** **On the Mega, the hardware SS pin, 53, is not used to select the W5100,** but it must be kept as an output or the SPI interface won't work."

---
Tags: shields, ethernet, pcb-design
---


# Question
Title: Measure cycle count and time of Digital Input
I am currently working on a project which is read a digital input signal from a machine. The machine operation is as below:

when the mold close, the machine gives the "HIGH" signal, when mold is open the machine gives "LOW" signal. A cycle is counted as one cycle when from the mold close --\> open --\> close.

My goal is to count the cycle and cycle time of each cycle. I am struggling when the Input comes from HIGH to LOW. Appreciate your help to give me some guildance on this project.

```
int MoldInput = 2;
int MoldState = 0;
int lastMoldState = 0;
int CycleTimeCounter = 0;
int CycleCount = 0;
unsigned long CycleTime;
volatile unsigned long TimeTemp1 = 0;
volatile unsigned long TimeTemp2 = 0;
void setup() {
  // put your setup code here, to run once:
  pinMode (MoldInput,INPUT);
  attachInterrupt(0, RealTimeMoldClose, RISING);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(CycleTime);
}
void RealTimeMoldClose(){
  unsigned long t = millis();
  TimeTemp2 = t;
  CycleTime = TimeTemp2 - TimeTemp1;
  TimeTemp1 = TimeTemp2;
}

```

# Answer
> 1 votes
You don't need to do anything on HIGH to LOW. For example, if you are counting how often a door opens you don't also need to count how often it closes, because it must close before it re-opens.

I don't see the point of the interrupt since your code is doing nothing else than checking if the interrupt occurred, so it may as well be checking if the input has changed anyway. This code is simpler:

```
const int MoldInput = 2;

int lastMoldState = 0;
unsigned long startTime = 0;
unsigned long TotalTime = 0;
unsigned long CycleTimeCounter = 0;

void setup() {
  pinMode (MoldInput, INPUT);
  Serial.begin(115200);
}

unsigned long lastReportedCycleCount = 0;

void loop() {
  int MoldState = digitalRead(MoldInput);
  if (MoldState != lastMoldState) {
    if (MoldState == HIGH) {
      CycleTimeCounter++;  // count times it was high
      TotalTime += millis() - startTime;  // add up time interval
      startTime = millis ();
      delay (100);    // debounce
    }  // end of state being HIGH
    lastMoldState = MoldState;
  }   // end of state change

  if (CycleTimeCounter % 10 == 0 && CycleTimeCounter != lastReportedCycleCount)
    {
    Serial.print (F("Average time after "));
    Serial.print (CycleTimeCounter);
    Serial.print (F(" cycles is "));
    Serial.print (TotalTime / CycleTimeCounter);
    Serial.println (F(" milliseconds"));
    lastReportedCycleCount = CycleTimeCounter;
    }
} // end of loop

```

---
Tags: arduino-uno, interrupt, timers
---


# Question
Title: Will a simple RC filter work with my mechanical rotary encoder, or do I need a Schmitt trigger?
I bought some incremental rotary encoders online https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf

The spec sheet for those suggests a filter circuit for the outputs of the encoder that looks like this:

Adding that filter reduces, but doesn't eliminate, spurious signals from the encoder. I wanted to avoid adding Schmitt triggers or other solid state components since I don't have a lot of room left on my proto board for an IC, but I'm beginning to think I will have to add something with hysteresis since any filter that reduces jitter will also slow the rise time/fall time for the output of the encoder and keep it in the "gray area" between LOW and HIGH for a digital signal for too long.

Is there a way to wire these encoders and/or software that lets you read from them with simple passive filtering and/or software rather than adding something like a latch or Schmitt trigger for debouncing?

# Answer
Having just chased a problem using a software based debounce for several days, what I'll add is that for the encoders I was using (green no-name Chinese ones), if you put 10mA though the contacts then the signal is a LOT better. So change the 10k to 470 Ohms.

Or if using 3.3V use 330 Ohms. Solved all my problems.
> 3 votes

# Answer
The answer seems to be no. I added the RC filter suggested by the manufacturer and the results still jump around (The values sometimes increase by several steps at once, or decrease even when turning the decoder clockwise.)

I added a CMOS Schmitt trigger and it resolves the problem.

I really don't understand why that is, since apparently Arduino digital inputs have integrated Schmitt triggers. This thread from the Arduino forum discusses it at length:

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

The only thing I can think of is that the hysteresis band of the built-in Schmitt triggers is too narrow (2.08 - 2.63V at VCC of 5V and typical operating conditions) and the filtered voltage still bounces between those values.

I'm using a MC14584B Schmitt trigger that I had lying around, and it looks like it's hysteresis band is ≈2.1V to 2.7V (typical at 25°C) which is slightly wider and goes slightly higher than the hysteresis range of the Arduino itself.

The differences seem quite small though, so I'm confused as to why the Schmitt trigger eliminates the "bobbling" of values I'm seeing.

I could add delay based debouncing code to my Arduino program, but the decoder handler is written as an ISR and those are supposed to be as fast as possible, and the millis() function is supposed to be quite slow, making it difficult.

## EDIT:

I asked a related question regarding filter component values on the EE stack exchange, and somebody there pointed out that I should only be seeing "bounce" on one pin at a time, and that I should be able to reject spurious changes purely through software. I'm trying to do that now.

My new code looks like this:

```
bool rotaryValueChanged = false;

bool pinAHasChanged = false;
bool pinBHasChanged = false;

enum ChangeTypes {
  fallingA,
  changingA,
  changingAOrB
  };
ChangeTypes changesToDetect = fallingA;

void encode() {
  pinAHasChanged = true;
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  //Fast equivalent to pinAState = digitalRead(rotaryPinA) == LOW
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;
  //Ignore state changes to pinA unless pinB has changed since the last change.
  //Also only pay attention if this is a falling edge
  //or we're tracking both rising and falling edge changes
  if (pinBHasChanged && (pinAState == false || changesToDetect != fallingA)) {
    rotaryValue +=  (pinAState == pinBState) ? -1 : 1;
    rotaryValueChanged = true;
    pinBHasChanged = false;
  }
}

void encodePinB() {
  pinBHasChanged = true;

  //Unless we're counting 48 ticks/rotation, don't count PinB changes.
  if (changesToDetect != changingAOrB) {
    return;
  }
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;

  //Ignore state changes to pinB unless pinA has changed since the last change
  if (pinAHasChanged) {
    rotaryValue +=  (pinAState != pinBState) ? -1 : 1;
    rotaryValueChanged = true;
  }
}

void setup() {
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);//FALLING
  attachInterrupt(digitalPinToInterrupt(rotaryPinB), encodePinB, CHANGE);
  //More setup code here...
}

```

This code is written to handle 3 possible options:

* Only falling edge state changes on pin A (12 steps/rotation)
* Rising or falling changes on pin A (24 steps/rotation)
* Rising or falling state changes on either pin (48 steps/rotation.)

The key part of this is to have interrupts on both pins. When one pin changes, its interrupt handler sets a "this pin changed" bool to true. In the ISR (Interrupt Service Routine) for the other pin, it only pays attention to a state change if the other pin has changed. That way, when Pin A changes states, if it bounces, the other pin should not bounce at the same time and so unless pin B has changed, I can simply ignore additional changes to Pin A and handle my debouncing in software, and without having to do timing delays which are too slow for an ISR.

However, the code above doesn't quite work. Sometimes I get bogus reverse rotation readings. If I'm rotating the encoder clockwise, the values I get increase one by one as expected, but occasionally decrement by 1 and then go back to incrementing.

What am I doing wrong?

Since the bouncing should only ever occur on one pin at a time, the above code **should** give correct readings from a bare rotary encoder without any hardware debouncing needed, but it doesn't.

My test case is only counting falling edge transitions for Pin A of my encoder, so picking up spurious counterclockwise rotation readings suggests that sometimes Pin B is changing state at the same time as pin B. That shouldn't happen, so I'm confused.
> 2 votes

# Answer
First of all, I would question the usefulness of debouncing a rotary encoder. I would expect to have contact bounce only when the contact is transitioning from `HIGH` to `LOW` or vice-versa. At this transition point, both the `HIGH` and `LOW` readings are in a sense correct. A non-debounced reading should then display a rotary angle that briefly changes back and forth between two *consecutive* positions, with no cumulative error.

I would suggest you forget about debouncing and just look at the state changes. If you think you do need debouncing, handle it downstream, by periodically querying the “raw” angle and updating the “debounced” angle:

* if the raw angle is more than one unit apart from the debounced angle, bring this difference back to one unit.
* if the raw angle has not changed since a fixed count of milliseconds, then make the debounced angle equal to the raw angle.

Second point: you are not looking at the falling edged of input A, you are looking at the rising edges. This is because `pinAState` uses negative logic: it is `true` when the pin is `LOW`. It shouldn't make a big difference though in terms of the logic of the code.

Third point: there is some flaw in your counting logic. I will not try to analyze it in detail, as the whole debouncing concept you use does not make sense to me, but only provide an example of how it can fail. Let's assume the encoder is in the position where both inputs are `LOW`, and you wiggle it a little bit so that each input, in turn, gives a positive pulse, like this:

```
                _       _       _       _       _       _
input A      __/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____
                    _       _       _       _       _       _
input B      ______/ \_____/ \_____/ \_____/ \_____/ \_____/ \_

rotaryValue      0     |   1   |   2   |   3   |   4   |   5

```

Here, `rotaryValue` is incremented on each rising edge of input A, save for the very first one. In this case, the expected behavior is for this variable to stay, say, within \[−1, +1\].
> 1 votes

---
Tags: rotary-encoder, debounce
---


title: Arduino freezes while running code

text:
# Question
Title: Arduino freezes while running code
I am frustrated with my arduino project can you help me? I am using Arduino Uno, electric lock (high/low), 4 distance sonic modules. Basically I have 4 drawers, I am measuring the distance - how much are they opened and if they are opened in given limits, I set the electric lock open (high).

It is working, but after some while, it stops and it stops running. I have tried to comment all serial communication - didn't help. I have tried to use proper variable data types - same. I have tried to buy much powerful power source - 12V 3,5A and I bought Electrolyte condenzator 4,7mF to balance the power peaks while the lock closes - didn't help.

The lock is turned on using relay, connecting it directly to power source 12V. Relay is powered from 5V arduino supply and controlled by arduino Digital pin. 4 Sonic distance modules are powered from arduino power supply.

Its even more funny that it starts running after ~10 minutes from nothing. Im confused.

Code:

```
    // defines pins numbers
const int trigPin1 = 2;
const int echoPin1 = 3;
const int trigPin2 = 6;
const int echoPin2 = 5;
const int trigPin3 = 9;
const int echoPin3 = 8;
const int trigPin4 = 12;
const int echoPin4 = 11;
const int relayPin = 7;
//distance limits
const int minSuplik4=27;//suplik4
const int maxSuplik4=29;
const int minSuplik3=22;//suplik3
const int maxSuplik3=24;
const int minSuplik2=32;//suplik2
const int maxSuplik2=34;
const int minSuplik1=9;//suplik1
const int maxSuplik1=11;
/*
double PreDistance1[4]={0,0,0,0};//supliky
double PreDistance2[4]={0,0,0,0};//supliky
double PreDistance3[4]={0,0,0,0};//supliky
*/
long distance[4]={0,0,0,0};//array with distances
int i;
int x;

int trigPinX[4]={trigPin1,trigPin2,trigPin3,trigPin4};//supliky
int echoPinX[4]={echoPin1,echoPin2,echoPin3,echoPin4};//supliky
int maxD[4]={maxSuplik1,maxSuplik2,maxSuplik3,maxSuplik4};//supliky
int minD[4]={minSuplik1,minSuplik2,minSuplik3,minSuplik4};//supliky
void setup() {
pinMode(relayPin, OUTPUT);
pinMode(trigPin1, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin1, INPUT); // Sets the echoPin as an Input
pinMode(trigPin2, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin2, INPUT); // Sets the echoPin as an Input
pinMode(trigPin3, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin3, INPUT); // Sets the echoPin as an Input
pinMode(trigPin4, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin4, INPUT); // Sets the echoPin as an Input
digitalWrite(relayPin, LOW);
Serial.begin(9600); // Starts the serial communication
}
void loop() {

for (int i=0; i<4; i++)
{
  delay(5);
  distance[i]=DistanceFunction(trigPinX[i],echoPinX[i]);
  delay(20);
  /*********** DEBUG ************
  Serial.print("Distance");// Prints the distance on the Serial Monitor
  Serial.print(i+1);
  Serial.print(":");
  Serial.print(distance[i]);
  Serial.print("<");
  Serial.print(minD[i]);
  Serial.print(":");
  Serial.print(maxD[i]);
  Serial.print(">");
  Serial.print(";");
  *********************************/
}

if(distance[0]>=minD[0] && distance[0]<=maxD[0] && distance[1]>=minD[1] && distance[1]<=maxD[1] && distance[2]>=minD[2] && distance[2]<=maxD[2] && distance[3]>=minD[3] && distance[3]<=maxD[3])
      {
        OpenFcn();
      }
else
      {
        CloseFcn();
      }
delay(100);
}

int DistanceFunction(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);// Clears the trigPin
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);// Sets the trigPin on HIGH state for 10 micro seconds
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);// Reads the echoPin, returns the sound wave travel time in microseconds
  long distanceFcn= duration*0.034/2;// Calculating the distance
  return distanceFcn;
}

int OpenFcn()
{
  digitalWrite(relayPin, HIGH);
  //Serial.println("OPENED");
  for (int x=5; x>0; x--)
    {
      //Serial.println("Otevreno:");
      //Serial.println(x);
      delay(1000);
    }
}

int CloseFcn()
{
  digitalWrite(relayPin, LOW);
  //Serial.println("CLOSED");
}

```

# Answer
> 1 votes
It looks like that there was a problem in the relay module or power supply cord. I have changed these two HW elements and looks like it is working. The reason why it did malfuctioning the arduino was, that when i moved the drawer, it slightly moved the power cord which had bad connection, so it made voltage drop on arduino supply and started to do crazy things. Thanks all for your time

---
Tags: arduino-uno
---


title: Water tank false trigger

text:
# Question
Title: Water tank false trigger
I am trying to make a simple water overflow protection system for my home. I have created it using `BC547` and NodeMCU (ESP8266). I have a simple circuit like this:

The problem here is I have 2 wires going into the tank. Which suppose to complete the circuit as soon as water touch both the wires. But the problem here is **its by default complete the circuit without even touching, this is happening only in my rooftop water tank**. I tried this circuit locally on my desk first and it is working fine. I feel the problem can be humidity inside the tank? Can this be a reason for false trigger?

Here is how I have my code. #define RELAY\_1 D1 #define TANK\_CONNECTION D4

```
void setup() {
  Serial.begin(115200);
  delay(10);

  Serial.println("Started");
  secondsTick.attach(1, ISRwatchdog);

  //Set relay pins to outputs
  pinMode(RELAY_1, OUTPUT);
  pinMode(TANK_CONNECTION, INPUT);

  digitalWrite(RELAY_1, relay_on);
  delay(100);

}

void loop() {
  tankFull();
  delay(100);
}

void tankFull(){

  Serial.println(digitalRead(TANK_CONNECTION));
   if(!digitalRead(TANK_CONNECTION) && relay_on == 0){
      Serial.println(motorOnCount);
      motorOnCount++;
      motorOffCount = 0;
      if(motorOnCount >= 10){
        Serial.println("Motor Turn OFF");
        digitalWrite(RELAY_1, HIGH);
         if (client.connected()) {
            client.publish(motor_status, "off", true);
            client.publish(tank_full, "on", true);

          }
        motorOnCount=0;
        relay_on = 1;
      }
      delay(100);
   } else{
      motorOffCount++;
       if (client.connected()) {
          client.publish(tank_full, "off", true);
       }
      //Serial.println(motorOffCount);
      if(motorOffCount>=100){
        motorOffCount=0;
        motorOnCount = 0;

      }
   }
}

```

Obviously this is not the full code. I am just trying to share the pattern of its working for basic understanding of the setup I have.

Any one have idea about why its always shows circuit complete even without touching the wires. I have tried with 5v as well and 3.3v as well which are present on NodeMcu Board. But none of them worked properly.

# Answer
> 2 votes
Certainly the issue is from EMI but not from the collector side as from the transistor base even the wires are shorter on that side as I understand from the comments.

It's a common mistake to let the transistor base floating, see here a different application but with the same cause and result, the transistor is turning on apparently with no reason. With the base floating the EMI current has no other path than through the transistor base where is amplified by beta ( 110 to 800 for BC547).

Put a 10Kohm resistor between the transistor base and emitter to let a path for EMI currents to the ground. Try different values, smaller if you still have false triggering, higher if the sensor is not turning on the transistor.

Of course, use INPUT\_PULLUP but the internal resistor is to high 30 to 100 kohm, better use an external resistor arround 10k or lower form the transistor collector to 3V3 to ensure a good noise margin on the collector side to.

simulate this circuit – Schematic created using CircuitLab

---
Tags: esp8266, nodemcu, electronics, transistor
---


# Question
Title: Using Arduino Mega with multiple HC05 Modules as masters, communicating to multiple HC05 Modules as slaves, each connected to separate Arduino
So I have not actually experimented with the HC05 Bluetooth Module yet, but I have read up about it and watched some videos. From what I understand, you cannot use one module (master) to communicate with more than one other module (slaves), or at least its pretty difficult. But, you can use a module hooked up to an arduino to communicate to to another module hooked up to another arduino (I believe pretty simply).

However, I thought it might be possible to use an Arduino Mega (because it has multiple TX/RX pins) with 3 HC05 Bluetooth modules, to each communicate to 3 separate HC05s which would each be hooked up to an arduino nano. I know this might have to do something with running multiple Software Serials (I have no idea what that is to be honest)?

The project involves using the master arduino to "listen" for a button pressed on the slave arduino (across the room without connecting wires), then listening for another button press from one of the other slaves in some sort of sequence and within a certain time frame.

Does anyone have any idea about how this might be done, even if it doesn't use the HC05 Bluetooth Module?

Thanks!

# Answer
Yes, this is possible. According to arduino.cc, the Arduino Mega has 4 hardware serial ports, so you can connect 3 HC-05 modules and still have 1 serial interface left. The Mega is a good choice, when you need this many serial interfaces, so at this point you don't even need `SoftwareSerial`. You will have to configure the HC-05 modules correctly from the master and command them to connect to the correct slave modules.

About `SoftwareSerial`: The serial interfaces mentioned above are "hardware" interfaces, meaning, that the itself microcontroller contains hardware, that does the main part of the receiving/transmitting by itself, without any need for code. The `Serial` library then only adds a bigger buffer for the data, wrapper functions to write to it and reacts to the interrupts, that come from the hardware interface. But since most microcontrollers only have a very limited number of hardware serial interfaces (often only 1 or even none), the `SoftwareSerial` library comes in handy. It emulates the UART protocol (which is a more professional term for the Serial interface from the Arduino world) with software (and some help from interrupts). This means, that you can use it with any pair of pins and you can even define multiple interfaces with it. But it also has drawbacks. For example: Only 1 `SoftwareSerial` interface can listen at once, you cannot use high baudrates, it uses interrupts, that you might need for an application.

---

That said, I don't think, that Bluetooth is the best way to go, if you only want to test a small number of buttons per slave. It is simply too much hassle to configure the modules and establish the connections correctly. Instead you can use 433MHz radio modules. They don't involve such a complex protocol like Bluetooth does, so it's a very simple solution. In the simplest case, you only need transmitters for the slaves and a receiver for the master. Every slave can send a short identifier, if the button was pressed. The master can then receive this data. Of course, if more than one slave sends simultaneously, the data will be garbage. But as long, as this is not a problem, you can keep it that simple.

There are many tutorials on the web, that explain how to use these modules. You can even find libraries, that are ready to use.
> 0 votes

---
Tags: arduino-mega, arduino-nano, softwareserial, hc-05
---


title: String does not name a type

text:
# Question
Title: String does not name a type
I'm using Arduino IDE for ESP32 WROOM board. I am testing the OTA feature with the ESP32httpUpdate library. I am using the example sketch of the library with the name httpUpdate.ino However, as soon as I change the update url with a string pointer that I declare globally, it is throwing a compile error that String does not name a type. Any ideas?

```
/**
 * httpUpdate.ino
 *
 *  Created on: 27.11.2015
 *
 */
String* FIRMWARE_UPDATE_VERSION = "1000";

String* updateURL = "XYZ.php";

#include <Arduino.h>

#include <WiFi.h>

#include <HTTPClient.h>
#include <ESP32httpUpdate.h>

#define USE_SERIAL Serial

void setup() {

    USE_SERIAL.begin(115200);
    // USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFi.begin("SSID", "PASSWORD");

}

void loop() {
    // wait for WiFi connection
    Serial.println("Yolo");
    if((WiFi.status() == WL_CONNECTED)) {

        t_httpUpdate_return ret = ESPhttpUpdate.update(updateURL, FIRMWARE_UPDATE_VERSION);

        switch(ret) {
            case HTTP_UPDATE_FAILED:
                USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
                break;

            case HTTP_UPDATE_NO_UPDATES:
                USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
                break;

            case HTTP_UPDATE_OK:
                USE_SERIAL.println("HTTP_UPDATE_OK");
                break;
        }
    }
}

```

# Answer
> 4 votes
`String` is included by Arduino.h. Before `#include <Arduino.h>` `String` is not defined. Move `#include <Arduino.h>` to the top of the file or remove it. If you remove it, the Arduino builder adds it.

---
Tags: esp32
---


title: how to use AckPayload correctly

text:
# Question
Title: how to use AckPayload correctly
i'm trying to send String from an Arduino(Uno) using the Serial. to an another Arduino(Uno). using nRF24l01+. and I'm using the library RF24.h the String is sended correctly but I have some problems with the acknowledgement.

This is my Rx code.

```
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
char buf[32]= "";
char false_buf[32]= "MKJK212U1H7";
void setup()
{
  Serial.begin(115200);
  radio.begin();
  radio.setChannel(0x35);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(1,15);
  radio.writeAckPayload( 1, false_buf, sizeof(false_buf) );
}
void loop()
{
int OkMsg;
  while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&buf,sizeof(buf) );
    Serial.println(buf);
    radio.writeAckPayload( 1, buf, sizeof(false_buf) );
      while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&OkMsg,sizeof(OkMsg) );
    Serial.println(OkMsg);
    if(OkMsg == 1){Serial.println("OkMsg's true!");}
    else {Serial.println("OkMsg's false!");}
    }}
  }

```

and this is my Tx code

```
#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>
RF24 radio(9, 10); // CE, CSN

const uint64_t pipe[1]= {0xF0F0F0F0E1LL};

char CharToSend[32]= "" ;
char Ack[32]= "" ;
String inputString = "";
String Allconfiguration = "";
boolean stringComplete = false;
char  inChar;
boolean isConnected = false;
int OkMsg = 0;

void setup()
{
  SPI.begin();
  Serial.begin(115200);
  RadioSetupTransmiter();
}

void loop()
{
  if(stringComplete)
  {
         if(Allconfiguration.startsWith("\n")){Allconfiguration.remove(0,1);}
     Allconfiguration.remove(Allconfiguration.length());
    inputString = "";
    Serial.print("Allconfiguration : ");
     Serial.println(Allconfiguration);
    int counter = 0;
    for(int i=0; i<Allconfiguration.length(); i++)
    {
      if((Allconfiguration[i] == '\n')&&(i!=Allconfiguration.length()))
      {
        int pre_counter = counter;
        counter = i+1;
        inputString = Allconfiguration.substring(pre_counter, counter);
        if(inputString[0]!='$'){inputString.toCharArray(CharToSend,32);}

        if(radio.write(&CharToSend, sizeof(CharToSend)))
        {CheckData();
       Serial.print("inputString : ");
         Serial.print(CharToSend);}
      }
       if(i == Allconfiguration.length()){
        const char EndChar[2] = "$";

       }
        inputString = "";
    }
    Allconfiguration = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
  char inChar = (char)Serial.read();
    Allconfiguration +=inChar;
     if (inChar == '$'){stringComplete = true;
    }
    }
}

void RadioSetupTransmiter(){  radio.begin();

  radio.setChannel(0x35);
  delay(100);
  radio.setAutoAck( true ) ;
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  // radio.printDetails();

  radio.stopListening();
  radio.openWritingPipe(pipe[0]);

  radio.setRetries(1, 15);
 }

void CheckData(){
  int OkMsg = 0;
    while (!radio.isAckPayloadAvailable()){};
      if(radio.isAckPayloadAvailable())
      {
       radio.read(&Ack,sizeof(Ack));
       //Serial.println(Ack);
       if(strcmp(CharToSend,Ack) == 0){
        OkMsg = 1  ;
        Serial.println("AckRecived");
        radio.write(&OkMsg,sizeof(OkMsg));}
    }
}

```

# Answer
I have not used the RF24 libary, but below are the register settings that should be written during `void setup()` to use the ACK\_PAYLOAD functionality (N.B. nRF24L01+ only, does not exist on nRF24L01. Check you are using the right version of the radio!)

**TX:**

* 0x00 CONFIG = PTX mode
* 0x0B RX\_PW\_P0 = Number of data bytes in pipe 0
* 0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL\_P0 bit)
* 0x1D FEATURE = 0x06 (set bits EN\_DPL and EN\_ACK\_PAY).

**RX**

* 0x00 CONFIG = PRX mode
* 0x0B RX\_PW\_P0 = Number of data bytes in pipe 0
* 0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL\_P0 bit)
* 0x1D FEATURE = 0x06 (set bits EN\_DPL and EN\_ACK\_PAY).
* Finally, load an initial payload using the W\_ACK\_PAYLOAD instruction 0xA8, i.e. `SPI.transfer(0xA8); SPI.transfer(payload);`.
> 3 votes

---
Tags: nrf24l01+
---


title: Burning Arduino Bootloader

text:
# Question
Title: Burning Arduino Bootloader
I'm trying to use an atmega chip from an arduino on a breadboard, with minimal hardware (using the internal 8mhz clock). I am using the article in the link provided. When I reach the final step (burning the bootloader), I get an error telling me the device signature is wrong-

Arduino: 1.8.5 (Windows 10), Board: "ATmega328 on a breadboard (8 MHz internal clock)"

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

Error while burning bootloader.

I am assuming the error is because the chip is from a uno clone, and uses an atmega328p-pu chip. How am I able to override this check using -F, as described in the error message? Or is there maybe some other way i can fix this? Thanks in advance.

https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

# Answer
One of the parameters that you have to give avrdude is the microcontroller you are using, and then it checks the signature of the micro to ensuere that everthing is ok. this parameter is passed through -p flag

```
avrdude -p <microcontroller name>

```

For ATmega328 this parameter should be m328 and in your case, with ATmega328p this parameter should be m328p. All options avalible can be checked in man page.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Smoothing does not work as expected
I using the standard example of smoothing:

```
/*
  Smoothing

  Reads repeatedly from an analog input, calculating a running average and
  printing it to the computer. Keeps ten readings in an array and continually
  averages them.

  The circuit:
  - analog sensor (potentiometer will do) attached to analog input 0

  created 22 Apr 2007
  by David A. Mellis  <dam@mellis.org>
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Smoothing
*/

// Define the number of samples to keep track of. The higher the number, the
// more the readings will be smoothed, but the slower the output will respond to
// the input. Using a constant rather than a normal variable lets us use this
// value to determine the size of the readings array.
const int numReadings = 10;

int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

int inputPin = A0;

void setup() {
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = analogRead(inputPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println(average);
  delay(1);        // delay in between reads for stability
}

```

to calculate power consumption for a load which changes it's value frequently (sometimes it stops and the consumption goes down to couple of watts).

My only modification of the above code is to pass a calculated power (V\*I) value to it instead of the analogRead(inputPin);. The input value for the power calculation works fine because without this code I get the exact good values for power. I have also increased the numreadings from 10-\>100 and probably will needed to be increased a lot more since I need the average for 1 minute.

There are 2 major issues with this code:

1, When a constant load is attached, which let's say draws 500W the value generated by the code is floating around 312W and never reaches 500.

2, When the load is disconnected it and the current power consumption is 1-2watts standby this code jumps to -312W. I could cast it to be an unsigned integer on the first place but that's not really a good solution.

Anyone knows how to fix this?

Thanks

# Answer
Yes, change the variable type to something that can hold larger numbers, because now adding up 100 measurements will overflow your variable.
> 1 votes

---
Tags: power
---


# Question
Title: How can I scan for a HIGH signal on digitalRead during the main loop, while running other things?
I'm working on a program which listens for certain bytes on serial through an if/then/elseif ladder. I want to also check if a pin (say, `A15`) has been given a HIGH state, by another Arduino with shared ground. The slave Arduino will turn a digital pin to HIGH and I want the MEGA2560 to check every time it loops if a HIGH is present from the other board. A "While button not pressed do nothing statement won't work, because that won't let the loop go. I tried doing an if statement, using something to the effect of this:

```
if (digitalRead(A15)==HIGH) {
  //things to do
}

```

But it seems no matter what I put, be it `HIGH`, `LOW`, `!= HIGH`, `!= LOW`, etc. or either input pinmodes, pullup or not, it always thinks the board is transmitting HIGH. In fact, it only doesn't think it's HIGH when it actually *is* HIGH. I'm pretty stumped on this. If you ask me, digitalRead is really odd with what's HIGH and what's LOW.

# Answer
Simplify, and show your setup code.

First, do you have a pinMode call in your setup function:

```
void setup() {
  pinMode(A15, INPUT_PULLUP);
  Serial.begin(115200);
}

```

Then use test code like this:

```
void loop() {
   if (digitalRead(A15) == HIGH) {
      Serial.println("Pin A15 is HIGH");
   } else {
      Serial.println("Pin A15 is LOW");
   }
}

```

Connect your A15 pin directly to ground with a jumper and run the sketch above. Open the serial monitor and see what is output. It should be LOW. Then disconnect the jumper and check again. It should now be HIGH. Finally, connect the jumper between A15 and +5V and check the output again. It should still show HIGH.

That lets you troubleshoot just the software piece. Once you get that working, connect pin A15 to the remote Arduino's output pin and try again.
> 1 votes

---
Tags: arduino-mega, arduino-nano, digital, digital-analog-conversion, digital-in
---