message:
Arduino with HC-05 Bluetooth Module | No data will be transmitted

I've got an Arduino Uno (Elegoo R3) and a Hc-05 bluetooth module. First of all i want to send data with an android app (Bluetooth terminal) to the Arduino and turn pin 13 (LED) on.

My Arduino code:

    #include <SoftwareSerial.h>

    int state = 0;

    void setup() {
      //Serial.begin(38400);
      Serial.begin(9600);

      pinMode(13, OUTPUT);
    }

    void loop() {
      if (Serial.available() > 0) {
        state = Serial.read();

        if (state == '1') {
          Serial.println("Turned on LED");

          digitalWrite(13, HIGH);
        }

        if (state == '0') {
          Serial.println("Turned off LED");

          digitalWrite(13, LOW);
        }
      }
    }

The RX and TX pins I have hooked up with the HC-05 but if I connect my smartphone with the HC-05 and type in a 1 or a 0 nothing happens. If I type a 1 or a 0 in my serial monitor on my computer (hooked up via usb to my arduino) it turns the LED on/off. The RX and TX lights also flashes one time. The bluetooth terminal app recognises all what was sent via serial monitor on pc and displays it in the app. But if I type something in the app, it won't flip the LED or show me some "Turned off LED" or "Turned on LED".

I also tried different apps from the PlayStore but all of them didn't work.

Does someone has an idea how I could fix this? Thank you for your answers.

EDIT: A drawing how my Arduino is connected to my HC-05 https://i.stack.imgur.com/N2YsJ.jpg

body:
> The TX signal coming from either the Arduino or HC-05 should be
> connected to the RX of the other as I understand it, because both are
> labeled from the perspective of their respective chips

Like @timemage already said, I connected TX with TX and RX with RX but this is wrong. The solution was to plug TX (Arduino) with RX (HC-05) and RX (Arduino) with TX (HC-05).

Thank you for your help. :)


sender: user

message:
TX Pin Stays Lit After Removing Voltage Regulator

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

To save power, I removed the linear regulator from my Arduino Nano clone and powered it via the 5V pin from a regulated source (a rechargeable USB phone charger). However, I've noticed that removing the linear regulator causes the TX pin to stay on all the time, which results in my phone not being able to communicate with the HC05 bluetooth module although it connects fine. I checked that the TX pin is not caused by `Serial.print` and noticed the same behavior on all the Nano's I've removed linear regulators from. The Nano's I've tested with the linear regulator work fine, though they use more power than I'd like. I've tried resetting the device, but the problem persists.

I'm wondering what's causing this? Isn't powering via 5V pin suppose to bypass the regulator? So what could cause the missing regulator to affect the TX pin? Unfortunately, I'm not experienced enough to connect the dots using the schematic so I was hoping someone could help me.

Though I'm not sure if it'll help, I'ved included my sketch below. Basically, I'm making using a ultrasonic sensor to communicate distance with my phone via bluetooth. It also plays music when it detects movement (using PIR sensor). Since the application is outdoor use I'm powering via battery and trying to minimize energy use. I got it down to ~4 mA by removing linear regulator.

    #include <avr/sleep.h>

    #define bluetoothIntPin 2
    #define pirInterruptPin 3
    volatile int state = 0;

    int bt_pin = 9;
    int pirPin = 8;
    int stateData = 0;
    int ultraPin = 10;
    int trigPin = 11;    // Trigger
    int echoPin = 12;    // Echo
    int piezoPin = 5;
    long duration, cm;
    unsigned char inches;
    unsigned long timer;
    volatile bool signalReceived = false;
    volatile bool pirSignalReceived = false;
    bool toggle_pir = false;
    int incomingByte = 0;
    bool song_in_progress = false;
    int song_type = 69;

    int nokia_melody[] = {

      // Nokia Ringtone
      // Score available at https://musescore.com/user/29944637/scores/5266155

      NOTE_E5, 8, NOTE_D5, 8, NOTE_FS4, 4, NOTE_GS4, 4,
      NOTE_CS5, 8, NOTE_B4, 8, NOTE_D4, 4, NOTE_E4, 4,
      NOTE_B4, 8, NOTE_A4, 8, NOTE_CS4, 4, NOTE_E4, 4,
      NOTE_A4, 2,
    };

    void setup() {
      pinMode(13, OUTPUT); //set pin 13 as output
      pinMode(ultraPin, OUTPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(pirPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(bt_pin, HIGH);
      digitalWrite(bluetoothIntPin, HIGH);
      digitalWrite(pirInterruptPin, HIGH);
      digitalWrite(ultraPin, LOW);
      digitalWrite(pirPin, LOW);
      Serial.begin(9600); // Default communication rate of the Bluetooth module
      attachInterrupt(digitalPinToInterrupt(bluetoothIntPin), bluetooth_interrupt, CHANGE);
      attachInterrupt(digitalPinToInterrupt(pirInterruptPin), pir_interrupt, CHANGE);
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      sleep_cpu();
    }

    void pir_interrupt(){
      // play sound effect
      digitalWrite(LED_BUILTIN, HIGH);
      delay(5000);
      digitalWrite(LED_BUILTIN, LOW);
      pirSignalReceived = true;
    }

    void bluetooth_interrupt(){
      state = !state;
      signalReceived = true;
    }

    void play_song(int melody[], int notes){
          // sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
        // there are two values per note (pitch and duration), so for each note there are four bytes

        // this calculates the duration of a whole note in ms
        song_in_progress = true;
        int wholenote = (60000 * 4) / tempo;

        int divider = 0, noteDuration = 0;
        for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {

        // calculates the duration of each note
        divider = melody[thisNote + 1];
        if (divider > 0) {
          // regular note, just proceed
          noteDuration = (wholenote) / divider;
        } else if (divider < 0) {
          // dotted notes are represented with negative durations!!
          noteDuration = (wholenote) / abs(divider);
          noteDuration *= 1.5; // increases the duration in half for dotted notes
        }

        // we only play the note for 90% of the duration, leaving 10% as a pause
        tone(piezoPin, melody[thisNote], noteDuration * 0.9);

        // Wait for the specief duration before playing the next note.
        delay(noteDuration);

        // stop the waveform generation before the next note.
        noTone(piezoPin);
      }
      song_in_progress = false;
    }

    void play_tone_once(){
      if (!song_in_progress){
         if (song_type==69){
          int notes = sizeof(nokia_melody) / sizeof(nokia_melody[0]) / 2;
          play_song(nokia_melody, notes);
        }
        if (song_type==79){
          int notes = sizeof(starwars_melody) / sizeof(starwars_melody[0]) / 2;
          play_song(starwars_melody, notes);
        }
      }
    }

    void loop() {
      if (signalReceived){
        sleep_disable();
        Serial.write(50);
        delay(500);
        timer = millis();
        digitalWrite(ultraPin, HIGH);
        digitalWrite(pirPin, HIGH);
        while (true){
            digitalWrite(trigPin, LOW);
            delayMicroseconds(2);
            digitalWrite(trigPin, HIGH);
            delayMicroseconds(10);
            digitalWrite(trigPin, LOW);
            pinMode(echoPin, INPUT);
            duration = pulseIn(echoPin, HIGH);
            cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
            inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
            Serial.write(inches);
            delay(50);
            incomingByte = Serial.read();
            if (pirSignalReceived){
              play_tone_once();
              pirSignalReceived = false;
            }
            else if (incomingByte == 69){ // automatic pir
              song_type = 69; //nokia
            }
            else if (incomingByte == 79){
              song_type = 79; // starwars
            }
            else if (incomingByte == 89){
              toggle_pir = !toggle_pir;
              if (toggle_pir){
                digitalWrite(pirPin, HIGH); // automate tone
              } else {
                digitalWrite(pirPin, LOW);
              }
            }
            else if (incomingByte == 99){
              digitalWrite(pirPin, LOW);
              play_tone_once();
            }
            if (incomingByte != 49 && incomingByte!=69 && incomingByte != 79 && incomingByte != 89 && incomingByte != 99){
              // receipt from android
              unsigned long timeElapse = millis() - timer;
              if (timeElapse > 7000) {
                break; // exit and SLEEP
              }
            }
            else {
                // reset the timer
                timer = millis();
              }
      }
      digitalWrite(pirPin, LOW);
      digitalWrite(ultraPin, LOW);
      digitalWrite(LED_BUILTIN, LOW);
      signalReceived = false;
      sleep_enable();
      sleep_cpu();
      }
    }

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

sender: assistant

body:
My Nano clone appears to be the same make as yours.  Certainly the underside of it looks identical.  On my clone, and I believe yours, the TX LED is wired as follows

```#
5V -- RESISTOR -- LED -- TXD/D1
```

The 5V node is just the 5V pin which is fed by USB bus voltage via a diode or by the output of the AMS1117 voltage regulator.  The TTL level serial TX signal idles high and sinks current through the LED when transmitting the start bit and low data bits.  Incidentally, the RX led is wired in the same manner.  By contrast the official Nano uses an FTDI that has dedicated LED driving pins.

It seems likely that you have bridged something with the solder that was holding the AMS1117 on the board in the process of removing it.  I would note that the regulator is mounted directly under the LEDs and their current limiting resistors and there are at least three vias in that part of the board.


message:
Can't sync with programmer Arduino Uno

I have a weird problem, and it's probably because I'm doing something wrong. I'm quite new to Arduino.

My Uno R3 (Elegoo) has been working fine for a month. It has been sitting on a bench for the past week, unused though. Last night I tried to push a sketch from the IDE: v1.8.14 on Windows 10 Pro (fully updated), board: Arduino Uno, Com port 5. I got this error:

```
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe6

```

So, I googled it and tried to fix it. No luck. And, the code changes frequently (right now it's 0x3a). So, I tried

* Using the blink sketch
* Rebooting my laptop
* Using a different USB port
* Using a different USB cable
* Using different settings in the IDE (Mega 2560 with the ATMega2560 processor)
* Using a different operating system (Ubuntu) on a different laptop with a different version of the IDE (1.8.13)
* Using a different Arduino (A Freenove Uno r3 from a robot kit)

Using a different board on windows does work! So, my original board is bricked maybe?

I got the same result, more or less. The only difference was that the response code changed. On Ubuntu, the response code is always 0x00 so I suspect the changing code is down to some problem in windows (I trust Linux a lot more than windows). I used the default blink sketch for all these attempts.

Note: I do have a green 'on' led and the L is orange and does the 3xflash on powerup and reset. This is the only USB port in use, so there's only one to choose in the IDE (happens to be com5) and it's clearly shown as Arduino. When I push the sketch, the orange L led stays solid orange and there is no flashing of the rx or tx leds.

Update:
I have read, with interest:
https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293

Because of this I have now checked the power rail with a multimeter and found 5v and 3.3v respectively on USB, and with a 9v battery I have 3.3v and 7.8v respectively. The L led flashes 3 times as expected on power up and reset.

Also, I have nothing attached to the board at all.

When I tried the loopback test the board would not power-on with reset connected to ground, so I don't know how to proceed with that.

I have just tried the Atmega16U2 chip test, and it failed. I'm pretty sure the wiring is correct (though it's hard to tell -- I can't find a dot indicating pin 1 on the good board so I'm guessing it's close to the 'n' in 'on' as mentioned in the post).

How could I have damaged this? What could I have possibly done to break that? I was only driving leds.

body:
A few things to make sure:

 - Disconnect your Arduino from any sensor or module
 - Closely look at the Arduino to see any signs of worn-out solder or damage
 - Make sure that the programming USB cable is plugged in all the way on the Arduino and the computer
 - Check the temperature of the ATMEGA chip, as well as, the voltage regulator

If everything looks normal there, you can try reflashing the bootloader on it. You can only do this if you have another Arduino Uno. Here is a good guide: https://www.instructables.com/How-to-Upload-Bootloader-to-Any-Arduino-/. Try that and then comment on what worked and what did not.


body:
Sometimes boards can glitch depending on wear and tear or on how well they have been manufactured. Personally I always buy boards direct from the Arduino store and  I have never had this issue. One thing that could help is placing a 0.1 uF capacitor between the +5V pin and ground and another between AVcc and ground. There will be some on the PCB already but this can help in some cases. Another thing that can help is pressing the reset buttom just after pressing upload on your PC.

Unfortunately, when out of sync errors occur it can be heavily luck based as to what works and how long it takes. Hopefully one of these tricks will work! But like you say, if other boards are working fine then it could just be bricked


message:
Port manipulation

My UNO having some stability issues because of  heavy memory use, I'm now optimizing the code
now looking to reduce the digital read memory use with the help of port manipulation. I got the code for      'digitial write' but no idea for the digital read pinMode(powerStatus, INPUT);digitalRead(powerStatus)
Thanks

body:
To read a pin you simply read the port the pin is part of then mask out which pin within that port you want to read.

For example to read pin D11 you need to read bit 3 of port B.

```
if (PINB & (1 << 3)) {
    // HIGH
} else {
    // LOW
}
```

However this doesn't address the underlying problems you're having with your sketch.  Saving on flash memory by optimizing your code will not fix instabilities (if anything it will introduce new instabilities from new untested code).

Instabilities related to memory are due to a lack of (or fragmentation of) SRAM not flash.  Optimizing code like this will save flash, but won't directly affect your SRAM usage at all.

Instead you need to optimize your SRAM usage by:

* Make sure all string literals are kept in PROGMEM by using the `F()` macro where appropriate
* Avoid use of `String` and instead stick to `char *` with pre-allocated buffers.
* Don't use `new` and `delete` or `malloc` and `free` as this will fragment your heap and cause instability (this is the underlying problem with `String`).


message:
Assign an interrupt to any pin of the atmega328 microcontroller

I need to record the appearance of a signal from the sensor on the PD0 pin. This is the first time in my life that I want to use an interrupt for this.
With your help, I configured the sketch for my pin PD0

    #include <avr/interrupt.h>

    volatile int value = 0;

    void setup()
    {
      cli();
      PCICR |= 0b00000100;    // turn on port d
      PCMSK2 |= 0b00000001;    // turn on pins PD0 (PCINT16)
      sei();

      Serial.begin(9600);
    }

    void loop()
    {
      Serial.println(value);
    }

    ISR(PCINT2_vect)// Port D, PCINT16 - PCINT23
    {
      value++;
    }

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

I need to wait and take a certain action when a high signal comes from the sensor. For example, add one to the constant.[![enter image description here][2]][2]
I also did not understand when interruptions occur. When the signal changes from bottom to top, when from top to bottom, or no matter how? Can't see if these settings are here? Maybe it is set somehow by default?

  [1]: https://i.stack.imgur.com/uLmaQ.jpg
  [2]: https://i.stack.imgur.com/FJHcK.jpg

body:
Here is a link to a good tutorial on how to enable, respond to, and clear interrupts on the ATMega328P device:

[Arduino Pin Change Interrupts][1]

I'll repeat the overall steps here in case this URL disappears in the future:

First, you must enable pin change interrupts:

[![Pin change Interrupts][2]][2]

Note the use of 3 bits in the PCICR register [0:2].  These enable pin change interrupts on ports B, C, or D in general.  You can choose any combination of these ports or all of the ports as you desire.

Next, you select which pin or pins on the enabled ports that you want to receive interrupts from.  You have control here over each individual port bit:

[![Pin Change Bits][3]][3]

Then you must write an ISR (Interrupt Service Routine) to handle the interrupt once it occurs.  You have the option of up to THREE ISRs, one to handle each port or you can have a single ISR to handle any pin change interrupt.  The way this works is that when an interrupt happens on an enabled port and pin, the AVR chip calls the ISR that you have configured for that event:

[![AVR ISR][4]][4]

So when an interrupt happens, how do you know which pin(s) caused the ISR?  Let's assume you used a single ISR to handle all 3 ports.  At this point you know only that an interrupt happened somewhere.  That's the purpose of the PCIFR register bits.  From the AVR datasheet we see this:

[![AVR PCIFR Bits][5]][5]

By checking the status of these bits you can now tell which pin or pins caused the interrupt.  Note that there CAN BE MORE THAN ONE, so it's up to you to decide the priority of each one and handle them accordingly.  Note that you only get ONE chance to read these during any ISR function call since they get cleared when the ISR executes.

One last note.  You MUST call the sei(); function to enable any interrupt to the CPU before any interrupt will happen.

In your example, however, you seem to be attempting to generate a pin change interrupt on an output. This is probably NOT what you want.  Try simply using the existing LED output pin as an indicator and choose a different pin, setup as INPUT, to be your pin change interrupt source.

  [1]: https://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/
  [2]: https://i.stack.imgur.com/Tfc7J.png
  [3]: https://i.stack.imgur.com/6WjYK.png
  [4]: https://i.stack.imgur.com/SMMx4.png
  [5]: https://i.stack.imgur.com/6ocpk.png


message:
Will plugging in a 12v power supply in the wrong polarity to a CNC SHIELD fry my circuit or damage my power supply?

I'm currently in the process of making a DIY pen plotter using an Arduino CNC Shield and GRBL Code. Right now I'm connecting the power supply to the shield. I got a standard 12v supply and I cut off the barrel connector so I can connect the supply directly to the CNC Shield. I can't seem to figure out which wire is negative and which is positive. I don't have a multimeter on me so can't test it but I have attached a picture of the information on the power supply which I think should be able to give someone with more knowledge, insight onto the polarity. I think the left wire is negative but not one hundred percent sure. If I risk a test will this damage my circuits or power supply ? Sorry for such an easy question I just don't want to accidentally fry my circuits as have been working on this for a really long time !!
Thank you so much,
Arav[![enter image description here][1]][1]

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

body:
If you wire the power into that shield wrongly you risk killing things - and with those big electrolytics reverse polarity could get *very* messy indeed.

You need to identify the polarity before you wire it in, and to do that you need something that is sensitive to polarity.

If you don't have a DMM you can do it with a simple resistor and LED in series - an LED will only work if the polarity is right.

Take a normal LED of the 5mm type (they're easier to identify) and look for the flat edge on the flange around the base. That indicates which is the "negative" or cathode of the LED.  Alternatively look for which of the legs is the shorter of the two, which is also an indication of which is the cathode.

Connect a resistor to this identified negative leg. You want the resistor to be at least 1kΩ, but no more than 10kΩ. You don't need the LED to be bright...

Connect your wires, one to the LED and the other to the resistor.

If the LED lights up then the wire connected to the LED is positive and the wire connected to the resistor is negative.  If it doesn't light up then the wires are reversed.  In this case check it by swapping the wires over - the LED should now light up.


message:
i was trying to rebuild my code for my bot but then there are errors coming up i am in the middle of my project so i need quick help

```c++
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 200
#define MAX_SPEED 190
#define MAX_SPEED_OFFSET 20

NewPing sonar (TRIG_PIN,ECHO_PIN,MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR34_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);

Servo myservo;
boolean goesForward=fclose;
int distance = 100;
int speedSet = 0;

void setup() {
  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
  int distanceR = 0;
  int distanceL = 0;
  delay (40);

  if (distance <= 15); {
    moveStop();
    delay(100);
    moveForward();
    delay(300);
    moveStop();
    delay(200);
    distanceR = lookRight();
    delay(200);
    distanceL = lookLeft();
    delay(200);

    if (distanceR>=distanceL) {
      turnRight();
      moveStop();
    } else {
      turnLeft();
      moveStop();
    }}else {
      moveForward();
    }
      distance=readPing();
  }

  int lookRight() {
    myservo.write(170);
    delay(500);
    int distance=readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
  }

  int readPing() {
    delay(70);
    int cm = sonar.ping_cm();
    if (cm ==) {
      cm=250;
    }
      return cm;
  }

  void moveStop() {
    motor1.run(RELEASE);
    motor2.run(RELEASE);
    motor3.run(RELEASE);
    motor4.run(RELEASE);
  }

  void moveForward() {
    if (!goesForward) {
      goesFORWARD=true;
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
      for (speedSet=0; speedSet<MAX_SPEED;speedSet+=2) {
        motor1.setSpeed(speed.Set};
        motor2.setSpeed(speed.Set};
        motor3.setSpeed(speed.Set};
        motor4.setSpeed(speed.Set};
        delay(5);
      }
    }
  }

  void moveBackward() {
    goesFORWARD=false;
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
    for (speedSet=0; speedSet<MAX_SPEED;speedSet+=2) {
      motor1.setSpeed(speed.Set};
      motor2.setSpeed(speed.Set};
      motor3.setSpeed(speed.Set};
      motor4.setSpeed(speed.Set};
      delay(5);
    }
  }

  void moveRight() {
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
    delay (500);
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
  }

  void moveRight() {
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
    delay (500);
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
  }

```
this is the error code
```
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"
C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'void loop()':

sketch_nov27b:53:13: error: 'lookLeft' was not declared in this scope
 distanceL = lookLeft();
             ^~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:53:13: note: suggested alternative: 'lookRight'

 distanceL = lookLeft();
             ^~~~~~~~
              lookRight

sketch_nov27b:58:1: error: 'turnRight' was not declared in this scope
 turnRight();
 ^~~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:58:1: note: suggested alternative: 'lookRight'

 turnRight();
 ^~~~~~~~~
 lookRight

sketch_nov27b:62:1: error: 'turnLeft' was not declared in this scope
 turnLeft();
 ^~~~~~~~

Sketch_nov27b:65:4: error: 'else' without a previous 'if'

   }else

    ^~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'int readPing()':

sketch_nov27b:86:10: error: expected primary-expression before ')' token

   if(cm==)

          ^

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'void moveForward()':

sketch_nov27b:104:1: error: 'goesFORWARD' was not declared in this scope

 goesFORWARD=true;

 ^~~~~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:104:1: note: suggested alternative: 'FORWARD'

 goesFORWARD=true;

 ^~~~~~~~~~~

 FORWARD

sketch_nov27b:111:17: error: 'speed' was not declared in this scope

 motor1.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:111:17: note: suggested alternative: 'speedSet'

 motor1.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

sketch_nov27b:112:17: error: 'speed' was not declared in this scope

 motor2.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:112:17: note: suggested alternative: 'speedSet'

 motor2.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

sketch_nov27b:113:17: error: 'speed' was not declared in this scope

 motor3.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:113:17: note: suggested alternative: 'speedSet'

 motor3.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: At global scope:

sketch_nov27b:114:1: error: 'motor4' does not name a type

 motor4.setSpeed(speed.Set};

 ^~~~~~

sketch_nov27b:114:26: error: expected declaration before '}' token

 motor4.setSpeed(speed.Set};

                          ^

Multiple libraries were found for "Servo.h"

 Used: C:\Users\amish\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\Servo

exit status 1

'lookLeft' was not declared in this scope

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

body:
Your code is riddled with typographical and basic syntax errors. Such things as using brackets instead of parentheses, semicolons after an `if` meaning it will do nothing, etc.

Sort out your basic syntax errors (hint: autoformat can help you with the indenting to highlight your problems) and you will see where you have gone wrong.

For instance, after autoformatting your code with `astyle` the `moveForward()` function has turned into this mess:

``` 98 void moveForward() {
 99     if (!goesForward) {
100         goesFORWARD = true;
101         motor1.run(FORWARD);
102         motor2.run(FORWARD);
103         motor3.run(FORWARD);
104         motor4.run(FORWARD);
105
106         for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) {
107             motor1.setSpeed(speed.Set
108         };
109
110         motor2.setSpeed(speed.Set
111     };
112
113     motor3.setSpeed(speed.Set
114 };
115 motor4.setSpeed(speed.Set
116 };
117 delay(5);
118 }
119 }
120 }
```

Also, you have no `lookLeft` function - instead you have two `lookRight` functions.  You really should *read* what you've written.


message:
share enum between python and arduino

I have created a gui in python that allows an arduino controlled mecanum wheel cart to move around.

The cart allows for 8 different move directions and can rotate left and right. Commands are sent over a serial connection between the laptop(w10, python) and the arduino.

I have an Enum class in python representing the different move directions.

I have a corresponding enum in the arduino to interprete the commands from the python task.

What is an easy way to share a single common enum definition for both coding environments?

body:
One approach that I have used for similar purposes is to generate the appropriate header files (or module or whatever) from a simple text file for all the required uses.

Since you already know python this should be pretty easy. Quick "proof of concept" follows. (Warning: I barely know any python.)

One downside to this is that you have to remember to regenerate the header/module each time you update the enum (keys or values) - don't forget to recompile for the C++ part. If you have a build system, it is best to integrate that code generation step into it.

A variation of this is to parse one of the language's source code to extract the definition and output it in a format suitable for the other. That is generally much harder to do though if you want to make it robust.

---

### robot.enum

    UP    1
    DOWN  2
    LEFT  3
    RIGHT 4
    JUMP  5

### enum_generator.py

<!-- language: lang-python -->

    def python_enum(filename):
        with open(filename, 'w') as w:
            w.write('class Robot(Enum):\n')
            with open('robot.enum') as r:
                for line in r:
                    parts = line.split()
                    w.write(f'    {parts[0]} = {parts[1]}\n')

    def cplusplus_enum(filename):
        with open(filename, 'w') as w:
            w.write('#pragma once\n')
            w.write('enum Robot: int {\n')
            with open('robot.enum') as f:
                for line in f:
                    parts = line.split()
                    w.write(f'  {parts[0]} = {parts[1]},\n')
            w.write('};');

    python_enum('robot_enum.py')
    cplusplus_enum('robot_enum.h')


message:
Are the GND pins of an Arduino identical to GND of its power supply?

What would happen if I connected a fan as shown in the following picture:

[![Fan connected to +12V of the power supply and GND of the arduino][1]][1]

 - +12V is supplied by the power supply that also powers the Arduino.
 - GND, however, is connected to a GND pin of the Arduino instead of the power supply.

I guess that would not work? Or are GND from the Arduino and GND from the power supply identical in this case?

----------

If you read the accepted answer, please also note the comments below. The power consumption of the consumer (fan) is important.

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

body:
"Ground" is just a lump of metal and each ground "pin" is connected to it. That includes the ground connection in the barrel jack. It's all one thing.

Wherever you connect your fan's ground to it's all ground.  That is, as long as all grounds external to the Arduino are connected, ultimately, to the Arudino.


message:
Arduino with interrupts enters in a locking state

I am quite noobish with using the interrupts on Arduino and I am facing a strange problem. I am using an Arduino Pro Mini, a light sensor and an RTC module(DS3231) which has set 2 alarms, one at sunrise and one at the sunset. Each time the DST triggers the alarm, the interrupt routine (here onAlarm()) blocks the state of Arduino and nothing happens form there. Is there anything wrong with the code I write?

The code bellow is a little bit simplified, I just let the method calls, not the whole declarations of them.

    #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
    #include <avr/power.h>
    #include <DS3232RTC.h>  //RTC Library https://github.com/JChristensen/DS3232RTC

    #define ldrInterruptPin  2
    #define DS2331interruptPin 3

    void setup() {

      Serial.begin(9600);//Start Serial Comunication
      Wire.begin();

      //_____________________setup DS3231 interrupts_________
      pinMode(DS2331interruptPin, INPUT_PULLUP);
      digitalWrite(DS2331interruptPin, HIGH);
      attachInterrupt(digitalPinToInterrupt(DS2331interruptPin), onAlarm, FALLING);

      //_____________________setup LD235R interrupts_________
      pinMode(ldrInterruptPin, INPUT);
      digitalWrite(ldrInterruptPin, HIGH);
      attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);

      resetDS3231Alarms();

      time_t t = RTC.get();
      setUpAlarms();
    }

    void loop() {
     //read the light sensor vlaues
    }

Adn this is the onAlarm function:

      void onAlarm() {
      Serial.println("ALARM");
      formatTime(timestamp, RTC.get());
      if (RTC.alarm(ALARM_1))
      {
        Serial << F("SLEEP alarm at ") << timestamp << endl;
        goToSleep();
      }
      else if (RTC.alarm(ALARM_2))
      {
        Serial << F("WakeUP Alarm at ") << timestamp << endl;

        Serial.println("Time to Wake up......!");
        sleep_disable();
        Serial.println("I woke up!!!");
        attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);
      }
      //update the sleep and wakeup times based on curreent day
      setUpAlarms();
    };

resetAlarms()

    void resetDS3231Alarms() {
      // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
      RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
      RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
      RTC.alarm(ALARM_1);
      RTC.alarm(ALARM_2);
      RTC.alarmInterrupt(ALARM_1, false);
      RTC.alarmInterrupt(ALARM_2, false);
      RTC.squareWave(SQWAVE_NONE);
    }

Every time an alarm occurs, the code blocks and outputs exactly what is in the serial monitor capture bellow:
It just prints "AL" form the Serial.println("ALARM"); and nothing happens from there

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

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

Does anyone know what causes this issue and how can it be solved?

body:
When the AVR processor goes to sleep, the _only_ way it can wake up is
by an interrupt. If it goes to sleep with interrupts disabled, then it
will never wake up.

Interrupt routines are by default non-interruptible: the first thing the
processor does when servicing an interrupt is to disable further
interrupts. Your `onAlarm()` function is thus running with interrupts
disabled. If it goes to sleep, it will lock the processor.

A quick and dirty fix would be to call `interrupts()` right before going
to sleep. I would not recommend that though, as you will end up piling
interrupt contexts one over another. The proper fix would be to trim
down your interrupt  service routines to the bare minimum that must be
done immediately, and handle everything else in regular code, within
`loop()`. In this particular case, setting a `volatile bool` might well
be the only thing you really need to do. Your `loop()` would test that
`bool` and take care of everything else.


message:
Comparing a String after reading it from Serial fails

I have bought an Arduino starter kit online. Everything seem to work, but when I try for example to use `if`s (and other conditional statements), the LEDs do not turn on. Here is the code for a little project I am currently working on:

```c++
int redpin = 3;
int greenpin = 2;
int bluepin = 4;
String color;
String msg = "Insert color: ";

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin,OUTPUT);
  pinMode(greenpin,OUTPUT);
  pinMode(bluepin,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(msg);
  while (Serial.available() == 0) {}
  color = Serial.readString();

  if (color == "red") {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "green") {
    digitalWrite(greenpin, HIGH);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "blue") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, HIGH);
  }

  if (color == "off") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
}
```

I tried turning on the RGB LED with single `digitalWrite()` functions and it works. I think that the `if` statements in the code are the problem.

I`m using an Arduino Mega 2560 BTW.

body:
After `color = Serial.readString();` `color` also contains a newline character.

You can remove that by adding the line `color.trim();`, or even better, avoid the newline altogether by using `Serial.readStringUntil('\n');` which discards the terminating newline character.

Also, you could, and maybe should, avoid using the `String` class and use:
```c++
char color[10]; // char array as buffer for reading from Serial
```
```c++
int number = Serial.readBytesUntil('\n', color, 10); //Read input and length
color[number] = '\0'; //Terminate the string by adding '\0' at its end
```
```c++
if (strcmp(color, "red") == 0) //Use strcmp(), not ==
```
respectively.


message:
Multiplexing a piano keyboard with arduino nano

I'm trying to use a cheap keyboard with 37 keys as a MIDI controller by reading the multiplexed keys with an Arduino nano. The keys are grouped in six groups with a max of 8 keys per group. Which results in my setup of 8 digital INPUTS which are pulled HIGH, and 6 OUTPUTS, which are pulled LOW, when reading that group of keys.
This works great when I only have 3 groups in my loop. However whenever I add another group it does not work anymore. It doesn't matter which groups are activated.

One group reading looks like this:

    digitalWrite(A0, LOW);
    for (byte j = 12; j > 4; j--)
    {
      uint8_t note = offset + 20 + (12-j);
      uint8_t key_state = digitalRead(j);

      if ( (key_state == 0) && (notes_pressed[note] == 1) )
      {
        notes_pressed[note] = 0;
        Serial.write(note + 100);
      } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
      {
        notes_pressed[note] = 1;
        Serial.write(note);
      }
    }
    digitalWrite(A0, HIGH);

With A0 being the group pin.

I think this has to do with the pins not being able to be pulled low as quickly because of weak output drivers or something similar. Unfortunately I don't have an oscilloscope to check the levels.
I have added delays to ensure the levels have settled when the reading occurs but to no avail.

Edit:
Schematic is pretty much just this. The diodes in the keyboard I left out, but they are there as necessary:
[![schematic][1]][1]

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

    #include "HardwareSerial.h"

    #define offset 48

    void midi_note_off(byte channel, byte key, byte velocity);
    void midi_note_on(byte channel, byte key, byte velocity);
    void midi_command(byte command, byte channel, byte param1, byte param2);

    byte notes_pressed[37];
    void setup() {
      Serial.begin(115200);
      pinMode(12, INPUT_PULLUP);
      pinMode(11, INPUT_PULLUP);
      pinMode(10, INPUT_PULLUP);
      pinMode(9, INPUT_PULLUP);
      pinMode(8, INPUT_PULLUP);
      pinMode(7, INPUT_PULLUP);
      pinMode(6, INPUT_PULLUP);
      pinMode(5, INPUT_PULLUP);
      pinMode(4, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(A2, OUTPUT);
      pinMode(A1, OUTPUT);
      pinMode(A0, OUTPUT);

      digitalWrite(4, HIGH);
      digitalWrite(3, HIGH);
      digitalWrite(2, HIGH);
      digitalWrite(A0, HIGH);
      digitalWrite(A1, HIGH);
      digitalWrite(A2, HIGH);
    }

    void loop() {
      digitalWrite(4, LOW);
      for (byte j = 8; j > 4; j--)
      {
        uint8_t note = offset + (8-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(4, HIGH);

      digitalWrite(3, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 4 + (12 - j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(3, HIGH);

      digitalWrite(2, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 12 + (12-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(2, HIGH);

      digitalWrite(A0, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 20 + (12-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(A0, HIGH);

      digitalWrite(A1, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 28 + (12-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(A1, HIGH);

      digitalWrite(A2, LOW);
      for (byte j = 5; j > 4; j--)
      {
        uint8_t note = offset + 36 + (5-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(A2, HIGH);
    }

I know the last part looping over a single value is unnessecary but it should still work.

body:
There are several issues to be considered when designing a [switch matrix][1] for an embedded processor regardless if it is a musical or computer keyboard:

 1. [Contact bounce][2]: This is more important for a computer keyboard
    then a musical keyboard.  However if the switch are particularly
    bad, it may audible.  Software may be used to mitigate the problem
    but will also add delay between the key press and the beginning of
    the note's sound.
 2. [Pull Ups][3]: Any logic input should not be left unconnected or
    floating.  This can lead to unexpected results.  Use Pull Up
    resistors (or Pull Down depending on your design) to mitigate this
    problem.  The [Arduino Uno's][4] embedded processor ([the
    ATmega328P][5]) comes with built in Pull Up resistors.
    The Arduino IDE abstracts this feature by including a parameter it
    the [pinMode() function][6] call to invoke this feature.
 3. [Rollover][7]: In a switch matrix 1 or 2 simultaneous switch
    closure can be uniquely detected.  However, if 3 switch closures
    connect 2 rows and 2 columns together, they can not be uniquely
    detected.  This is because current can flow through the 3 closed
    switches activating both rows and both columns nullifying the
    ability for the embedded processor to scan individual rows or
    columns.  To mitigate this problem a diode is added to all
    switches in the switch matrix such that there is no current path
    between rows or columns.

From the [Rollover wikipedia page][8]:
> Most music keyboards use isolation diodes in their keyboard matrix to
> implement full n-key rollover, making them immune to both key ghosting
> and key jamming

This image if from [this stack exchange question][9]:
[![This image is from [this stack exchange question][8].][10]][10]

  [1]: https://en.wikipedia.org/wiki/Keyboard_matrix_circuit
  [2]: https://en.wikipedia.org/wiki/Switch#Contact_bounce
  [3]: https://en.wikipedia.org/wiki/Pull-up_resistor
  [4]: https://store.arduino.cc/usa/arduino-uno-rev3
  [5]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
  [6]: https://www.arduino.cc/reference/en/language/functions/digital-io/pinmode/
  [7]: https://en.wikipedia.org/wiki/Rollover_(key)
  [8]: https://en.wikipedia.org/wiki/Rollover_(key)#n-key_rollover
  [9]: https://arduino.stackexchange.com/questions/31885/need-help-in-circuit-diagram-of-88-reed-switch-matrix
  [10]: https://i.stack.imgur.com/76A84.jpg


body:
A few excerpts from the program:

```c++
#define offset 48
//...
byte notes_pressed[37];  // valid indices: 0 – 36
//...
uint8_t note = offset + (8-j);  // j ≤ 8, thus note ≥ 48
//...
notes_pressed[note] = 0;
```

That last line writes past the end of the `notes_pressed` array, and
overwrites who knows what in memory. This could be the source of the
issue you are facing.


message:
Best buffering practice for continuous SD card writing

In a simplified example, I have a microcontroller functioning as a data acquisition device - sensor data is received over UART, and then saved to an SD card.

This received data is in the form of a 12 byte struct, received at 1kHz. The microcontroller receiving the data is an esp32, with an SD card connected over spi. Not an uncommon issue, but if a typical SD card write is triggered everytime new data is received, it will take longer than the gap between samples to  write the data.

What is typically considered the best practice for this type of system, presuming the data will always be received faster than it can be written. I have seen examples of circular buffers, but presumably these will eventually fill completely and samples will be missed.

In my particular example, I have the bonus second cpu core in the esp32. Therefore, my thinking is to use 2 alternating buffers. Data will be received on core 1, and placed into the active buffer. When the buffer is full, incoming data will be written to the second buffer, and the first will be written to the SD card by core 2.

Is this a sensible solution to the problem? I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.

body:
Buffers will help you if at some point the input stream stops, so the "slower" device (e.g. the SD card) can catchup. If *the data will always be received faster than it can be written* (note **always**) then no buffer will help you.

But I assume you meant that there times where you get bursts of input data at 1Khz, then it will stop. So, as long as the _average_ input data rate is lower than the ability for the SD to persist the data, you will be fine.

The SD card library already has a buffer (as @Majenko pointed out), so most likely you won't need to do anything. Seem like something you can test relatively simply.

The 2 core approach sounds somewhat overkill (not to mention some synchronization issues you will have to deal with)


body:
> Is this a sensible solution to the problem?

No, unfortunately not. The size of the buffer is limited by the available RAM on your chip. Jumping between multiple buffers or cores will not change that, since it is a hardware limitation.

> I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.

When you are continuously receiving faster than you can write, you only have 2 options:

- Improve write speed
- Reduce the needed data size

There is no other way, and that's a logical conclusion, not so much a programmical or hardware conclusion. It that situation the amount of "buffered" data will increase indefinitely, so you would need an infinite amount of memory. And that doesn't exist in real world. The same principle would apply to a high end PC with lots of memory, it will just be full after longer time, than with an ESP.

- Improving write speed:
    - On various sites I have read, that you can use the SD card with different SPI frequencies. A higher frequency would mean a higher transaction speed. You can investigate further at this point.
    - Writing a full 512 byte page at once and only closing and opening the file again, if really needed, will improve the overall speed.

- Reduce the needed data size
    - Maybe you can compromise with your data resolution and then pack those values as dense as possible (like packing two 4-bit values into a single byte of transmission).
    - You can research for compression code, so that you can compress your data lossless before transmitting it. Though the result will always depend on the kind of your data. Also mind, that in this case you are trading transmission size for computation time and RAM.

About buffers:

I would say, a normal circular buffer does not bring you much advantages here, since with the SD card you don't want to do bytewise data transmission. The 2 buffer approach, that you mentioned, seems good to me. Though doing handling with different cores does not make much sense to me. The UART receiving itself is done by hardware and some ISRs. You can do all the SD card transmissions in your main code, just making sure, that you regularly copy the received data from the Serial buffer into your buffer.


body:
Forgive my non-technical analogy, but this is how my brain works.   Hope you can get past the conclusion that "this isn't a technical answer", until you at least see it from this different perspective.

Buffers, input streams, and sampling rates, storage rates all relate strongly to filling up a bath.   Taps, water, baths and plug holes?   WTF?

Try slightly blocking the plug hole in your bath, and turn both taps on full.

The water that's drained away is the rate of which data is stored to the SD card.  That's the storage-rate.

The remaining water which doesn't drain away fast enough causes the bath the fill up.   The water is the sampling rate, the bath is the buffer.

If the taps remain on, and water is leaving the taps faster than the water can escape from the partially blocked hole will cause the bath to fill up with water.

So, if the blockage isn't cleared, the bath will eventually overflow.

Either you turn the taps down, use a bigger bath, or increase the drainage rate.


body:
One approach would be to use Circular Buffering. It involves using a fixed-size buffer that wraps around itself, allowing data to be continuously written and overwritten. This approach eliminates the need for costly memory reallocation or shifting operations. As new data is written, older data is overwritten in a circular fashion. But, you will need to choose the appropriate buffer size. A larger buffer size can help handle bursts of data However, larger buffers also consume more memory.

If one buffer isn't enough, then you could use Two buffers instead. While one buffer is being written to the SD card, the other buffer can be used to receive new incoming data. Once the write operation is completed, the roles of the buffers are swapped. This technique can help improve efficiency by minimizing data transfer and write latency, which is the goal you aim at. I've used this type of buffer for audio data acquisition, and it worked well, got rid of the buffer overflow issues.

The other method would be to use DMA,  if your microcontroller or system supports it, which I think it does, using DMA for SD card writing can offload the data transfer task from the CPU. DMA allows direct memory access without CPU intervention, enabling faster and more efficient data transfers. DMA can significantly reduce the overhead associated with continuous SD card writing.

For DMA, you might want to check this:
https://github.com/RobTillaart/DAC8552/issues/8 and this: https://github.com/espressif/esp-idf/blob/master/examples/peripherals/spi_master/lcd/main/spi_master_example_main.c


message:
Merging two 2-d arrays in order of axes

Looking to merge two different 2D arrays of different row sizes into one long array:

 ```
  int 2dArray1[][] = {
    {1, 2, 3},
    {4, 5, 6}};
  int 2dArray2[][] = {
    {10, 20},
    {30, 40}};
  int 1dLongArray[10];
```
 This is where I need help in order to have the values of 1dLongarray be arranged as follows:
```
1, 2, 3, 10, 20, 4, 5, 6, 30, 40
```
How would I achieve this? Thanks in advance.

body:
Consider using loops of length specific to the desired number of transactions.  For example, using this pseudo code create a sketch which follows this pattern:

    initialize i to zero
    loop 2 times for each row using the variable x
      loop 3 times for each element in first array using the variable y
        long array [i] = first array[x][y]
        increment i
      loop 2 times for each element in a second array using the variable z
        long array [i] = second array[x][z]
        increment i


message:
When is SPI.beginTransaction required?

I have been gradually converting many devices from i2c to spi for various reasons.  I noticed in tutorials like [this from arduino.cc][1] that `SPI.beginTransaction` is explicitly called out.  Then they link to examples such as [this][2] and [this][3] where they don't use `SPI.beginTransaction`.  In working through my own devices I found that I could often (almost always) forgo the use of `SPI.beginTransaction`.  The only case where I found problems was when I had 2 devices that used different SPI settings.

I went to Google and other searches for a simple reason for `SPI.beginTransactions` and found discussions of interrupts and locks and settings.  There was much discussions about users applications wrapping all calls with `SPI.beginTransaction` and `SPI.endTransaction`.  There were bugs when libraries didn't wrap everywhere.

This leads me to the conclusion that making calls to `SPI.beginTransaction` are only needed when the SPI settings need to change, but in practice you should always do it.  Is there documentation or examples that definitely state the purpose and proper (best practice) usage of it?

  [1]: https://www.arduino.cc/en/Reference/SPI
  [2]: https://www.arduino.cc/en/Tutorial/LibraryExamples/BarometricPressureSensor
  [3]: https://www.arduino.cc/en/Tutorial/LibraryExamples/DigitalPotControl

body:
It appears calling the method [beginTransaction()][1] prevents additional SPI transactions from interrupting the current transaction.  Calling [endTransaction()][2] allows access to the SPI hardware again. This added complexity may sound odd.  Especially in the simple Arduino sketch-writing paradigm.  But as programs grow in complexity, more SPI devices are added and interrupts are used to quickly access SPI devices - the likely hood of SPI contention increases.

In the [SPIClass source code][3], there is this comment immediately before the beginTransaction() method:

      // Before using SPI.transfer() or asserting chip select pins,
      // this function is used to gain exclusive access to the SPI bus
      // and configure the correct settings.

So, it may be, that if the sketch-code is particularly well behaved and does not need protection from accidentally using the SPI hardware from multiple concurrent transactions, that these two methods need not be used.  But why take the chance.

  [1]: https://www.arduino.cc/en/Reference/SPIbeginTransaction
  [2]: https://www.arduino.cc/en/Reference/SPIendTransaction
  [3]: https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SPI/src/SPI.h


body:
Every modern Arduino library for a SPI device should use SPI library with beginTransaction to be able to coexists with libraries for SPI devices using different modes and speed.

Recently we had here [a question][1] about two libraries for SPI not working together. The devices required different modes. The libraries didn't use beginTransaction, they only used SPI.begin() in initialization. It is not possible to use these libraries together.

The STM32 core supports switching CS pin with enhanced beginTransaction and endTransaction but this is not so useful as it looks. Many devices use CS as 'commit' and the CS must be switched several times inside one 'transaction'.

If you write a library you don't know with what other SPI devices on bus it will be used so call [`beginTransaction`][2] as the library gets control and [`endTransaction`][3] as the public library function returns control out of the library.

  [1]: https://arduino.stackexchange.com/questions/78050/my-two-slave-spi-setup-on-arduino-not-working-correctly/78055#78055
  [2]: https://www.arduino.cc/en/Reference/SPIbeginTransaction
  [3]: https://www.arduino.cc/en/Reference/SPIendTransaction


body:
Although this question has an accepted answer, I'd like to provide some background and historical reasons to OP's question.

Transactional SPI using `SPI.beginTransaction()` was introduced in 2014, it was not available in the early version of the Arduinos or example codes published before that. As the results, there are still many codes out there on the Internet show the old way of setting up the SPI configuration, and this include the exampes provided by Arduino.cc on its [library reference page](https://www.arduino.cc/en/Reference/SPI) even up to today, the authors of the library did not make any changes in those examples to show the usage of new API.

What the `SPI.beginTransaction()` does is to allow you to set unique SPI settings(through `SPISettings` object) for your application, even if other devices use different settings. `SPI.beginTransaction()` behave like a locking mechanism to gain the exclusive use of the SPI bus, and therefore requires `SPI.endTransaction()` to release the bus for others to access it. `SPI.beginTransaction()` provides better cross-device compatibility and solve software conflicts and allowing multiple SPI devices to properly share the SPI bus. You should therefore use the `SPI.beginTransaction()` in your SPI sketch. You should also using `SPISettings` object to configure your SPI communication interface, and not use the deprecated methods such as `SPI.setBitOrder()`, `SPI.setClockDivider()` and `SPI.setDataMode()` for setting up the SPI configuration.

Although rarely need today, there is a pre-defined macro `SPI_HAS_TRANSACTION` in SPI library for checking whether the firmware of the Arduino board supports `SPI.beginTransaction()`. It is useful for providing backward compatibility if you are writing an Arduino library.

    #ifdef SPI_HAS_TRANSACTION
      SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
    #elseif
      // use old Arduino SPI library syntax
    #endif


message:
How to move a servo with a function

Im currently moving a servo from one side to another by using the typical for loop like this:

    int lightON = 180;
    int lightOFF = 90;

    if (buttonState == HIGH) {

      digitalWrite(LED, HIGH);
      for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
        servo1.write(pos1);
        delay(15);
      }
      digitalWrite(LED, LOW);

    }

That would be moving the servo one way and if I push the button again the servo would move another way.

    if (buttonState == LOW) {

      digitalWrite(LED, HIGH);
      for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
        servo1.write(pos1);
        delay(15);
      }
      digitalWrite(LED, LOW);

    }

The thing is, I have this very same code in 3 other servos and I don't want to be repeating the same code with 2 different variables (pos and servo) over and over again, so I tried

    void runServoLight(int pos, int light1, int light2, Servo servo, int state) {

      if (state == 1) {

      digitalWrite(LED, HIGH);

      for (pos = light1; pos <= light2; pos += 1) {
         servo.write(pos);
         delay(15);
      }

      digitalWrite(LED, LOW);

      } else if (state == 0) {

      digitalWrite(LED, HIGH);

      for (pos = light2; pos >= light1; pos -= 1) {
        servo.write(pos);
        delay(15);
      }

      digitalWrite(LED, LOW);

      }

    }

Now instead of running the whole for loop code I only run:

    runServoLight(pos1, lightON, lightOFF, servo1, 1);

The problem is that it doesn't seem to work and I can understand why, I may be writing the function wrong but im nor really sure. I would really appreciate some help. Thank you!

body:
You wrote:

> ```c++
> void runServoLight(
>         int pos, int light1, int light2, Servo servo, int state)
> ```

Here you are giving the list of parameters used by the function. In C++,
parameters are by default passed _by value_. This means that, when the
function is called, the arguments passed in the call are _copied_ into
the parameters listed here, which are local variables of the function.
Changes to those parameters will not propagate to the arguments provided
by the caller.

This can be an issue for the `Servo` object. This object keeps some
internal state, which has the memory of the current configuration of the
timers. Since you are working on a copy of the provided object, the
original object is not updated when you act on the copy. I do not know
whether this is making your program misbehave, but it would be safer to
pass the `Servo` object _by reference_:

```c++
void runServoLight(
        int pos, int light1, int light2, Servo &servo, int state)
```

This way the object will not be copied: the function will instead work
on the original object provided by the caller.

The same may apply to the _pos_ parameter. The very first thing the
function does with this parameter is to overwrite it. Then there is no
point in receiving that value from the caller. You can instead remove
the parameter and create a local variable with the same name:

```c++
void runServoLight(int light1, int light2, Servo &servo, int state) {
    int pos;  // local variable
    ...
}
```

If you want the caller's version of this variable to be updated, you
could pass it by reference, just like the `Servo` object. It is,
however, more efficient to keep the variable local and have the function
return the final position. The call would then look like:

```c++
pos1 = runServoLight(lightON, lightOFF, servo1, 1);
```

One final point that is not visible in the snippets you showed: are you
doing _edge detection_ on the buttons? Edge detection means that you act
on the _changes_ of state of the buttons, not on the states themselves.
For example, you move from `lightOFF ` to `lightON` not when the button
state _is_ `HIGH` but rather when it _turns_ `HIGH`.


body:
This is not a solution, however, by rafactoring it makes your sketch more maintainable as duplicated code is removed:

    void runServoLight(int pos, int light1, int light2, Servo servo, int state)
    {
      if (state == 1) {
        process(light1, light2, +1, servo);
      }
      else if (state == 0) {
        process(light2, light1, -1, servo);
      }
    }

    def process(int this_light, int other_light, int delta, Servo servo)
    {
      digitalWrite(LED, HIGH);
      for (pos = this_light; pos >= other_light; pos += delta) {
        servo.write(pos);
        delay(15);
      }
      digitalWrite(LED, LOW);
    }

Instead of the state integer, it's more clear to use an enumeration and use a `switch` statement.

    #include "Servo.h"

    const int LED = 13;

    enum EServoState { LEFT, RIGHT };

    void runServoLight(int light1, int light2, Servo servo, EServoState state);

    void setup()
    {
    }

    void loop()
    {
      int light1 = 1;
      int light2 = 2;
      EServoState state;
      Servo servo;
      runServoLight(light1, light2, servo, state);
    }

    void runServoLight(int light1, int light2, Servo servo, EServoState state)
    {
      switch (state)
      {
      case LEFT:
        process(light1, light2, +1, servo);
        break;

      case RIGHT:
        process(light2, light1, -1, servo);
        break;

      //default:
       // Handle program error
      }
    }

    void process(int this_light, int other_light, int delta, Servo servo)
    {
      digitalWrite(LED, HIGH);
      for (int pos = this_light; pos >= other_light; pos += delta)
      {
        servo.write(pos);
        delay(15);
      }
      digitalWrite(LED, LOW);
    }


message:
74HC595 to 4 Digit 7 Segment using SevSegShift Library

I have a question regarding the use of [SevSegShift][1] library. I followed the example properly and tested it to see if it works. It was able to power up the seven segments and light up the whole LEDs (even the decimal) but it's not showing the output I want to show.

Based on the code below, I want to show the number 500 but it does not. Even tried `sevsegshift.setChars("abcd")`, no change.

This is my code:

    #include <SevSegShift.h>

    #define SHIFT_PIN_SHCP 6
    #define SHIFT_PIN_STCP 5
    #define SHIFT_PIN_DS   4

    SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

    void setup() {
      byte numDigits = 4;
      byte digitPins[] = {9, 10, 11, 12}; // These are the PINS of the ** Arduino **
      byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
      bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
      byte hardwareConfig = COMMON_CATHODE; // See README.md for options
      bool updateWithDelays = false; // Default 'false' is Recommended
      bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
      bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or isn't connected

      sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
      sevseg.setBrightness(10);
    }

    void loop() {
      sevseg.setNumber(500);
      //delay(1000);
      sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
    }

This is my breadboard schematic down below.

[![Breadboard][2]][2]

(220 ohm resistors on the digit pins and the segment pins are connected to the shift register)

  [1]: https://github.com/bridystone/SevSegShift
  [2]: https://i.stack.imgur.com/ug6Md.png

body:
Finally able to fix it with the help of @PeterPaulKiefer, I was able to find the problem. The problem is in the code itself (schematic is alright. No changes there) and this is the updated code.

    #include <SevSegShift.h>

    #define SHIFT_PIN_SHCP 6
    #define SHIFT_PIN_STCP 5
    #define SHIFT_PIN_DS   4

    SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

    void setup() {
      byte numDigits = 4;
      byte digitPins[] = {12, 11, 10, 9}; // These are the PINS of the ** Arduino **
      byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
      bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
      byte hardwareConfig = COMMON_ANODE; // See README.md for options
      bool updateWithDelays = false; // Default 'false' is Recommended
      bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
      bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected

      sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
      sevseg.setBrightness(100);
    }

    void loop() {
      sevseg.setNumber(500);
      sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
    }

**What changed:**

 1. Turns out my 7-segment is `COMMON_ANODE` so I changed my `hardwareConfig`
 2. Set brightness to 100
 (At this point, it shows the number in reverse but with a decimal point in each digit)
 3. Set `disableDecPoint` to `false`
 (At this point, the display is showing but in reverse but no more decimal point)
 [![reverse][1]][1]
 4. To fix this, I set the `digitPins[]` in reverse and it now shows the proper format
 [![Correct Output][2]][2]

Thank you so much Peter for helping me figure out what's wrong!

Also the LED Bar I use is [4-Digit 0.36" LED, 7-segments display, common-anode][3]. (The link is to the shop I got it from)

  [1]: https://i.stack.imgur.com/sAuEM.jpg
  [2]: https://i.stack.imgur.com/Cf6tK.jpg
  [3]: https://store.createlabz.com/products/40-005?_pos=3&_sid=cf5299bd3&_ss=r


message:
Problems uploading with a new Nano

My first post - I am a relative newbie.

I want to make a smartcontroller for my boat - I have built the electronics and written and tested a sketch for the Nano, all working totally fine. I then decided that I would  like to keep my existing Nano (Nano-A) as a development system and buy another one (Nano-B) to actually deploy. Both of these are cheap chinese clones (from different suppliers).

However I cannot upload anything to Nano-B. It seems to be basically working (LEDs flash) but not wishing to accept any sketch uploads. The COM port seems to be working OK and I have tried all the various options available in the Arduino IDE (boards, programmers etc.) without success.

So I came to the conclusion that possibly the bootloader on Nano-B needs to be re-flashed.

So I setup Nano-A as a programmer, loaded up "ArduinoISP", connected up the ISP pins and hit "burn bootloader".

It seems as if this is "nearly working". I have turned on the -v (verbose) option for avrdude and pasted the log below. It looks to me as if the IDE is invoking avrdude twice; (1) To set the Fuses etc, and (2) to upload the actual bootloader. I seems that (1) is working OK but (2) is failing.

I've been tearing my hair out for about 3 weeks with this and would be really keen to get some ideas.
Thanks in advance.

Arduino "burn bootloader" IDE Log - follows;

    Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Nano, ATmega328P"

    C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

    avrdude: Version 6.3-20190619

             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM8

             Using Programmer              : stk500v1

             Overriding Baud Rate          : 19200

             AVR Part                      : ATmega328P

             Chip Erase delay              : 9000 us

             PAGEL                         : PD7

             BS2                           : PC2

             RESET disposition             : dedicated

             RETRY pulse                   : SCK

             serial program mode           : yes

             parallel program mode         : yes

             Timeout                       : 200

             StabDelay                     : 100

             CmdexeDelay                   : 25

             SyncLoops                     : 32

             ByteDelay                     : 0

             PollIndex                     : 3

             PollValue                     : 0x53

             Memory Detail                 :

                                      Block Poll               Page                       Polled

               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff

               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff

               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : STK500

             Description     : Atmel STK500 Version 1.x firmware

             Hardware Version: 2

             Firmware Version: 1.18

             Topcard         : Unknown

             Vtarget         : 0.0 V

             Varef           : 0.0 V

             Oscillator      : Off

             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.11s

    avrdude: Device signature = 0x1e950f (probably m328p)

    avrdude: erasing chip

    avrdude: reading input file "0x3F"

    avrdude: writing lock (1 bytes):

    Writing | ################################################## | 100% 0.04s

    avrdude: 1 bytes of lock written

    avrdude: verifying lock memory against 0x3F:

    avrdude: load data lock data from input file 0x3F:

    avrdude: input file 0x3F contains 1 bytes

    avrdude: reading on-chip lock data:

    Reading | ################################################## | 100% 0.04s

    avrdude: verifying ...

    avrdude: 1 bytes of lock verified

    avrdude: reading input file "0xFD"

    avrdude: writing efuse (1 bytes):

    Writing | ################################################## | 100% 0.04s

    avrdude: 1 bytes of efuse written

    avrdude: verifying efuse memory against 0xFD:

    avrdude: load data efuse data from input file 0xFD:

    avrdude: input file 0xFD contains 1 bytes

    avrdude: reading on-chip efuse data:

    Reading | ################################################## | 100% 0.04s

    avrdude: verifying ...

    avrdude: 1 bytes of efuse verified

    avrdude: reading input file "0xDA"

    avrdude: writing hfuse (1 bytes):

    Writing | ################################################## | 100% 0.04s

    avrdude: 1 bytes of hfuse written

    avrdude: verifying hfuse memory against 0xDA:

    avrdude: load data hfuse data from input file 0xDA:

    avrdude: input file 0xDA contains 1 bytes

    avrdude: reading on-chip hfuse data:

    Reading | ################################################## | 100% 0.04s

    avrdude: verifying ...

    avrdude: 1 bytes of hfuse verified

    avrdude: reading input file "0xFF"

    avrdude: writing lfuse (1 bytes):

    Writing | ################################################## | 100% 0.04s

    avrdude: 1 bytes of lfuse written

    avrdude: verifying lfuse memory against 0xFF:

    avrdude: load data lfuse data from input file 0xFF:

    avrdude: input file 0xFF contains 1 bytes

    avrdude: reading on-chip lfuse data:

    Reading | ################################################## | 100% 0.04s

    avrdude: verifying ...

    avrdude: 1 bytes of lfuse verified

    avrdude done.  Thank you.

    C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -Uflash:w:C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:i -Ulock:w:0x0F:m

    avrdude: Version 6.3-20190619

             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM8

             Using Programmer              : stk500v1

             Overriding Baud Rate          : 19200

             AVR Part                      : ATmega328P

             Chip Erase delay              : 9000 us

             PAGEL                         : PD7

             BS2                           : PC2

             RESET disposition             : dedicated

             RETRY pulse                   : SCK

             serial program mode           : yes

             parallel program mode         : yes

             Timeout                       : 200

             StabDelay                     : 100

             CmdexeDelay                   : 25

             SyncLoops                     : 32

             ByteDelay                     : 0

             PollIndex                     : 3

             PollValue                     : 0x53

             Memory Detail                 :

                                      Block Poll               Page                       Polled

               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff

               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff

               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : STK500

             Description     : Atmel STK500 Version 1.x firmware

             Hardware Version: 2

             Firmware Version: 1.18

             Topcard         : Unknown

             Vtarget         : 0.0 V

             Varef           : 0.0 V

             Oscillator      : Off

             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.11s

    avrdude: Device signature = 0x1e950f (probably m328p)

    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed

             To disable this feature, specify the -D option.

    avrdude: erasing chip

    avrdude: reading input file "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"

    avrdude: writing flash (32768 bytes):

    Writing | ################################################## | 100% 0.00s

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_cmd(): programmer is out of sync

    avrdude: stk500_cmd(): programmer is out of sync

    avrdude: stk500_cmd(): programmer is out of sync

    avrdude: 32768 bytes of flash written

    avrdude: verifying flash memory against C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:

    avrdude: load data flash data from input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:

    avrdude: input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes

    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.00s

    avrdude: loadaddr(): (b) protocol error, expect=0x14, resp=0x3f

    avrdude: stk500_paged_load(): (a) protocol error, expect=0x14, resp=0x10

    avrdude: stk500_cmd(): protocol error

    avr_read(): error reading address 0x7e01

        read operation not supported for memory "flash"

    avrdude: failed to read all of flash memory, rc=-2

    avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xff

    avrdude done.  Thank you.

    Error while burning bootloader.

Edit ... Connections between the Arduinos. Nano A is the programmer. Nano B is the target

- Nano A    Nano B
- ISP 1  --     ISP 1 (MISO)
- ISP 2  --     ISP 2 (VCC - 5v)
- ISP 3  --     ISP 3 (SCK)
- ISP 4  --     ISP 4 (MOSI)
- ISP 6  --     ISP 6 (GND)
- D10    --     ISP 5 (RESET)

I have also now added a 60ohm resistor between RESET and +5V on Nano A
I have also tried connecting a capacitor between RESET and GND. (2uF and 100uF - I didn't have a 10uF) - but it made no difference

Further investigations.

I have tried running avrdude in "terminal" mode and can confirm that I can do all of the usual read/write operations except writing to anywhere in flash memory. This seems to be the only operation that does not work. I will now try breaking down the flash write operation into the individual SPI programming instructions to see if I can work out where it is failing. I suspect that my MCU is a "brick" but I have learned loads!

Another edit;
I have now been using the avrdude terminal mode "send" command to step throuh the individual SPI operations one at a time to write flash memory and hey! it works! (see below)
[![Windows command interpreter - avrdude session][1]][1]

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

So, if this works, why does ArduinoISP fail to load the bootloader?
I will set this up as another/new question

body:
Perhaps this isn't the answer to the bootloader issue but I went through the same thing recently, I realized a little late about what was exactly the problem, so I checked the uC on the Nano Board and it has an ATMega168 instead of the normal ATMega328p.

So if you are using ArduinoIDE you need to check the ATMega168 option while you are selecting your uC chip (as in the picture above)... Sometimes (as it happened to me, just going for the basics solve all the problems)

Hope this could help you mate

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

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


body: There is more then one bootloader in the Nano's, a new one and the old one. I had the same problem so I simply went to tools in the IDE and switched from the new  to the old, it solved my problems.


body:
I have now fixed this problem, but still do not fully understand what the original problem was.

Please see my other post on this qusetion to see what I did
[Link to other post][1]

  [1]: https://arduino.stackexchange.com/questions/79909/cant-get-burn-bootloader-working-arduino-nano


message:
Is it necessary to set a function with always_inline attribution when the function would work maybe once?

I'm going through a library for the ILI9488 running by SPI and want to copy this library in my version.

In the beginning of the source file, there's a guard for the `SPI_HAS_TRANSACTION` that if the library would run in Arduino compiler then it would use the SPI functions, otherwise it should run from another platform SPI libraries.

Library link:
[jaretburkett / ILI9488][1]

This is the part of code I have questions about:

 // If the SPI library has transaction support, these functions
 // establish settings and protect from interference from other
 // libraries.  Otherwise, they simply do nothing.
 #ifdef SPI_HAS_TRANSACTION
 static inline void spi_begin(void) __attribute__((always_inline));
 static inline void spi_begin(void) {
 #if defined (ARDUINO_ARCH_ARC32)
   // max speed!
   SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
 #else
  // max speed!
   SPI.beginTransaction(SPISettings(24000000, MSBFIRST, SPI_MODE0));
 #endif
 }
 static inline void spi_end(void) __attribute__((always_inline));
 static inline void spi_end(void) {
   SPI.endTransaction();
 }
 #else
 #define spi_begin()
 #define spi_end()
 #endif

My questions:
1. why the programmer first declare the function in source file not in header file ?
2. why to use `always_inline` attribution for a function that's is most the time used once in program file and it's not likely to be used many times during operating time ?
3. what does this define means `ARDUINO_ARCH_ARC32` and where to find it ? I searched in all files in arduino folders and didn't find it. Is it dedicated for fast boards or the usual 16MHz arduino boards ?

-------------------------------------------------------------------
Edit:

I want to add another question for the same library.

This function content:

    void ILI9488::spiwrite(uint8_t c) {

   //Serial.print("0x"); Serial.print(c, HEX); Serial.print(", ");

   if (hwSPI) {
 #if defined (__AVR__)
   #ifndef SPI_HAS_TRANSACTION
  uint8_t backupSPCR = SPCR;
  SPCR = mySPCR;
   #endif
  SPDR = c;
  while(!(SPSR & _BV(SPIF)));
   #ifndef SPI_HAS_TRANSACTION
  SPCR = backupSPCR;
   #endif
 #else
  SPI.transfer(c);
 #endif
   } else {
 #if defined(ESP8266) || defined (ARDUINO_ARCH_ARC32)
  for(uint8_t bit = 0x80; bit; bit >>= 1) {
    if(c & bit) {
  digitalWrite(_mosi, HIGH);
    } else {
  digitalWrite(_mosi, LOW);
    }
    digitalWrite(_sclk, HIGH);
    digitalWrite(_sclk, LOW);
  }
 #else
  // Fast SPI bitbang swiped from LPD8806 library
  for(uint8_t bit = 0x80; bit; bit >>= 1) {
    if(c & bit) {
  //digitalWrite(_mosi, HIGH);
  *mosiport |=  mosipinmask;
    } else {
  //digitalWrite(_mosi, LOW);
  *mosiport &= ~mosipinmask;
    }
    //digitalWrite(_sclk, HIGH);
    *clkport |=  clkpinmask;
    //digitalWrite(_sclk, LOW);
    *clkport &= ~clkpinmask;
  }
 #endif
   }
 }

what I understood from this is that the programmer wants the library to be more versatile to support AVR chips programmer by another IDE than Arduino, also supports ESP8266 and anything else should be handled by softSPI, actually pretty smart coding I guess.

My question here, is does `#if defined (__AVR__)` checks for either AVR/Arduino in general and when specifies `SPI_HAS_TRANSACTION` means Arduino SPI library specifically ? right ?

  [1]: https://github.com/jaretburkett/ILI9488

body:
1. The function is only used in the library, and not part of the "API" of that library. Kind of like a private function.

2. Both functions are both being called 14 times inside the source code of this library. But in the larger scheme of things, it doesn't add a lot. But why not add it and maybe save a few bytes, and a few clock cycles.

3. The `ARDUINO_ARCH_ARC32` is for the Arduino 101 board (Intel Curie processor).


body:
> 1. why the programmer first declare the function in source file not in header file ?

the declarion is for the inline attribute. the function should be used only in this cpp.

> 2. why to use always_inline attribution for a function that's is most the time used once in program file and it's not likely to be used many
> times during operating time ?

there are 14 occurrences of transaction start and it is called before every SPI communication commands set in the library. see [my answer about beginTransaction][1]

> 3. what does this define means ARDUINO_ARCH_ARC32 and where to find it ? I searched in all files in arduino folders and didn't find it. Is it
> dedicated for fast boards or the usual 16MHz arduino boards ?

[the architecture define][2] is generated by the builder from selected board's boards package folder name. ARC32 architecture is the Intel Arduino 101 boards package.

EDIT (answer to edited part of the question):

> My question here, is does `#if defined (__AVR__)` checks for either
> AVR/Arduino in general and when specifies SPI_HAS_TRANSACTION means
> Arduino SPI library specifically ? right ?

`__AVR__` is defined in avrlibc, the toolchain for AVR microcontrolers. Arduino uses avrlibc for AVR MCUs. It is not recommended to check `__AVR__`. The AVR family of MCU is now large with different peripherals so checking `__AVR__` should be really restricted to CPU matters.

Every Arduino 'architecture' has its own SPI library. The transactions support was added later so not all implementations of the SPI library support transactions. To declare transactions availability in SPI library Arduino defined the SPI_HAS_TRANSACTION define.

  [1]: https://arduino.stackexchange.com/questions/79728/when-is-spi-begintransaction-required/79737#79737
  [2]: https://arduino.github.io/arduino-cli/library-specification/#working-with-multiple-architectures


body:
Here I am only addressing question number 2. The others have already
complete answers.

The choice to whether a function should be inlined or not is a
speed/size trade-off. There is a cost to calling a function. On AVR, for
example, the `call` instruction takes 4 CPU cycles, and `ret` takes
another 4. Inlining the function removes this cost. On the other hand,
you end up with as many copies of the function as places where it is
inlined, and this in turn costs flash memory.

The compiler is usually smart enough to make wise decision regarding
function inlining. In this case, it is not obvious what decision it
would make on its own. On the one hand, the function is used multiple
times in the code, which makes a good case _against_ inlining it. On the
other hand, the body of the function is tiny: only setting up some
registers (the two parameters of `SPIClass::beginTransaction()`,
including the implicit `this`) and [jumping to another function][tail],
so the cost of inlining is small.

For this library, the programmer happened to have a strong opinion on
this matter, and he though inlining was really the best option. Also, he
did not thrust the compiler to make the good decision. This is the
reason why he used the gcc extension:

```c++
__attribute__((always_inline))
```

And no, it is not necessary, it is just an optimization choice.

[tail]: https://en.wikipedia.org/wiki/Tail_call


message:
Can't upload code to Arduino board on Mac

I'm using a MacBook Pro with 10.13.6, an Official Arduino Uno Board and Arduino 1.8.13 IDE.

I'm having troubles uploading code to the Arduino Board.
I have 5 ports available:
- dev/cu.-AvnetaSPPPort
- dev/cu.Bluetooth-Incoming-Port
- dev/cu.SRS-BTX300-DataInteract
- dev/cu.RS-XB41-BluetoothSeria-1
- dev/cu.UEMEGABOOM-LWACP-2

I'm not sure if any oh these ports is the correct one but I've already tried all of them and I keep getting errors like: "`avrdude: ser_open(): can't open device "/dev/cu.-AvneraSPPPort": Resource busy`"

Some weeks ago I was trying Arduino on the same computer and all went good but right now I can't get it to work, however I don't remember wich port was selected.

In the IDE the board I have selected is "Arduino Uno" and as Programmer option I have "AVRISP mkll".

Does anyone know how to solve this?

body:
List the ports again, with- and without the Arduino plugged in: open the built-in Terminal app (usually in Applications/Utilities) and type 'ls /dev/tty.*'. The difference will tell you the Arduino's device name.

"Resource Busy" generally means something else has already connected to that port.  Is a terminal-emulator program running and connected to that port? If you're using a terminal-emulator other than the one built in to the IDE, you have tell it to disconnect before you can upload to the Arduino.


body:
I finally solved the problem.

Although the Board has no information about being a clone (it only says "Uno" and was provided by the faculty so I think it is official), I was looking on the web for similar problems and found out that installing CH340 Driver was working for a lot of users.
So that was what I did and now it works like a charm.


message:
Standard deviation and variance of an array of numbers

Looking for a simple way to get the variance of an array of numbers,
that will compile with the Arduino compiler.
Something like this c#:

    static float variance(double []a, int n)
    {
        // Compute mean (average of elements)
        double sum = 0;

        for (int i = 0; i < n; i++) sum += a[i];
        double mean = (double)sum / (double)n;
        // Compute sum squared differences with mean.
        double sqDiff = 0;
        for (int i = 0; i < n; i++)
            sqDiff += (a[i] - mean) * (a[i] - mean);
        return (float)sqDiff / n;
    }

    // Driver Code
    public static void Main ()
    {
        double []arr = {10, 11, 12, 13};
        int n = arr.Length;
        Console.WriteLine( "Variance: " + variance(arr, n));
    }

---

To keep it simple, and thanks for all your help....
it is a platform with actuators in each corner to raise and lower
the platform....
Each actuator sends a feed back via modbus to the main micro processor at its request
Which is stored to a array, which is processed and then sent via modbus
Back to control (simple on/off) each actuator to keep platform in somewhat of a level position +/- a set number....
I already use the min/max  (max – min =  ) in the my code to limit a set, simple differential between the
Actuators....  I am thinking that using the variance differential would work better for the application....
Thinking it would also detect a jammed or faulty actuator faster than the max/min difference with
Less platform twisting....
(Response to Edgar), You could look at it as XYZ,…  X= position.. Y= actuator.. Z=sample rate

This is my code snip it for the max/min

example 1  —  adj\_str =  actuators position = (10,11,10,9) run level flag 1

example 2  —  adj\_str =  actuators position = (10,14,10,9) run level flag 0

```c++
void min_max()
{
    int max = adj_str[0];
    int min = adj_str[0];
    for (int i = 0; i <= 3; i++)
    {
        const int value = adj_str[i];
        if (value > max) max = value ;
        if (value < min) min = value ;
    }
    //-
    adj_str_dif = max - min;
    //-
    if (adj_str_dif < 1) level_flag = 1;
    //-
    if ((level_flag == 1)&&(adj_str_dif > 4))  // 4 = the differential
    { level_flag = 0;}
    //-
    if (level_flag == 0)           // Level Till Max or Min (re-level)
    {
        // -- Lower --
        if (adj_str_dif > 0 && (digitalRead(but_pin[1]) == LOW))
            base = (max);
        // -- Raise --
        if (adj_str_dif > 0 && (digitalRead(but_pin[2]) == LOW))
            base = (min);
    }
    //-
    if (level_flag == 1)       // Run Till full retract or full extend
    {
        // -- Lower --
        if (adj_str_dif < 1 && (digitalRead(but_pin[1]) == LOW))
            base = 1023;
        // -- Raise --
        if (adj_str_dif < 1 && (digitalRead(but_pin[2]) == LOW))
            base = 0;
    }
}
```

body:
C++ and C# (or Java) basic language constructs are very similar. Here is the Arduino version of your C# code with minimal required modifications. There is no change in the function implementation.

```

float variance(double a[], int n)
{
    // Compute mean (average of elements)
    double sum = 0;

    for (int i = 0; i < n; i++) sum += a[i];
    double mean = (double)sum / (double)n;
    // Compute sum squared differences with mean.
    double sqDiff = 0;
    for (int i = 0; i < n; i++)
        sqDiff += (a[i] - mean) * (a[i] - mean);
    return (float)sqDiff / n;
}

void setup() {
    Serial.begin(115200);
    double arr[] = {10, 11, 12, 13};
    int n = sizeof(arr) / sizeof(double);
    Serial.print( "Variance: ");
    Serial.println(variance(arr, n));
}

void loop() {

}
```


message:
Sketch skipping the OPEN Arduino inputs

Folks,
I am a beginner to Arduino. I have a sketch that tests a set of INPUTS for HIGH or LOW by using a 'for' loop. When the for loop reaches an INPUT which is kept OPEN (no wires connected to it), the for loop apparently 'skips' that INPUT and move on to the next. However, if I have +5V connected to any INPUTS within the range of the for loop, it works correctly. Any thoughts what's is happening here?

body: You should always connect something to an input to pull it high or low when no signal is present.  The simplest thing is to activate the built-in pullup resistor, which will result in the input returning HIGH when there is nothing connected.  If that's not compatible with your particular use, add a resistor from the input to ground (10k-100k is fine) so that it will return LOW when nothing else is connected.  If the input is just floating, it is susceptible to noise causing random state changes. The input impedance is very high (100 Meg) so it can pick up static and other mischief.