body: I want to make a VB.NET program to communicate over serial with the board, but I need to be sure it knows which port. Instead of programming in more advanced methods of verification, for this project I would simply prefer to keep the board on the same (internal) USB port. Will it always appear on the same serial port (COMx) and will VB always be able to find it there?

title: Ensure board is always on the same port?

Answers: 2

body: My experience is that the Serial-to-USB converters (of which Arduino is one) have are assigned a COM port according to the USB port they are plugged into. So if you always to connect it to the same physical USB port it will have the same number. However this number will not be the same with a different Arduino or on a different computer.

body:
*Normally*, the COM port number wont change, but you cannot simply rely on this.

Depends on various effects, especially if you have multiple USB-Serial devices, update the driver, etc. Also, there's the possibility to clean the COM port numbers in the operating system to get rid of unused legacy entries, which will restart counting them from fresh.

Most applications search for all existing ones, eventually display their names, and leave it to the user to choose the desired port.

And, btw. it's not related to VB.net


body:
i am a student doing a project related to datalogging. My project is a rehabilitation device that uses 2 rotary encoders to record data for rotation and linear movement of a human arm. The data extract is store inside the PC, but my supervisor wants me to upgrade it, he gave me an Arduino Ethernet Shield to attach it on Arduino Mega and he wants me to upload the data obtained from the device to Microsoft Azure database. I'm still new in both Arduino Ethernet Shield and Azure...can anyone help me?

What can i do with the Ethernet Shield? I mean we normally use the USB cable to work with Arduino, so this mean I have to connect both?

Thanks in advance!

title: Arduino with Ethernet Shield with PC to upload data to Microsoft Azure

Answers: 0


body:
I am using arduino uno to control dc motor speed with L298N. But the problem is that the motor is only going at max speed. PWM pin doesn't work for some reason.
I heard many people had some problem but haven't found the solution yet.

code:-

    #include <L298N.h>

    #define ENA 9
    #define IN1 8
    #define IN2 7

    L298N motor(ENA, IN1, IN2);

    void setup() {
    // Setup pin mode

    //used for display information
      Serial.begin(9600);

    }

    void loop() {
    //Drive Motor Forward
      motor.setSpeed(10);
      motor.forward();
      delay(500);
      motor.setSpeed(100);
      motor.forward();
      delay(500);
      motor.setSpeed(255);
      motor.forward();
      delay(500);

    }

I only see the motor move at full speed every time. I connected 5V of Arduino to +12V pin of motor driver and Arduino is powered with my laptop USB.

I am using 4.5V toy dc motor for test - [DC motor][1]

What could be wrong here?

  [1]: https://uae.souq.com/ae-en/dc-geared-motors-for-robots-straight-shaft-12139874/i/?a_source=google&a_medium=cpc&a_content=search_shopping&u_type=shopping&a_campaign=Shopping-Smart-UAE-EN-Global&referrer=re=1&a=amodi&ca=Google-Shopping-Smart-1018320391&an=Google Search&p=Android&pl=45586436090&cr=-&s=&gclid=CjwKCAjwhbHlBRAMEiwAoDA34xlPRdDs2_k7X-qV8erCRBm9ERJz3M0s-0CaZYC5dPhSB717S_m1DhoCvpUQAvD_BwE

title: Not able to control DC motor speed with l298N & pwm pins

Answers: 2

body:
Try to use this code, without the library, and be sure to connect every pin to the correct Arduino output. If everything is okay it should work. Check the tutorial [here][1]

    int IN3 = 5;
    int IN4 = 4;
    int ENB = 3;
    void setup()
    {
     pinMode (ENB, OUTPUT);
     pinMode (IN3, OUTPUT);
     pinMode (IN4, OUTPUT);
    }
    void loop()
    {

      digitalWrite (IN3, HIGH);
      digitalWrite (IN4, LOW);
      analogWrite(ENB,55);
      delay(2000);
      analogWrite(ENB,105);
      delay(2000);
      analogWrite(ENB,255);
      delay(2000);
      analogWrite(ENB,0);
      delay(5000);
    }

  [1]: https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/

body:
Modifying the library code file L298N.cpp. Insert 2 lines in setSpeed():

    void L298N::setSpeed(unsigned short pwmVal)
    { _pwmVal = pwmVal;
      if (_ismoving == true)                   // +++
       analogWrite(_pinEnable, _pwmVal);      // +++
    }

Problem solved!


body:
    class Channel
    {
        private:
            uint8_t _pin;
            uint8_t _state;
            uint32_t _rise;
            uint32_t _fall;
            uint8_t _count;
            uint8_t _channel;

            static uint8_t channelCount;

            void display()
            {
                uint32_t diff = (_fall - _rise) / 1000;
                uint32_t secs = diff % 60;
                uint32_t mins = diff / 60;
              //  Serial.print(",");
                Serial.print(_channel);
                Serial.print(",");
                Serial.print(mins);
                Serial.print(",");
                Serial.print(secs-4);
                Serial.print(",");
                Serial.println(_count);
            }

        public:
            Channel(int pin) : _pin(pin), _count(0)
            {
                _pin = pin;
                _count = 0;
                _channel = channelCount;
                channelCount++;
            }
            void process()
              {
                int s = digitalRead(_pin);
                if (s != _state)
                  {
                    _state = s;
                    if (s == LOW)  // Fell
                      {
                        _fall = millis();
                        _count++;
                        display();
                      }
                    else
                      {
                        _rise = millis();
                      }
                    }
                }
            void begin()
            {
                pinMode(_pin, INPUT);
            }
    };

    uint8_t Channel::channelCount = 0;

    Channel channels[] = { 3,5 };
    #define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

    void setup()
    {
        Serial.begin(115200);
        Serial.println("Channel,Minutes,Seconds,Count");
        for (unsigned int i = 0; i < NUM_CHANNELS; i++)
          {
            channels[i].begin();
          }
    }

    void loop()
    {
        for (unsigned int i = 0; i < NUM_CHANNELS; i++)
          {
            channels[i].process();
          }
    }

This code works normally in some cases, (i.e.) It provides the exact time between the signal when it's ON and when it gets OFF in seconds.

In some cases, it spits out a 10 digit number. The correct value follows the unknown number in the screenshot attached below [![which was taken when the output is recorded][1]][1]

  [1]: https://i.stack.imgur.com/kGFCV.jpg

title: Calculating the time between the signal when its ON and when it gets OFF

Answers: 1

body: I suspect secs is 0 sometimes, because of _rise being 0? In that case unsigned int subtraction causes this: secs(0) - 4 = -4 % 2^32, resulting in your 4294967292


body:
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

    Sketch uses 12452 bytes (38%) of program storage space. Maximum is 32256 bytes.
    Global variables use 970 bytes (47%) of dynamic memory, leaving 1078 bytes for local variables. Maximum is 2048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

title: problem in uploading the code

Answers: 2

body:
It means there is no proper communication between the IDE and your Arduino. The reason can be many things:

- RX/TX UART port used
- USB port broken
- USB cable broken
- Arduino broken
- USB port drivers not properly installed
- Problem inside IDE
- ...

To troubleshoot you could try:

- Disconnect RX/TX jumpers
- Try another USB port
- Remove other USB devices
- Try another USB cable
- Try another Arduino
- Try another PC/laptop
- Reinstall IDE
- Reinstall USB drivers

body: Try to upload your code without any device connected to Uno. Disconnect all IO pins. Upload the code via onboard USB port.


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

title: Adafruit esp32 Feather Failing to compile

Answers: 1

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.


body:
So I am working on a project where the board plays a song on a buzzer using PWM and I want the song to stop when i press an external button

    typedef enum stateType_enum{
    waitPress, debouncePress, waitRelease, debounceRelease
    } stateType;
    volatile stateType state = waitPress;
    volatile bool deviceOn = false;

    int main(void){
       sei();
       while(1) {

       switch(state){
         case waitPress:
           break;
         case debouncePress:
           delayMs(100);
           state = waitRelease;
           break;
         case waitRelease:
           break;
         case debounceRelease:
           delayMs(100);
           state = waitPress;
           break;
       }

       if(deviceOn){
           triggerAlarm(&deviceOn);
       }
       _delay_ms(100);
    }

    ISR(PCINT0_vect){
       if(state == waitPress){
          state = debouncePress;
       }
       else if (state == waitRelease){
          deviceOn = !deviceOn;
          state = debounceRelease;
       }
    }
My real question is, can I send the deviceOn as a pointer to the song?

title: can an ISR change the value passed by pointer while the subroutine is executing?

Answers: 0


body:
I am trying to control a robot, where I have one HC05 module as a master connected to an Arduino Uno with an attached joystick. This Arduino sends data signals that will run blocks of code on the slave Arduino, which will have four servo motors connected to it, but for testing purposes, only two are connected. This Arduino also has an HC05 Bluetooth module connected to it, but it is configured as a slave. I have tried everything to get the Bluetooth functionality to work, but it does not work! If you are interested in the background of this, this is for my Rapid Assembly and Design project for school, which I have a report on soon. We are creating a robot that can operate on land and traverse the sea, so we are making it waterproof as well.
P.S. both modules are HC05 modules.

Master Code:

    #include <SoftwareSerial.h>
    int yPin = A0;
    int xPin = A1;
    int buttonPin = 2;
    int xPosition = 0;
    int yPosition = 0;
    int buttonState = 0;
    const int RX_PIN = 10;
    const int TX_PIN = 9;
    SoftwareSerial BL(RX_PIN, TX_PIN);
    const int BLUETOOTH_BAUD_RATE = 9600;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      BL.begin(39600);
      pinMode(xPin, INPUT);
      pinMode(yPin, INPUT);
      pinMode(buttonPin, INPUT_PULLUP);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      xPosition = analogRead(xPin);
      yPosition = analogRead(yPin);
      buttonState = digitalRead(buttonPin);
      /*if (buttonState == 1) {
        if (xPosition >= 450 & xPosition <= 550) {
          if (yPosition >=450 & yPosition <= 550) {
            Serial.write("a1 ");
            bluetooth.write("a1");
          }
          if (yPosition > 550) {
            Serial.write("a2 ");
            bluetooth.write("a2");
          }
          if (yPosition < 450) {
            Serial.write("a3 ");
            bluetooth.write("a3");
          }
        }
        if (yPosition >= 450 & yPosition <= 550) {
          if (yPosition >= 450 & yPosition <= 550) {
            Serial.write("b1 ");
            bluetooth.write("b1");
          }
          if (xPosition > 550) {
            Serial.write("b2 ");
            bluetooth.write("b2");
          }
          if (xPosition < 450) {
            Serial.write("b3 ");
            bluetooth.write("b3");
          }
        }
      }
      delay(100);
    } */
      if (buttonState == 1) {
        if (xPosition >= 450 & xPosition <= 550) {
          if (yPosition >= 450 & yPosition <= 550) {
            BL.write("a1");
            BL.print("a1");
            Serial.print("a1");
            Serial.write("a1");
          }
          if (yPosition > 550) {
            BL.write("a2");
            BL.print("a2");
            Serial.print("a2");
            Serial.write("a2");
          }
          if (yPosition < 450) {
            BL.write("a3");
            BL.print("a3");
            Serial.print("a3");
            Serial.write("a3");
          }
        }
        if (yPosition >= 450 & yPosition <= 550) {
          if (xPosition >= 450 & xPosition <= 550) {
            BL.write("b1");
            BL.print("b1");
            Serial.print("b1");
            Serial.write("b1");
          }
          if (xPosition < 450) {
            BL.write("b2");
            BL.print("b2");
            Serial.print("b2");
            Serial.write("b2");
          }
          if (xPosition > 550) {
            BL.write("b3");
            BL.print("b3");
            Serial.print("b3");
            Serial.write("b3");
          }
        }
      }
    }

Slave Code:

    // Global Area
    #include <Servo.h>
    #include <SoftwareSerial.h>
    int xPin = A1; // X connects to analog pin
    int yPin = A0; // Y connects to analog pin
    int buttonPin = 2; // Digital input pin for joystick state
    int xPosition = 0; // Digital input pin for joystick X
    int yPosition = 0; //  Digital input pin for joystick Y
    const int RX_PIN = 10;
    const int TX_PIN = 9;
    int motorBRPin = 3;
    int motorBLPin = 4;
    int motorPRPin = 6;
    int motorPLPin = 5;
    int buttonState = 0; // Joystick state variable
    Servo motor_br; // Declaration of servo with name of motor
    Servo motor_pr;
    Servo motor_bl;
    Servo motor_pl;
    SoftwareSerial BL(RX_PIN, TX_PIN);
    const int BLUETOOTH_BAUD_RATE = 9600;
    String state = "";

    void setup() {
      Serial.begin(9600); // Begin serial monitor
      BL.begin(9600);
      pinMode(xPin, INPUT); // Declaring xPin as an input
      pinMode(yPin, INPUT); // Declaring yPin as an input
      pinMode(buttonPin, INPUT_PULLUP); // Declaring buttonPin as an input
      motor_br.attach(motorBRPin); // Telling servo which pin our servo motor is attached to
      motor_bl.attach(motorBLPin);
      motor_pr.attach(motorPRPin);
      motor_pl.attach(motorPLPin);
      }
    void loop() {
      xPosition = analogRead(xPin); // Declaring the value of xPosition; The value given by the xPin read by the board at the analog input pin
      yPosition = analogRead(yPin); // Declaring the value of yPosition; The value given by the yPin read by the board at the analog input pin
      buttonState = digitalRead(buttonPin); // Declaring the value of buttonState;
      //Printing for reference
      /*Serial.print("X: ");
      Serial.print(xPosition);
      Serial.print(" | Y: ");
      Serial.print(yPosition);
      Serial.print(" | Button: ");
      Serial.println(buttonState);*/
      // If statements, if joystick is not pressed and is being pushed up, the motor will run clockwise at full speed.
      /*if (buttonState == 1) {
        if (xPosition >= 450 & xPosition <= 550) {
          if (yPosition >= 450 & yPosition <= 550) {
            motor_br.write(90);
            motor_bl.write(90);
          }
          if (yPosition > 550) {
            motor_br.write(0);
            motor_bl.write(0);
          }
          if (yPosition < 450) {
          motor_br.write(0);
          motor_bl.write(0);
          }
        }
        if (yPosition >= 450 & yPosition <= 550) {
          motor_br.write(90);
          motor_bl.write(90);
          motor_pr.write(90);
          motor_pl.write(90);
          if (xPosition < 450) {
            motor_br.write(0);
            motor_bl.write(0);
            motor_pr.write(0);
            motor_pl.write(0);
          }
          if (xPosition > 550) {
            motor_br.write(180);
            motor_bl.write(180);
            motor_pr.write(180);
            motor_pl.write(180);
        }

        }

        /*else if (xPosition < 450) {
          motor_br.write(0);
          motor_bl.write(0);
          motor_pr.write(0);
          motor_pl.write(0);
        }
        else if (xPosition > 550) {
          motor_br.write(180);
          motor_bl.write(180);
          motor_pr.write(180);
          motor_pl.write(180);
        }
        else if (yPosition >= 450 & yPosition <= 550) {
          motor_br.write(90);
          motor_bl.write(90);
        }
        else if (yPosition < 550) {
          motor_br.write(180);
          motor_bl.write(180);
        }
        else if (yPosition > 450) {
          motor_br.write(0);
          motor_bl.write(0);
        }
      }
      if (buttonState == 1) {
        if (xPosition >= 450 & xPosition <= 550) {
          motor_br.write(90);
          motor_bl.write(90);
          motor_pr.write(90);
          motor_pl.write(90);
        }
        else if (xPosition < 450) {
          motor_br.write(0);
          motor_bl.write(0);
          motor_pr.write(0);
          motor_pl.write(0);
        }
        else if (xPosition > 550) {
          motor_br.write(180);
          motor_bl.write(180);
          motor_pr.write(180);
          motor_pl.write(180);
        }
      }
      else if (buttonState == 0) {
        if (xPosition >= 450 & xPosition <= 550) {
          motor_br.write(90);
          motor_bl.write(90);
          motor_pr.write(90);
          motor_pl.write(90);
        }
        else if (xPosition < 450) {
          motor_br.write(0);
          motor_bl.write(0);
          motor_pr.write(0);
          motor_pl.write(0);
        }
        else if (xPosition > 550) {
          motor_br.write(180);
          motor_bl.write(180);
          motor_pr.write(180);
          motor_pl.write(180);
        }
      }*/
        while (BL.available()) {
          state = BL.read();
          state = Serial.read();
          Serial.print(state);
        }
        if (state == "a1" or "b1") {
          motor_br.write(90);
          motor_bl.write(90);
          state = "";
        }
        if (state == "a2") {
          motor_br.write(0);
          motor_bl.write(0);
          state = "";
        }
        if (state == "a3") {
          motor_br.write(180);
          motor_bl.write(180);
          state = "";
        }
        if (state == "b2") {
          motor_br.write(0);
          motor_bl.write(0);
          state = "";
        }
        if (state == "b3") {
          motor_br.write(180);
          motor_bl.write(180);
          state = "";
        }
        state = "";
      }

title: Arduino Bluetooth to Control Joystick Issue

Answers: 0


body:
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();
}
//*****************************************************************************************//
````````````````````````````````````

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

Answers: 1

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.


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

title: Water tank false trigger

Answers: 1

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


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

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

Answers: 4

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/


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

title: Seeburg Consolette Jukebox

Answers: 1

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.


body:
WT8266-S1 WiFi module in my hand I want to encode this module with Ardino IDE. I have a coded program for Arduino NodeMCU 1.0. How can I convert it to the WT8266-S1 WiFi module? Do you have the WT8266-S1 WiFi module source code? Firebase connection to do the application to turn off the LED. Below is a sample code share.

    #include <SoftwareSerial.h>

    SoftwareSerial esp01(9,11);

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

      pinMode(4,OUTPUT);
      digitalWrite(4,LOW);

      pinMode(12,OUTPUT);
      digitalWrite(12,LOW);

      pinMode(13,OUTPUT);
      digitalWrite(13,LOW);

      sendData("AT+RST\r\n",2000);
      sendData("AT+CWMODE=2\r\n",1000);
      sendData("AT+CIFSR\r\n",1000);
      sendData("AT+CIPMUX=1\r\n",1000);
      sendData("AT+CIPSERVER=1,80\r\n",1000);
    }

    void loop()
    {
      if(esp01.available())
      {
        if(esp01.find("+IPD,"))
        {
         delay(1000);

         // odczytanie ID połączenia
         int connectionId = esp01.read()-48;

         esp01.find("pin=");

         int pinNumber = (esp01.read()-48)*10;
         pinNumber += (esp01.read()-48);
         digitalWrite(pinNumber, !digitalRead(pinNumber));
          String closeCommand = "AT+CIPCLOSE=";
         closeCommand+=connectionId;
         closeCommand+="\r\n";

         sendData(closeCommand,1000);
        }
      }
    }

    String sendData(String command, const int timeout)
    {
        String response = "";

        esp01.print(command);

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(esp01.available())
          {
            char c = esp01.read();
            response += c;
          }
        }
        Serial.print(response);
        return response;
    }

Warning: espcomm_sync failed when I install this thread
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
 getting the error

title: WT8266-S1 WiFi module

Answers: 0


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

title: expected `}' at end of input

Answers: 2

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.


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

title: Please answer this

Answers: 1

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.


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

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

Answers: 2

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");


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

title: Write faster on AT24C32

Answers: 3

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.


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

title: Can I daisychain multiple Arduino Nanos to a single USB port (specialized purpose)

Answers: 1

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/