message:
Adafruit esp32 Feather Failing to compile

So yesterday, I was able to upload/compile given example code to the Esp32 Huzzah board. Today I couldn't even compile. Even carefully using the [tutorial adafruit provides][1].

I was getting errors as given below. How do I fix this?

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o):(.literal.main_task+0x14): undefined reference to `app_main'

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o): In function `main_task':

 /Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/esp32/cpu_start.c:503: undefined reference to `app_main'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial9availableEv+0x0): undefined reference to `uartAvailable'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4peekEv+0x0): undefined reference to `uartPeek'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4readEv+0x0): undefined reference to `uartRead'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5flushEv+0x0): undefined reference to `uartFlush'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEh+0x0): undefined reference to `uartWrite'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEPKhj+0x0): undefined reference to `uartWriteBuf'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::available()':

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartAvailable'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::peek()':

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartPeek'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::read()':

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartRead'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::flush()':

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartFlush'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char)':

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWrite'

 C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char const*, unsigned int)':

 C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWriteBuf'

 collect2.exe: error: ld returned 1 exit status

 exit status 1
 Error compiling for board Adafruit ESP32 Feather.

  [1]: https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/using-with-arduino-ide

body:
So it turns out the problem is that you're using the esp32 1.0.1 library provided by espressif. I'm assuming you're using the Arduino IDE board manager URL: https://dl.espressif.com/dl/package_esp32_index.json

To fix this, **don't** use 1.0.1. Use 1.0.0! Remove 1.0.1 and install 1.0.0. That should get it to compile properly without the uart, app_main errors.


sender: user

message:
how to write an int to RFID tag and when read then store that in an array

The writing code is from the MFRC522 Example below:

I have added an array to store the value but it does not store it as the same value written to it in the writing. instead it stores it as byte values.
I am fairly new so would appreciate any help.
<!-- language-all: lang-cpp -->
``````````````````````````````````````````````````````
/*
 * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
 * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * Hardware required:
 * Arduino
 * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
 * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

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

  byte buffer[34];
  byte block;
  MFRC522::StatusCode status;
  byte len;

  Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Enter the weight, ending with#"));
  len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
  for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

  block = 1;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

}
``````````````````````````````````````````````````````````
and the reading code is :
`````````````````````````````````````````
/*
 * Initial Author: ryand1011 (https://github.com/ryand1011)
 *
 * Reads data written by a program such as "rfid_write_personal_data.ino"
 *
 * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
 *
 * Uses MIFARE RFID card using RFID-RC522 reader
 * Uses MFRC522 - Library
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

int weightArray[2];
int counter = 0;

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
  Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read

}

//*****************************************************************************************//
void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;

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

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

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

  Serial.println("Detected");

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT FIRST NAME
/*  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");
*/
  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);
    }

  for(int i = 0; i < sizeof(weightArray) / sizeof(weightArray[1]); i++) {
    Serial.print(weightArray[i]);
  }

  counter++;

  Serial.println(F("\n**End Reading**\n"));

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//
````````````````````````````````````

sender: assistant

body:
First you are not writing `int` value during write as, buffer is defined as `byte` type. Your are just type casting it `char*` during serial read for storing data. And Your are writing just first 16 value in your CARD, so you might not get the expected results.

`byte` data type provides only `8 bit` or `1 byte` of memory location.
`int` data type provides `2 bytes` or `4 bytes` of memory location.


message:
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:

[![enter image description here][1]][1]

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.
<!-- language-all: lang-cpp -->
    #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.

  [1]: https://i.stack.imgur.com/qsbCm.png

body:
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][1] 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.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/z4RnM.png)

<!-- End schematic -->

  [1]: https://electronics.stackexchange.com/questions/338505/why-relay-module-occasionally-switches-by-itself-on/370260#370260


message:
changing state of an LED using a pushbutton leads to unstable result

I am trying to run this code:

~~~c++
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:

<!- begin snippet: js hide: true -->

~~~xml
<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][1].

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

**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][3].

  [1]: https://we.tl/t-JRlKclqjBf
  [2]: https://www.arduino.cc/en/tutorial/button
  [3]: https://photos.app.goo.gl/p8PTzLZjDotrimyAA

body:
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.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/sPSP8.png)

<!-- End schematic -->

  [1]: https://i.stack.imgur.com/290M1.png


body:
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).


body:
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](https://www.arduinolibraries.info/libraries/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).


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

~~~c++
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][1], but I'm not sure if it will improve the stability.

I used [this video][2] and information on [this page][3].

  [1]: https://gist.github.com/Foadsf/b1e9820632d953705fcb49fc75c1f4fb
  [2]: https://www.youtube.com/watch?v=hXDgHuUKGqU
  [3]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/


message:
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");}
    }

body:
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.


message:
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);
       }
      }

body:
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


body:
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.


message:
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?![1]][1]
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

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/NnGI5.jpg
  [2]: https://i.stack.imgur.com/LowQz.jpg

body:
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.


message:
What is the purpose of Serial.println() without an argument?

I am attempting to control a stepper motor with [Sparkfun's Big Easy Driver][1], 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();
    }

  [1]: https://learn.sparkfun.com/tutorials/big-easy-driver-hookup-guide?_ga=2.180625124.2131528762.1552592364-1334954616.1545061294

body: It simply prints a newline to the serial monitor. Just for spacing.


body:
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,

<!-- language-all: lang-c++ -->

    Serial.println();

is equivalent to

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


message:
Write faster on AT24C32

I'm using [AT24C32](http://ww1.microchip.com/downloads/en/devicedoc/doc0336.pdf) EEPROM chip from ATmel. I found code that will write and read bytes from chip.
Code writes and reads bytes correctly and without any problem.

But I have to write few 8-byte values often(every 10-15 seconds). I did "cut" those variables to 48 bit(so 6-byte variable) and with that I speeded up saving but it's still slow.

Is there any chance to speed up saving proccess? Code is below

    void EEPROMClass::write48(int16_t address, uint64_t value)
    {
        uint8_t byteValue = (value & 0xFF);
        write8(address, byteValue);

        byteValue = ((value >> 8) & 0xFF);
        write8(address + 1, byteValue);

        byteValue = ((value >> 16) & 0xFF);
        write8(address + 2, byteValue);

        byteValue = ((value >> 24) & 0xFF);
        write8(address + 3, byteValue);

        byteValue = ((value >> 32) & 0xFF);
        write8(address + 4, byteValue);

        byteValue = ((value >> 40) & 0xFF);
        write8(address + 5, byteValue);
    }

    void EEPROMClass::write8(int16_t const address, uint8_t const value)
    {
     Wire.beginTransmission(AT24C32);

     Wire.write(highAddressByte(address));
     Wire.write(lowAddressByte(address));

     Wire.write(value);
     delay(2);
     Wire.endTransmission();
    }

`delay` of 2ms is required otherwise EEPROM will write different value. Code has 4 "6-byte" variables(total of 24 bytes). Every byte is minimum 2ms, so total time to save only "6-byte" variables is 48ms(round to 50ms). That is too slow for me. How to speed up `write` function?

body:
after writing a value to EEPROM, and terminating the I2C connection with a STOP, the EEPROM enters a self writing mode to write what you have sent to it, to it's internal memory. (you don't actually write the values to the memory section; you write them to a buffer, and then the internal controller writes them to its memory section).

this "self writing mode" takes about 5ms, and you cant do nothing about it. but you can use "page writing" instead of byte writing. that 32K model, has a 32 bytes page buffer. you have to send all the bytes (as long as they are under 32 bytes) at once in one I2C transaction. this time, the chip fills its page buffer and then after a STOP, writes it all at once on its memory. in your code, you just write one byte in your buffer each time in a single transaction. like sending a bus with just one passenger at a time.

remember in this mode, you only set the address of the first byte. the next bytes automatically settle in the next addresses.


body:
Mostly the best speed you get, is if you use the 'page' size, which is 32 bytes. It will take longer than 4 bytes, but less then 4 times 8 bytes.

You could do a check to see if using one page write (of 32 bytes) is faster than 6 times a one byte write.

However, it depends if you can change your design so it writes 32 bytes at a time.
E.g. by writing 60 seconds 4 times 8 bytes (32 bytes) in one page write, instead of every 15 seconds 8 bytes. This will be much faster.


body: I never let processor wait a process to finish. I call a procedure do whatever could be done put a mark where I got and return to do other stuff. Next scan I pick up from where I left and continue if the conditions allow, if not i leave it for the next scan. I would never put a waiting time in a loop. In your case I would open the communication, send as many bytes as I can, put a mark how far I got, close the communication and return. Next scans(when the data are transferred from the buffer to the EEPROM) I would repeat the same process for the rest of the data. At any scan I invest a few hundreds of microseconds.


message:
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?

body:
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][1]. There are many RS485 to USB converters available [like this one][2] for computers that do not have an RS485 port.

  [1]: https://en.wikipedia.org/wiki/RS-485
  [2]: https://www.alliedelec.com/product/ftdi/usb-rs485-we-1800-bt/70069439/


message:
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;
    }

body:
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


message:
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!

body:
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.


message:
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;
            }
        }
    }

body: `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.


message:
Arduino uno holder

Arduino sells a holder for the UNO board, but without much documentation or detailed specifications, see [this link][1].  Can anyone give the diameter of four small holes, two located on the top edge and one each on the left/right edges?   What size of screw will fit?  They are smaller than M3 / 4-40 apparently.

Also, does anyone know what material is the holder made from?

[![enter image description here][2]][2]

  [1]: https://store.arduino.cc/holder-type-uno
  [2]: https://i.stack.imgur.com/FOuTZ.png

body:
Arduino UNO holes are just over 3mm in diameter. Both 4-40 and M3 bolts will work well, giving you a bit of wiggle room. You will have to file down the width of the bolt head to fit against the 6 pin header near D13.

As far as the holder material, I don't know. I 3D print my own.


body:
** Self answer:

I obtained several of these holders from Arduino starter kits.  They are made from a clear, colorless plastic that seems to have been injection molded.  However, it is hard to tell exactly which plastic, since these does not have any recycle logo!  The image posted in the original question is perhaps a newer version.

The four smaller holes can accept M2.5 screws, I checked.


message:
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

body:
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.


message:
Arduino Smoothing does not work as expected

I using the standard example of smoothing:
<!-- language-all: lang-cpp -->

    /*
      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

body: Yes, change the variable type to something that can hold larger numbers, because now adding up 100 measurements will overflow your variable.


message:
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:
```C++
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.

body:
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.


message:
DHT11 + ESP plus Arduino

Someone could help me?
I want to use dht11 with arduino and esp. Both will read data from dht11
the problem is that simultaneously cannot be done. So the solution will be to set one as a master and the other one as a slave.
the control will be done like so...
another wire from arduino pin->set as output ->esp pin->set as input.
if wire == 1 then dht11 will be read by arduino
if wire == 0 then esp will read dht.
with some delay ofcourse. but the problem is that i dk how to stop the communication between one board and the sensor when the other board will read it. so does it not exist any conflict

body:
**Disclaimer:**

I've never used an ESP chip based board I know almost nothing about them. I am going to assume that it works, in software terms, like an Arduino, and base my answer on Arduino code. If the esp chip works differently, you'll need to adapt my suggestion.

---

Try something like this:

Connect a GPIO line between the microcontrollers. Also connect that line - through a 10K resistor - to +5V.

Have both microcontrollers set up it's GPIO as an input.

(We'll call the GPIO pin on both microcontrollers the "DHT_available" line. It will be HIGH when the DHT sensor is not being used by the other controller.)

When one of the microcontrollers wants to read the DHT11, have it check the GPIO line. If it's HIGH switch the GPIO line to an output and pull it low, then take a reading. When the reading is complete, switch the GPIO line back to an input.

If the GPIO line is LOW, wait and check again.

---

Alternately you could attach each of the microcontroller's GPIO lines to interrupt handlers on a rising edge. Then have the interrupt handler set the GPIO line to an output, pull it to LOW, and set a flag that means "begin reading".

Have your loop function check the "begin reading" flag, and if true, trigger a read from the DHT, and once it's complete, set the GPIO back to an input.

With the first option, each microcontroller would need to poll the "DHT_available" line continuously until it goes HIGH before beginning reading.

With the second option, as soon as one of your microcontrollers is done taking a reading, it would stop pulling the communications line LOW, the other one's rising edge interrupt would fire, and the other one would immediately begin reading.


body:
Also.. i would see a problem there. Lets say so..
Sensor data.
Gnd.
Vcc
uC 2560
uC Esp
If sensor data is linked to both uC
And  use a line dht_available btween 2560 and esp to handle the uC reading.. then..
If dht_available == HIGH then 2560 read after switch dht line to Low
If dht_available == LOW then esp read after reading dhtline》 HIGH
But the sensor wil continue to send data to both.. regqrding the dhtline is high or low.
I dk how to say to sensor.. if dhtline is LOW stop sending data to 2560 because is esp time to read.