text:
TX Pin Stays Lit After Removing Voltage Regulator

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();
  }
}

you made a hardware change to the board ... please provide a schematic diagram for the board, not a program listing

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.

Would it be possible to bypass the regulator by bridging the Input and Output pins of the voltage regulator instead of completely desoldering it?

That's kind of a new question, but I'll just say this much: If the point is to not have any sort of current being used by the regulator, I don't think that will do it.  Take for example whatever it is using internally for a voltage reference.  This is connected somehow to the input (and in the scenario you outlined the output as well) and gnd.  If you can find a schematic for the board, I would add it to your question as jsotola mentioned.

thanks. you are right that i probably messed up the circuitry. I desoldered just the legs of the regulator (excluding the heatsink) and avoided the hidden traces.

I gather you're saying this to indicate that you achieved some success that way.

mostly to validate your answer, but yes i did bypass the regulator


text:
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:
Have I bricked my Arduino Uno? Problems with uploading to board
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.

See Have I bricked my Arduino Uno? Problems with uploading to board and report (edit into your question) what the results are of trying my various suggestions.

Using different settings in the IDE (Mega 2560 with the ATMega2560 processor) - that is the wrong processor type to select. You want a Uno.

Did your previous sketch use the watchdog timer?

Does this answer your question? "avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

@NickGammon - Arduino Uno was the first board I tried. I only tried the Mega in desparation. I haven't run a watchdog in a previous sketch - my previous sketch was driving some neopixels. I haven't read your first link yet (will do now), but I tried a 2nd arduino (a new one) and had the same problem.

@NickGammon I have been through your thorough answer linked above and have commented on my progress in the question.

It seems to be the 16U2. The https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293 post really helped diagnose this. That should be referenced on the arduino site. Thanks for the help @NickGammon

Btw: I now recognise that this is a duplicate of https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293

I was only driving leds. - how, exactly? LEDs need a current limiting resistor. I can't see how that would break the Atmega16U2 however.

They were neopixel type 'jewel' LEDs (7 per board, in a circle-ish pattern x 3 boards). I was using a capacitor between the power rails and a resistor as per the instructions. I made this video (https://youtu.be/g4enns1v0Ys) when I originally powered it incorrectly (I fixed that though).

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

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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


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

how can direct port manipulation instead of digitalWrite/Read reduce dynamic memory use?

Did you read the Arduino tutorial on the subject?

for optimizing my code

@EdgarBonet yes

So you have already read the answer to your question. If you tell us what specific part of that tutorial you found confusing (maybe add a quote), we could try to help clearing up the confusion.

less code will free flash, but not SRAM. even 100% use of flash will not create stability issues

"Heavy memory use" as you put it does NOT cause "stability issues".  What EXACTLY do you mean by "stability issues" here?  If you mean that the part doesn't run reliably and resets itself, it's more likely you have a power supply issue.  If would really help if you would edit your question and indicate exactly what you are doing, what problem you are seeing, etc.  General terms like "stability" and "heavy use" really mean nothing.

Stop using String in your code. That will cure 99% of all memory stability issues.

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

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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++;
}

I need to wait and take a certain action when a high signal comes from the sensor. For example, add one to the constant.
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?

It is unclear, what exactly your problem is. In the example the used pin is pinBlink with the value 7. You can change it with the define at the start of the sketch

The pin numbers of the TQFP package are irrelevant here. You just need to know that pin “PD0” of the ATmega328P is “digital 0” of the Arduino Uno and Arduino core library.

PD0 is Serial RX and pin 0 on Uno/Nano/Mini. why do you want use this pin?

why not use "external interrupt" peripheral?

I dont know. It seems that this is how it works, but I don't understand how it works. Which edge of the pulse. I turned on the button instead of the sensor, but I still can't understand

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
I'll repeat the overall steps here in case this URL disappears in the future:
First, you must enable pin change interrupts:

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:

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:

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:

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.

Thanks! I got something. The counter increases the number when I touch the wire coming out of the PD0 pin with my hand. But I still do not understand on what front or how it works like that

the original question used a library for pin change interrupts. how does this answer answer the question?

@Juraj I see no library being used.

the question was edited


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

It depends on the shield. If there is a protection diode then it will be safe. If there isn't then you will end up with a smoking shield. Please link to the exact shield you are using.

https://www.amazon.co.uk/gp/product/B07CQRPFFW/ref=ppx_yo_dt_b_asin_title_o05_s01?ie=UTF8&psc=1 - Here is the link for the shield I bought. Sorry I probably should have included it in my first post! Thank you for such a quick reply

I don't see any diodes on there (or anything much at all other than some capacitors). There is no protection. Get it wrong and things will die. Maybe even exploding capacitors, which is fun....

You need a DMM or something else that's polarized to identify which wire is which. An LED and resistor could be used.

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.

Hi, Thank you so much for the answer! I currently only have a RGB LED and a ton of 220Ω resistors whichI guess I could connect to the power supply (with a very messy circuit :)). Is there no way of knowing the polarity of the wires from the info on the power supply. It says its a centre-positive supply does this not mean anything ?

That only relates to the connector at the end (which you have now cut off). The wire with the stripe might be negative, but it might not. You can only tell by testing it.  For the RGB LED you need to know if it's "common anode" or "common cathode" to know how to wire it up

Oh yes I completely forgot about that!! Would connecting the RGB LED to a single double AA battery (as you can see my supplies are very very limited :) )  work to test if its a cathode or anode  ?

You would need 2 batteries and small resistor to get the polarity of the LED. 1.5V won't be enough.

Thank you so much I followed all the steps and i've got the polarity now !!


text:
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
#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.

the servo part was not working so it came together

Sort out your code indentation and you will immediately see where the problem is. Try with the autoformat in the IDE.

thanks a lot...

You say you need quick help. Why?

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


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

You mean simple code-sharing between two pieces of source code in differing languages? You'll have to find some common ground between them.

You mean copy and past the text (the enum list) between the two?  I found a great thread that talks about Python enums specifically.  But even with the slightly different syntax of all the different options in Python, I still see slight differences that will likely prevent cutting and pasting w/o modification.  Ask and I'll post that as an answer if you want.

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
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')


text:
Does anybodyknow how to program Muscle Sensors v3?
#include <Servo.h>

const int x =  200

//Naming the servosServo
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;

void setup()
{
  Serial.begin(9600);
  servo2.attach(10);
  servo3.attach(11);
  servo4.attach(3);
  servo5.attach(6);
  servo6.attach(5);
}

void loop()
{
  //Printing the EMG data
  Serial.println(analogRead(0));

  if (analogRead(5) > 200)
  {
    servo2.write(180);
    servo3.write(148);
    servo4.write(89);
    servo5.write(180);
    servo6.write(180);
  } else if (analogRead(0) < 200)
  {
    servo2.write(38);
    servo3.write(10);
    servo4.write(0);
    servo5.write(16);
    servo6.write(16);
  }

  delay(100);
}

I don't know if the problem is in the code or in the circuit.

En este web site se habla inglés. ¿Puedes editar tu pregunta y traducirla al inglés?

I'm assuming you're referring to this?

you said nothing about a problem that you are seeing ... remove all of the servo code ... reduce your code to read sensor and print the value to serial monitor


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

+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.

why are you not connecting it to the power supply ground?

The fan, together with other parts, is connected to the Arduino via a connector with a limited number of pins. GND from the Arduino is already connected there. I would save contacts if I could reuse this GND instead of also connecting GND of the power supply.

it is a good idea to avoid connecting external device grounds to the arduino ... the current that is drawn by the external device can create a voltage drop between the arduino ground and the power supply ground ... that would lower the voltage between the power pins at the arduino

Thank you @jstola. Could I just connect all consumers (no matter if they are powered by +12V of the power supply or +5V of the Arduino) to GND of the power supply (and not use the GND pin of the Arduino at all)?

yes, you definitely could do that ... anything that has a motor or a solenoid and things like LED strips should be grounded at the power supply ... sensors would be ok to ground at the arduino, unless they draw many tens of mA

"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.

To add to the above: Because wires and PCB traces are not perfect conductors, that is have resistance, there are practical differences between between different labeled "GND" points.  So it does matter where your current is traveling within the network of conductors that are labeled "GND".  High currents traveling on the ground must travel through GND conductors (traces, wires) capable of handling those currents.

Indeed, but given that the current limit of the headers is only 1A you won't be passing that much through the Arduino's ground pins...

Thank you for your comments. The fan is actually very powerful (originally intended for cooling server PCs - it draws 1A).  In this case, in consideration of your remarks, it would probably be better to connect GND of the fan directly to the power supply?

@xoric For that kind of current, yes, connect it to the power supply's ground for the lowest impedance and highest current handling.

Thank you @Majenko, your explanation was very helpful.

Another helpful remark from an experienced electrical engineer who advised me to connect GND directly to the power supply: In the picture above the fan current flows through the Arduino, which doesn't necessarily cause problems, but in any case doesn't have a positive effect either. It is also no mistake to leave the plus and minus cables of the fan close together. This minimizes electromagnetic interference that the fan may produce.


text:
How to change the update rate in TinyGPS++?
I am working with TinyGPS++ library and Arduino-nano and I want to change the update rate.
I worked before with Adafruit GPS and uses the below code for updating it.
// Set the update rate
 GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate

I have also worked with NMEAGPS.h to update every 30sec.
gps.send_P( &gpsPort, F("PMTK220,30000") );        //update 1time in 30s

So how to change the upsate rate for TinyGPS++ library? as I want to update 1 time in 30seconds.

I looked at the source code and it appears that the library checks for a new complete sentance as fast as you call the method encode.  From your question, it is not clear if this library is working too slow or too fast for your application.  But it does appear your application is in charge of any desired delay.

@st2000 I just want an update after every 30second.

If your code does not need to do anything else, I'm thinking you can simply call delay milliseconds with 30000 each time in between calling encode().  If you would like to do other things during that time, then you need to implement a state machine.

can you explain with an example?

This example TinyGPS code appears to attempt to grab new GPS data once a second.  Guessing, if you increase the loop counter on line 30 from 1000 to 30000, the delay will increase from once a second to once every 30 seconds.

@st2000 I am using TinyGPS++ library and the above code is of TinyGPS which is correct answer to my question but there is a function isUpdated in TinyGPS++ , so that function and the code you suggested are equivalent?

Is this the code for TinyGPS you are talking about? I don't see "isUpdated" anywhere in the code.

Oh, bet you are talking about his other GPS project.  But I still don't see "isUpdated" in his source code.  Ah, that's because the code is so short he just puts the code in the header file.  All that's going on is that he returns (exposes) the true / false bool value of a private variable named updated.  The method does not accept a formal parameter.  And all it can return is True or False. Doesn't look like it has anything to do w/time.  It just gets set true or false depending on the last method you happen to call.

@st2000 So should i use the code you suggested or else use isUpdated ? this code uses isUpdated

This is the example code. Not the library code. But you know that, right? It looks like "isUpdated" is used so as to only allow printing the values after the GPS module has updated the values. But that's likely way faster than what you want.  You wanted to print out data once every 30 seconds. So you have to add your own code to add a delay. A GPS module is a complex radio receiver with its own processor of which you do not have full control. On a good day it might see a dozen US (GPS), Russian (GLONASS) and other satellites. With that many satellites there will be a lot of data to print out.


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

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

Never use Serial in an interrupt. It itself relies on an interrupt, which can't happen because your interrupt is the one running.

I removed all the Serial prints and the issue is still present. Nothing in the onAlarm() method is run and the code freezes

You may be calling a function that itself calls delay(). That will also break.  Interrupts should be the absolute minimum you can get away with - ideally just set a flag then examine that flag in loop() to do your actual work. The interrupt captures the event, but doesn't do the work.

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.

Thaks, it works with both of the options you gave, but I chose the one with the bool


text:
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 ifs (and other conditional statements), the LEDs do not turn on. Here is the code for a little project I am currently working on:
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.

You should print the variable color out to the Serial monitor, to make sure, that you really received, what you send. Also you shouldn't use Serial.readString(), but Serial.readStringUntil('\n') and set your Serial Monitor to a line ending of newline only. Then try again. If that works, I will formulate an answer around that.

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:
char color[10]; // char array as buffer for reading from Serial

int number = Serial.readBytesUntil('\n', color, 10); //Read input and length
color[number] = '\0'; //Terminate the string by adding '\0' at its end

if (strcmp(color, "red") == 0) //Use strcmp(), not ==

respectively.


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

#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.

The Arduino outputs are about 25 Ω, whereas the internal pull-up is roughly 30 kΩ, so a single OUTPUT LOW can pull low many INPUT_PULLUP pins. Could you show the schematic of your keyboard + Arduino setup?

You have unbalanced parentheses on line 82.

Thanks, that must have happened while pasting here!

your for loops are messed up ......the order of keys in the columns is not all the same (if your schematic is correct) ... first column is 5 to 8 ... second column is 12 to 5 ... third column is 5 to 12 ... fourth column is 5 to 12 ... fifth column is 12 to 5 ... sixth column is a single key that does not require a for loop

stop calculating note ...  note = offset + 20 + (12-j) ... use increment instead ... note++

A few excerpts from the program:
#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.

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

Contact bounce: 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.
Pull Ups: 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 embedded processor (the
ATmega328P) comes with built in Pull Up resistors.
The Arduino IDE abstracts this feature by including a parameter it
the pinMode() function call to invoke this feature.
Rollover: 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:

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:

Thanks for your input.

This is something I want to mitigate later if necessary. However now I don't get any reaction to button presses or releases.
I am using the Arduino Pull Ups
The keyboard I bought has these diodes built-in

Sounds like you have already taken into account the basics.  Wait ... I thought you did manage to create some notes?  If you are creating no notes that means anything could be wrong including the MIDI player!  Hummm ... you should start over then.  Check all your wiring (using test equipment if you have any).  Then use a version of your code that does not change between different columns.  Then try 2 columns.  Add delays in the code after changing columns to see if that helps.

Sorry I worded that wrongly. I get no reaction to button presses, whenever I uncomment more than three columns in the loop. It does not matter which ones are commented, the other ones react properly. I tried with some delays, but I will try to add these in different places, to maybe get a different behaviour.

Re “built in Pull Up and Pull Down resistors”: The Uno has built-in pull-ups, but no pull-downs. Re “if two switch closures occur in the same row or column, they can not be uniquely detected”: It seems to me you need at least three switches to be pressed in order to create this sort of ambiguity.

No pull downs?  My bad - I corrected the answer.  If scanning by lowering the column voltages and 2 columns are electrically connected by 2 closed switches in the same row (w/no diodes) then I do not see a way to tell the difference ... oh, I see what you mean.  You don't need to tell the difference.  You just need to detect they are both closed.  Ok, I'll fix that too.


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

data will always be received faster than it can be written ... that means that you will lose data ... data compression may help .... please provide few examples of the 12 bytes of data

SDCards can be written over a 1 bit bus or 4 bit bus.  The latter is faster and, as I recall, requires a license to implement.  Also, the speed at which SDCards work varies greatly.  If your driver can take advantage of this, try a faster SDCard.  Finally, all SDCards contain a propriety controller.  So picking the right OEM for your needs may help.  (I'd go w/@jsotola recommendation 1st, try losses compression if you can.  Simple is best.)

if a typical SD card write is triggered everytime new data is received, -- It isn't. An internal 512 byte buffer is maintained by the SD library to store an entire data block. When that is filled it will flush it to the SD card in one go and get (or allocate) the next.

I suppose the question is not so much how the SD writing process itself can be sped up, but how incoming data can be preserved while the write is taking place

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.

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)

Unfortunately in this case the input data is at a constant rate, start to finish with no interruptions. There's also up to a maximum of 30 minutes of data, meaning it's a bit outside the bounds of just writing to onboard memory and dumping to the SD card at the end, hence the 2 core idea. If a full SD 512 byte write only takes 3000us, data can be written at an average speed higher than its coming in - but what to do with the data received while the SD write is occurring?

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.

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


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

step by step, how did you do it on paper? ... the program would do it the same way

The only way that I could think to make it work on paper would be to use memcpy for a one dimensional arrays and then create a two dimensional array out of it somehow. I'm not really sure how to do that, and I'm fairly new to coding and don't have a tutor or instructor to help me. I always try to do my best to find an answer myself before asking online but this one had me stumped.

when i say on paper, i mean, how would you do it if you knew nothing about programming ... what sequence of steps would you follow? ... i also do not mean write down first three numbers ... i mean baby steps, like look at array1, row1, position1.  copy content to first empty position at destination

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

Being a brand new account I can't upvote your comment yet, so I'm leaving this comment to thank you!

If you can derive a working solution from this answer, you should be able to accept this answer as a solution to your question.

Thanks @Hitachii for making the answer as correct.  If the answer works great!  If not, please leave a comment and I'll edit the answer to improve it.

Sure. If someone were to plug the guideline for the formula that you posted, into the problem that I posted, for "long array [i] = first array [y] [x]" and "long array [i] = second array [z][x], they would have to switch the placement of x and z/y in their respective line to look like "long array [i] = first array [x][y]" to follow the original sequence of the array.
Do I post my working code? This shows how green I am to this platform.

You are correct.  The 1st argument is the row and the second is the column.  I'll change my answer.


text:
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 that SPI.beginTransaction is explicitly called out.  Then they link to examples such as this and this 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?

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

It appears calling the method beginTransaction() prevents additional SPI transactions from interrupting the current transaction.  Calling endTransaction() 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, 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.

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 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 as the library gets control and endTransaction as the public library function returns control out of the library.


text:
Error sending data from ESP8266 to Uno
I am sending data from an ESP8266 to an Uno (I need to use the Uno because it has more inputs than the ESP and I need those for my project.) The ESP8266 is connected to the Uno's Serial pins 0/1 RX/TX (communicating on BAUD rate of 9600), and then I have a SoftwareSerial out from the Uno (on a BAUD rate of 57600) for debugging. Something weird is happening though. The transfer works a couple times and then I get this in the log:
--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Exception (0):
epc1=0x40239ba1 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

>>>stack>>>

ctx: sys
sp: 3fffebd0 end: 3fffffb0 offset: 0190
3fffed60:  40239b2e 3feffe00 3fffd9d0 00000050
3fffed70:  000005e0 00000000 40103501 3ffed4d0
3fffed80:  0000003c 00000000 00000022 401049e6
3fffed90:  401049c8 3fffc100 3ffef2a0 00000000
3fffeda0:  00000000 4022279f 00000020 40100198
3fffedb0:  400005e1 150cc636 00000005 4010144c
3fffedc0:  4022279f 00000030 00000010 3ffefdcc
3fffedd0:  40221007 3fff051a 00000014 00000000
3fffede0:  00000000 00000061 00000061 00000001
3fffedf0:  3ffecdb8 00000006 00000000 3fff04fc
3fffee00:  3fff051a 3ffef2a0 00000061 00000000
3fffee10:  3ffe9be8 7fffffff 50800000 00000001
3fffee20:  00000001 00004a08 00000142 401006d7

Any ideas what could be causing this? Here is the code that the Uno uses for receiving from the ESP and printing to the SoftwareSerial (Serial is the RX/TX and mySerial is the SoftwareSerial). It uses a couple helper functions I haven't included here but let me know if you need them:
void receiveFromESP() {
  if (Serial.available() > 0   ) {
    endofTransmission == 0;
    alreadyZeroed = 0 ;
    receivedChar = Serial.read();
    mySerial.print(receivedChar);
    if (receivedChar == '[' ) {
      lastNum = 0 ;
      commaNumber = 0 ;
      lastWasNum = 0 ;
    }
    if (receivedChar == '*' ) {
      lastNum = 0 ;
      commaNumber = 0 ;
      lastWasNum = 0 ;
      createArray[0] = 4;
      createArray[1] = 4;
      createArray[2] = 4;
      createArray[3] = 4;
    }
    if (receivedChar == 'A'
        || receivedChar == 'B'
        || receivedChar == 'C'
        || receivedChar == 'D'
        || receivedChar == 'E'
        || receivedChar == 'F'
        || receivedChar == 'G'
        || receivedChar == 'H'
        || receivedChar == 'I'
        || receivedChar == 'J'
        || receivedChar == ','
       ) {
      if (lastWasNum == 1) {
        createArray[commaNumber] = lastNum;
        commaNumber++;
      }
      lastWasNum = 0 ;
      createArray[commaNumber] = charToNumber(receivedChar);
      commaNumber++;
      lastNum = 0 ;
    }
    if (receivedChar == ']') {
      lastWasNum = 0 ;
      endofTransmission = 1 ;
      for (int i = 0; i < 50; i++) {
        mySerial.print(createArray[i]);
        mySerial.print(':');
      }
    }
    if (
      receivedChar == '0'
      ||  receivedChar == '1'
      ||  receivedChar == '2'
      ||  receivedChar == '3'
      ||  receivedChar == '4'
      ||  receivedChar == '5'
      ||  receivedChar == '6'
      ||  receivedChar == '7'
      ||  receivedChar == '8'
      ||  receivedChar == '9'
    ) {
      lastWasNum = 1;
      receivedCharInt = (int)receivedChar - 48;
      lastNum = lastNum * 10 + receivedCharInt;
    }
    t = millis();
  }
};

As requested, here is the full ESP code:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

#include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic

#define SERIAL_BUFFER_SIZE 256

void setup() {

  Serial.begin(9600);
  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("*WIFISETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }
  WiFiManager wifiManager;
  wifiManager.setConfigPortalTimeout(120);
  //first parameter is name of access point, second is the password
  wifiManager.autoConnect("AP-NAME", "AP-PASSWORD");
}

void loop() {
    WiFiClient client;
    HTTPClient http;
    if (http.begin(client, "[URL]")) {  // HTTP
      // start connection and send HTTP header
      http.addHeader("Content-Type", "text/plain");
      http.addHeader("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=");
      int httpCode = http.GET();

      if (httpCode == 200 ) {  // HTTP header has been sent and Server response header has been handled
        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          Serial.println(payload);
        }
      } else{
        if (httpCode > 0 ){
          //website problem
          Serial.printf("[2,1,1,1]");
        }
        if (httpCode == -1 ){
          //wifi problem
          Serial.printf("[4,1,1,1]");
          ESP.reset();
        }
      }
      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  delay(10000);
}

use stack decoder IDE plugin to decode the stack. the crash is in esp code, so Uno code is not what we need to see

Thanks, I am looking into the stack decoder IDE plugin now. To be clear, I am seeing this on the SoftwareSerial log coming out of the Uno. Can I ask how you know the crash is in esp code? Thanks

I've seen it many times. Uno doesn't produce a stack dump and the "CUT HERE ..." is a joke by esp8266 arduino developers

I am connecting just the ESP to my computer to watch the log. The ESP sends data every 30 seconds so I assume I will see the crash happening there too and will check out the stack decoder IDE plugin too. (The ESP is sending on 9600 and the SoftwareSerial is on 57600.)

"The ESP is sending on 9600 and the SoftwareSerial is on 57600." ???

I added clarification about the BAUD rates to the question text.

Post your ESP code, you are likely has a buffer overflow somewhere in your ESP. BTW, use if (receivedChar >= '0' && receivedChar <='9')  would be much simpler for your Arduino code.

I added the ESP code

Why not use a PCF8574 I2C expansion board, they work great on 3V3. If you need more inputs or outputs use the PCF8575. There are a lot of I2C expansion boards you can select from. They will also be faster and less convoluted then your existing solution.

The answer to "why not" is "I have never heard of I2C boards before." Please forgive my lack of knowledge, and my convoluted solutions, as I am new to this. I would appreciate your help in addressing the problem that I took time to lay out in this post. Thank you.

Try going to ebay and search for "I2C modules"  I got over 7,000 hits.  The exception you are getting is from the ESP8266. Eliminate the Delay() and your crashing should go away. There are lots of posts on the web telling you why not to use it. By the way you did not clearly lay out your problem you just posted a lot of code. I googled ESP8266 Exception (0): and got this as the first hit: https://www.espressif.com/sites/default/files/documentation/esp8266_reset_causes_and_common_fatal_exception_causes_en.pdf

I have reconfigured the code to use millis() instead of delay(). I am still facing the same error message. Please let me know if there are problems I could explain better in my post - I am trying to be helpful and provide all the information that I can.

How about showing a schematic. Be sure to show the ground connections as you have them connected. You might go into a little more detail about the baud rates and how do you get the serial debugger to work with softwareserial.


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

In your function, light1 needs to be lower than light2. Looks like you got those mixed up in the call.

You wrote:

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

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


text:
DHTNEW library not working with ATTiny85 + DHT11
I tried to make a simple project with Attiny85 chip and DHT11 sensor. After 2 days of struggle, made it finally work, but not quite as expected. TinyDHT library does work, while DHTNEW does not.
I wonder,

what can be changed to make any of the libraries work at lower clock rate?
how to make DHTNew work?

My results so far:
with TinyDHT:

@ 16 MHz works nominally, showing valid T/H values (if I breathe on the sensor, it shows 95-99% humidity)
@ 8 MHz, shows nothing (either nan, or zeros)
@ 1 MHz, shows temp/hum as 5, 5 (or 50, 50, can't tell)

with DHTNEW:

@ 16 MHz returns SENSOR_NOT_READY
@ 16 MHz with mySensor.setDisableIRQ(true); -> WAITING_FOR_READ at first, then nothing (nan or 0)
@ 8 MHz WAITING_FOR_READ at first, then TIMEOUT_C
@ 8 MHz with setDisableIRQ -> always TIMEOUT_C
@ 1 MHz always TIMEOUT_A

Here's the setup on photo and as a scheme. Arduino UNO works as a programmator for Attiny chip, as shown in this tutorial. After I upload the code to Attiny85, the chip starts working normally, and there's no need to disconnect the Arduino board. (For actual work, I disconnect it, connect 5V power, and it works the same way.)
Settings in the IDE:

Board: Attiny25/45/85
Processor: Attiny85
Clock: Internal from 1 to 16 MHz
Programmer: Arduino as ISP

How I test this:

change clock frequency
run Tools -> Burn bootloader
run Sketch -> Upload
wait till upload ends (RX/TX diodes stop blinking)
the LED on breadboard blinks me the numbers

Code for TinyDHT
Code for DHTNEW

Reading the measurements requires somewhat accurate timings (i.e. millis() needs to work). Did you check that a blink sketch blinks at the expected frequency when you change your clock settings?

@Mat It blinks somewhat correctly, but I need to check that to tell more exactly. It may be some % off, indeed.


text:
74HC595 to 4 Digit 7 Segment using SevSegShift Library
I have a question regarding the use of SevSegShift 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.

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

See the comment of the last statement. It says, don't use blocking code in the for loop e.g. delay() and one line above you use delay(). Hmmm, possibly ?! The shift register must be update very fast i guess.

@PeterPaulKiefer Thank you, that was an oversight on my part. Took out the delay() and still the same output :(

Did you connect +5V and Ground to the breadboard? Your schematic doesn’t show them.

@StarCat Yep! I'm sorry I forgot that part. Will edit it :D

OK, for me this was the most obvious possibillity of failure. But there are more. A brightness of 10 seems very low to me (max is 100). If you have COMMON_ANODE LED-Bars but you have configured COMMON_CATHODEs this would invert the brightness. Dark is Bright and Bright is Dark. Take this together and i might result in your observations. And probably the wiring is not correct. If you add a picture to the post we could check it. Btw. pin 12 can not provide PWM output (no ~ symbol), so it can not be used to regulate the brighness of the connected digit.

@PeterPaulKiefer That actually made a lot of sense! I changed it to COMMON_ANODE and set brightness to 100 so that I don't need to change pin 12. That helped a lot! The only problem now is that the display is showing in reverse and the decimal point is showing even if I set the disableDecPoint to true but I was able to fix that by reversing the digit pins and also setting disableDecPoint to false. I will put the updated code and also some picture output :D

swap the digit selection pins

Please forget the last sentence in my last comment. I've looked intio the lib code and they do not use PWM to control the brightness. Instead they use custom method the controll the brightness over the on and of time of an LED.

@PeterPaulKiefer, PWM wit 595?

@Juraj. If you controll the backpath (digit selector pins) it should work. Of cause the shift register can not be used for PWM ;-).  And yes, their custom method is far more clever then PWM. I have to admit.

@PeterPaulKiefer, PWM on digit selection pins? it makes even more less sense. only one digit can be lit at time. the redraw is fast lighting up digits one by one. the time between the redraws determines the brightness of the display

@Juraj As I wrote it is not a clever alternative but it depends an the speed of the PWM if it is possible or not. I admit, the idea of PWM is not the best one I had, and also it would be better if I try to think before I write. ;-)

hello i made this but i have question how we can turn on dots??

this program and wiring god but i cant find a way to turn on decimal point with numbers

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:

Turns out my 7-segment is COMMON_ANODE so I changed my hardwareConfig
Set brightness to 100
(At this point, it shows the number in reverse but with a decimal point in each digit)
Set disableDecPoint to false
(At this point, the display is showing but in reverse but no more decimal point)

To fix this, I set the digitPins[] in reverse and it now shows the proper format

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. (The link is to the shop I got it from)