text:
Arduino Nano 33 BLE getting the current time using RTC
I have a an arduino NANO 33 BLE and I'm trying to get the current time and date. Based on the documentation, the arduino has nRF52840 microcontroller which comes with a 24 RTC timer It is listed in the nordic documentation as well. However, I'm not sure exactly how to use it to get the current time; Based on the MbedOS documentation for Time I wrote out the code to print out the current time and date in conjunction with reading the data:
#include "mbed.h"
#include <Time.h>
#include <RTClib.h>

time_t rawtime;
struct tm *info;

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

//resistor val = 100K

void loop() {
  rawtime = time(NULL);
  time(&rawtime);
  info = localtime(&rawtime);
  int val = analogRead(A1);
  Serial.print(val);
  Serial.print('-');
  Serial.print(asctime(info) );
  delay(5);
  }

However it just prints out this:

XX-Thu Jan 1  00:08:30 1970

Where the XX is the correct sensor data. Why is the time not the current time but the beginning unix epoch ? This code was run in the Desktop Arduino IDE in Win10

if you buy a wall clock, put a battery into it and don't do anything else, then do you expect the correct time to be shown?

@jsotola doesnt the   rawtime = time(NULL); time(&rawtime);  acts like setting the time ? Or am I misinterpreting that line of code ?

where would the current time/date come from? ... https://duckduckgo.com/?q=jan+1st+1970&ia=web

I was going to write something more elaborate, but in short the RTC in the NRF52840 is not a "clock" so much as an asynchronous timer/counter. As in, you can run it from a clock source that isn't related to the system clock that times your code and it may (or may not) continue to count when you're in a sleep mode. So, you may be able to use this async. timer/counter as a building block in constructing what amounts to an approximation of a real-time clock (like a DS3231). That you might use it that way isn't assumed by Nordic, or mbed, or Arduino, or libc/time.h, and RTCLib.h concerns itself with accessing specific models external realtime clock chips with no direct connection to time.h. So there's nothing to support your specific use case in each of these things.
So you can try to build a real-time clock functionality out of it. But if you're like most Arduino users you're probably better off getting a DS3231 or something like it. You will probably end up with more accurate time keeping and battery backup, etc than you would if you build this functionality yourself out of the NRF52's counter.
If you have a need or strong desire to use <time.h>, that can usually be done by completing its implementation in some implementation specific documented way. Basically you'd retrieve the time fields out of something like the DS3231 an then use that to set what amounts to a time_t variable that backs time() and then to call regularly call some kind of time advance function from an interrupt routine based on the square wave output from the DS3231 (or whatever). If you really want to make use of the async. counter yourself, all of that applies there as well.


text:
Forget WiFi ESP32
How can you make ESP32 forget all the Wi-Fi networks it was connected to? Or at least forget the one to which the board is currently connected?

WiFi.disconnect()

It only disables Wi-Fi, but when the ESP32 is turned on, it connects again automatically

connect to another network

https://docs.espressif.com/projects/arduino-esp32/en/latest/api/wifi.html#disconnect

or erase the flash memory

Thank you! Use WiFi.disconnect(false, true)

source: Stack Exchange

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

sort: votes


text:
Error resolving FQBN (Fully Qualified Board Name)
In Arduino IDE, I get this error "Error resolving FQBN: getting", when compiling a sketch. Can anyone help me get around this problem?
I am using the Arduino IDE. I have installed the M5Stack official 2.0.5-1.0 boards in Board Manager and the STAMP-PICO 0.0.2 library in Library Manager.
I get the following Compile error with ALL sketches, even the STAMP-PICO Basics IO example sketch.
"Error resolving FQBN: getting Error compiling for board STAMP-PICO."
Strangely ... in Arduino IDE v2.0.3, on the same computer using the same libraries and boards, the sketch compiles ok.
Sounds like something specific to Arduino IDE v1

@MG1 What board exactly do you have?

OK - I resolved the issue, myself.
The Boards Manager installations became confused, probably because I was using both Arduino 1.8.19 and Arduino IDE 2.0.3 on the same computer.
Somehow, the folder ~/Library/Arduino15/packages/m5stack/hardware/esp32/ contained more than one version of the esp32 board libraries, v2.0.5 as well as v2.0.5-1.0 and c2.0.5+1.0.
My fix involved uninstalling the M5 esp32 board library altogether and making sure that all sub-folder versions had been deleted too. Then, reinstalling the latest board version and restarting the Arduino IDE app.

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


text:
Is it possible to sample a signal with a sample frequency of 48kHz?
I want to have a filter with a 48kHz sample frequency, is that possible using the esp32?
Here is a part of the code i developed using the arduino IDE:
void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(115200);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);

  /*
     The following function allows you to obtain more information
     related to the state of network and IoT Cloud connection and errors
     the higher number the more granular information you’ll get.
     The default is 0 (only errors).
     Maximum is 4
  */
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
}

void loop() {
  ArduinoCloud.update();
  Pot = (float) analogRead(PinADC_sensor_35) * 3.3 / 4096;

  float t = micros()/1.0e6;
  float xn = sin(2*pi*200*t);

  delayMicroseconds(21);
  //delay(0.020833);

  float H1yn = (1/1)*(H1yn1*(-0.2025) + 0.6*xn + 0*xn1);
  xn1 =xn;
  H1yn1 = H1yn;

  float H2yn = (1/1)*(H2yn1*(-0.2025) + 1*H1yn + 0.3*xn2 );
  xn2 = H1yn;
  H2yn1 = H2yn;

  float H4yn = (1/1)*(H4yn1*(-0.9097) + 1*H2yn - 1*xn4);
  xn4 = H2yn;

  SinalQuadrado = SinalQuadrado + H4yn*H4yn;
  k++;

Does the delayMicroseconds(21) have any effect? I stop the program for 21 mili seconds (48kHz) to sample a signal.

You need to take into account all the other things going on in the loop as well, not just the delay. Your sampling frequency will probably be nowhere near 48kHz.

@StarCat How can i certify that i have a sampling frequency of 48kHz?

@jsotola Perhaps that's a bad computation in my part. But even if i use the delay function with 21milliseconds how can i be assured the signal will be sampled at 48kHz?

21us is the correct value for 48kHz, but the rest of your code also takes time to execute. I would guess that the Arduino cloud update is taking significantly longer (since network action mostly takes some time to execute). Probably you need interrupts to do this, though I'm not sure how this works with an ESP32


text:
Reading from Analog Mic and Transmitting over BLE (Nano 33 BLE)
I'm trying to read from an analog mic with a sampling frequency of 10 kHz and transmitting the data over BLE on Arduino Nano 33 BLE Sense Rev 2. The MCU reaches that sampling rate with no problem but once I activate BLE it starts having a delay too big to keep up with the 10kHz
Is it possible doing something like this on Arduino, or will I have to try with a different chip?


text:
Why can't I write to SD, while the ReadWrite example works?
I've created a sensor that measures the color of the external cerebrospinal fluid drain using TCS3200. I'm able to get readings, but I'm unable to save them on the SD card, yet I'm very much able to save using the ReadWrite example. This led me to believe the issue isn't hardware-related. I'm possibly missing a very obvious thing(Just like I've overlooked the division by zero and lost roughly 6 hours figuring it out).
I'm using an Arduino Micro clone. TCS3200 and a microSD module.
Here's my code:
    #include <SPI.h>
#include <SD.h>

// Define pins connected to the TCS3200 sensor
#define S0 2
#define S1 3
#define S2 4
#define S3 5
#define sensorOut 6

// Calibration values for clear CSF readings (TO-DO: Calibrate these)
int baselineClearPeriodCount = 1; // Initialize to 1 to prevent division by zero (oops.)
int baselineRedPeriodCount = 1;
int baselineGreenPeriodCount = 1;
int baselineBluePeriodCount = 1;

// Target count to be achieved within the dynamic time adjustment
const int targetCount = 360;

// Timeout setting for the pulseIn() function (microseconds)
const int pulseTimeout = 2000;

// Specifies the chip select pin for the SD card module
const int chipSelect = 10;

// Variables for interacting with the SD card
File sensorDataFile;
String dataString = "";

// Function Prototypes
void setupSensorPins();
void readColor(int &colorCount, int S2State, int S3State);

void setup() {
  // Initialize serial communication
  Serial.begin(9600);
  // Give time for the serial monitor to open
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Serial communication initialized.");

  // Set up the sensor pins
  setupSensorPins();
  Serial.println("Sensor pins setup completed.");

  // Initialize SD card
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("SD card initialization failed!");
    while (1);
  }
  Serial.println("Initialization done.");

}

void loop() {
  // Debug statement to indicate start of loop
  Serial.println("Starting loop...");

  // Variables to store counts for each color and clear reading
  int redPeriodCount = 0;
  int greenPeriodCount = 0;
  int bluePeriodCount = 0;
  int clearPeriodCount = 0;

  // Read Red, Green, Blue, and Clear colors
  readColor(redPeriodCount, LOW, LOW);
  readColor(greenPeriodCount, HIGH, HIGH);
  readColor(bluePeriodCount, LOW, HIGH);
  readColor(clearPeriodCount, HIGH, LOW);

  // Calculate and log data
  int turbidityReductionPercent = (baselineClearPeriodCount - clearPeriodCount) * 100 / baselineClearPeriodCount;
  int redChangePercent = (redPeriodCount - baselineRedPeriodCount) * 100 / baselineRedPeriodCount;
  int greenChangePercent = (greenPeriodCount - baselineGreenPeriodCount) * 100 / baselineGreenPeriodCount;
  int blueChangePercent = (bluePeriodCount - baselineBluePeriodCount) * 100 / baselineBluePeriodCount;

  // Build the data string
  dataString  = String(redPeriodCount) + "," + String(greenPeriodCount) + "," +
                String(bluePeriodCount) + "," + String(clearPeriodCount) + "," +
                String(turbidityReductionPercent) + "," +
                String(redChangePercent) + "," + String(greenChangePercent) + "," +
                String(blueChangePercent) + "%\n";

  // Debug statement to print the data string
  Serial.println("Data String: " + dataString);

  // Log data to SD card
  sensorDataFile = SD.open("sensordata.txt", FILE_WRITE);

  if (sensorDataFile) {
    sensorDataFile.println(dataString);
    sensorDataFile.close();
    Serial.println("Text file write complete");
  }
  else {
    // if the file didn't open, print an error:
    Serial.println("Error opening text file.");
  }

  // Short delay before the next loop iteration
  delay(1000);
}

void setupSensorPins() {
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);
}

void readColor(int &colorCount, int S2State, int S3State) {
  // Setting frequency scaling to 20%
  digitalWrite(S0, HIGH);
  digitalWrite(S1, LOW);

  digitalWrite(S2, S2State);
  digitalWrite(S3, S3State);
  unsigned long startTime = millis();
  colorCount = 0;
  int dynamicMeasurementTime = 50;
  unsigned long currentTime = millis();

  while (currentTime - startTime < dynamicMeasurementTime) {
    int pulseWidth = pulseIn(sensorOut, LOW, pulseTimeout);
    if (pulseWidth > 0) {
      colorCount++;
      if (colorCount >= targetCount) {
        dynamicMeasurementTime = currentTime - startTime;
        break;
      }
    }
    currentTime = millis();
  }

  // Debug statement to print color count
  //Serial.print("Color count (S2: ");
  //Serial.print(S2State);
  //Serial.print(", S3: ");
  //Serial.println(S3State);
  //Serial.print("): ");
  //Serial.println(colorCount);
}

The monitor reads:
Starting loop...
Data String: 0,0,0,1,0,-100,-100,-100%
Error opening text file.

I've also tried manually adding an empty txt file which also didn't work.

Try shortening the name of the file to 8 or less characters left of the dot.

That fixed it... I suppose that's what "short 8.3 names" mean. I feel like it should be more explicitly said on the Arduino documentation. Thank you!

can it be more explicit than it is? https://www.arduino.cc/reference/en/libraries/sd/#usage

@Juraj If you know what "short 8.3 names" mean, of course. But considering that many people using Arduino are either hobbyists or people from other departments, it might be overlooked. I was even surprised to learn that it is limited as such, with a device so capable...

Because "short 8.3 names" means less than 8 characters on file names and you cannot make file names longer than 8 characters in order to fit that naming convention. Thanks @Delta_G


text:
Emulating Arduino Uno with QEMU: interrupts do not work
So I wrote this code for Arduino Uno:
// file qemu.ino
void setup() {
    Serial.begin(9600);
}

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

And then compiled and uploaded it to the real microcontoller. Everything works as it should, printing milliseconds elapsed. The millis() value updates regularly.
Then, I tried to execute the same code in QEMU by using these commands:
arduino-cli compile -b arduino:avr:uno -e .
qemu-system-avr -M uno -nographic -bios build/arduino.avr.uno/qemu.ino.with_bootloader.bin

Serial prints work, but millis() stays at 0 all the time. So just a bunch of 0s getting printed.
Further investigation of Arduino source code revealed the problem: millis() reads the variable timer0_millis, which gets updated in ISR(TIMER0_OVF_vect), that is, in the 16th interrupt vector. The init() function also makes sure that this interrupt is enabled.
Also because millis() never gets updated, delay() and Serial.read() hang forever.
So the conclusion is: interrupts work on a real device, but for some reason not on QEMU.
Maybe I am missing something?

The documentation of qemu-system-avr says “[...] ATmega controller, which model is limited to USART & 16-bit timer devices”. Not sure I understand that sentence. It could mean the emulator does not support the 8-bit Timer 0, which is used by the Arduino timing functions like millis().

you came to the correct conclusion

The documentation of qemu-system-avr says:

[...] ATmega controller, which model is limited to USART & 16-bit timer devices, enough to run FreeRTOS based applications [...]

It means the emulator does not support the 8-bit timer 0, which is used by the Arduino timing functions like millis().

That's weird since Arduino is almost unusable without timer0.

@AlexanderPerechnev You did not read the linked documentation, did you? :-D It clearly states that this suffices to run FreeRTOS (added to the answer now). Some Arduinos are apparently used outside the Arduino firmware environment. Not everyone is happy with the limits of it.

No, I didn't. I opened this topic just because it's interesting that Qemu can emulate AVR-based devices as well.


text:
Programmer vs target clock frequency
I have a 16u2 programming a 1284P for a custom board I am building. The 16u2 converts USB to USART for programming the 1284P, however the 16u2 has a maximum frequency of 16MHZ while the 1284P has a maximum frequency of 20MHZ. I am aiming to use the 20MHZ crystal with the 1284P.
Does the target device(1284P) need to have the same clocking frequency as the programmer(16u2)?

no, it does not

@jsotola You have noticed the "Answer" box on these pages, have you not?

There are multiple ways of programming a 1284P board, such as:

Using the bootloader, via serial input
Using ICSP (via the SPI pins)
High-voltage programming

The bootloader is via a specific baud rate, which is not tied to the processor clock speed. The other two are self clocked so you could probably program them at one byte per second (although you wouldn't want to).

Does the target device(1284P) need to have the same clocking frequency as the programmer(16u2)?

No, it does not.


text:
Does an ISR pause PWM?
I have a Nano producing a PWM output from one of its pins. This PWM signal cannot stop as it drives a filament for a VFD display(if it stops, nothing shows). However, I need to capture the pulses from an external clock in order to shift display data in accordance with the multiplexing timer using an ISR sequence.
However, does an interrupt temporarily pause PWM while the ISR is being executed?

No, it doesn't.
An interrupt request interrupts the processor inside the
microcontroller, which stops whatever it is doing in order to run the
interrupt service routine (or ISR). The PWM is generated by a timer,
which is a peripheral and does not care about what the processor is doing.


text:
can differential drive work together with ultrasonic sensor?
I've written a sketch to drive a differential drive system, specifically - to be able to drive strait. This does work.
So I am trying to add the ability to stop when the path is blocked using US sensor directed towards the front of the "car". I manage to get correct readings, but my "car" cannot move strait anymore.
I tried using the ping_timer() functionality of NewPing library, but it did not solve the problem. When the ultrasonic code is commented out, my "car" can go strait.
My algorithm for strait driving is essentially to compare the pulses from two rotary encoders fitted to the wheels, and if one exceeds the other by more than one pulse, shut down the relevant motor and turn on the other motor (if it wasn't on already) so the slower motor has a chance to keep-up.
I wonder if there is a problem in my code that I cannot find, I will be very thankful for anyone who can review my sketch:
#include <Arduino.h>
// #include <Servo.h>
#include <TimedAction.h>
#include <NewPing.h>

#define RIGHT_MOTOR_ON (0 - int(pulseCountRight <= pulseCountLeft + 1))
#define LEFT_MOTOR_ON (0 - int(pulseCountLeft <= pulseCountRight + 1))

const int EN_RIGHT = 6;
const int IN1_RIGHT = 7;
const int IN2_RIGHT = 8;
const int ENCODER_RIGHT = 2;

const int EN_LEFT = 5;
const int IN1_LEFT = 10;
const int IN2_LEFT = 11;
const int ENCODER_LEFT = 3;

const int SPEED = 100;

const int BW_TRUE = -1;
const int BW_FALSE = 0;

// const int SERVO_PIN = 9;
// const int SERVO_MAX_RIGHT = 0;
// const int SERVO_MAX_LEFT = 125;
const int SERVO_SWEEP_DELAY = 150;
// const int SERVO_TURN_RIGHT = -25;
// const int SERVO_TURN_LEFT = 25;

const int ULTRASONIC_TOO_CLOSE = 20;
// Timeout is the maximum time it would take sound to do a roundtrip with length of "ULTRASONIC_TOO_CLOSE".
// Formula is: DIST(cm) x TIME(us per cm).
const int ULTRASONIC_TIMEOUT = ULTRASONIC_TOO_CLOSE * US_ROUNDTRIP_CM;
const int ULTRASONIC_TRIG_PIN = 13;
const int ULTRASONIC_ECHO_PIN = 12;

unsigned int pulseCountRight = 0;
unsigned int pulseCountLeft = 0;

int movingStrait = BW_TRUE;
int stopping = BW_TRUE;

double distance = 0.0;

void pingTimer();
void checkTimer();

NewPing sonar(ULTRASONIC_TRIG_PIN, ULTRASONIC_ECHO_PIN, 400);

TimedAction pingTimerAction(SERVO_SWEEP_DELAY, pingTimer);

// Servo myServo;

void countPulse(unsigned int &counter) {
  ++counter;

  char c[1000];
  sprintf(c, "Pulses (right,left): %d,%d, Motor on (right,left): %d,%d", pulseCountRight, pulseCountLeft, RIGHT_MOTOR_ON, LEFT_MOTOR_ON);
  Serial.println(c);

  analogWrite(EN_RIGHT, SPEED & (RIGHT_MOTOR_ON | ~movingStrait) & ~stopping);
  analogWrite(EN_LEFT, SPEED & (LEFT_MOTOR_ON | ~movingStrait) & ~stopping);
}

void forward() {
  movingStrait = BW_TRUE;
  stopping = BW_FALSE;
  pulseCountRight = 0;
  pulseCountLeft = 0;

  digitalWrite(IN1_RIGHT, LOW);
  digitalWrite(IN2_RIGHT, HIGH);

  digitalWrite(IN1_LEFT, LOW);
  digitalWrite(IN2_LEFT, HIGH);

  analogWrite(EN_RIGHT, SPEED);
  analogWrite(EN_LEFT, SPEED);
}

void backwards() {
  movingStrait = BW_TRUE;
  stopping = BW_FALSE;
  pulseCountRight = 0;
  pulseCountLeft = 0;

  digitalWrite(IN1_RIGHT, HIGH);
  digitalWrite(IN2_RIGHT, LOW);

  digitalWrite(IN1_LEFT, HIGH);
  digitalWrite(IN2_LEFT, LOW);

  analogWrite(EN_RIGHT, SPEED);
  analogWrite(EN_LEFT, SPEED);
}

void right() {
  movingStrait = BW_FALSE;
  stopping = BW_FALSE;

  digitalWrite(IN1_RIGHT, LOW);
  digitalWrite(IN2_RIGHT, HIGH);

  digitalWrite(IN1_LEFT, HIGH);
  digitalWrite(IN2_LEFT, LOW);

  analogWrite(EN_RIGHT, SPEED);
  analogWrite(EN_LEFT, SPEED);
}

void left() {
  movingStrait = BW_FALSE;
  stopping = BW_FALSE;

  digitalWrite(IN1_RIGHT, HIGH);
  digitalWrite(IN2_RIGHT, LOW);

  digitalWrite(IN1_LEFT, LOW);
  digitalWrite(IN2_LEFT, HIGH);

  analogWrite(EN_RIGHT, SPEED);
  analogWrite(EN_LEFT, SPEED);
}

void stop() {
  movingStrait = BW_FALSE;
  stopping = BW_TRUE;

  digitalWrite(IN1_RIGHT, LOW);
  digitalWrite(IN2_RIGHT, LOW);

  digitalWrite(IN1_LEFT, LOW);
  digitalWrite(IN2_LEFT, LOW);
}

void setup() {
  Serial.begin(9600);
  Serial.println("DifferentialDrive2");

  pinMode(EN_RIGHT, OUTPUT);
  pinMode(EN_LEFT, OUTPUT);
  pinMode(IN1_RIGHT, OUTPUT);
  pinMode(IN2_RIGHT, OUTPUT);
  pinMode(IN1_LEFT, OUTPUT);
  pinMode(IN2_LEFT, OUTPUT);

  pinMode(ENCODER_RIGHT, INPUT_PULLUP);
  pinMode(ENCODER_LEFT, INPUT_PULLUP);

  // pinMode(SERVO_PIN, OUTPUT);

  pinMode(ULTRASONIC_TRIG_PIN, OUTPUT);
  pinMode(ULTRASONIC_ECHO_PIN, INPUT);

  attachInterrupt(digitalPinToInterrupt(ENCODER_RIGHT), [] { countPulse(pulseCountRight); }, CHANGE);
  attachInterrupt(digitalPinToInterrupt(ENCODER_LEFT), [] { countPulse(pulseCountLeft); }, CHANGE);

  digitalWrite(IN1_RIGHT, LOW);
  digitalWrite(IN2_RIGHT, HIGH);

  digitalWrite(IN1_LEFT, LOW);
  digitalWrite(IN2_LEFT, HIGH);

  analogWrite(EN_RIGHT, SPEED);
  analogWrite(EN_LEFT, SPEED);

  // myServo.attach(SERVO_PIN);
  // myServo.write((SERVO_MAX_RIGHT + SERVO_MAX_LEFT) / 2);

  forward();
}

unsigned long start_time = 0;

void pingTimer() {
  sonar.timer_stop();
  start_time = micros();
  sonar.ping_timer(checkTimer);
  // NewPing::timer_us(ULTRASONIC_TIMEOUT * 4, checkTimer);
}

void checkTimer() {
  // static int angle = SERVO_MAX_RIGHT;
  // static int direction = SERVO_TURN_LEFT;
  if (micros() - ULTRASONIC_TIMEOUT >= start_time && sonar.check_timer()) {
    distance = ((float) sonar.ping_result / (float) US_ROUNDTRIP_CM) / 2.0;
    if (distance < ULTRASONIC_TOO_CLOSE) {
      stop();
      Serial.println("stoppeing");
    }
  }
  // sonar.timer_stop();
}

void loop() {
  pingTimerAction.check();
  if (distance == 0 || distance > ULTRASONIC_TOO_CLOSE) {
    // forward();
  }
}

Here is a printout of the pulse counts and the status of the motors for a run:
DifferentialDrive2
Pulses (right,left): 1,0, Motor on (right,left): -1,-1
Pulses (right,left): 1,1, Motor on (right,left): -1,-1
Pulses (right,left): 2,1, Motor on (right,left): -1,-1
Pulses (right,left): 3,1, Motor on (right,left): 0,-1
Pulses (right,left): 4,1, Motor on (right,left): 0,-1
Pulses (right,left): 5,1, Motor on (right,left): 0,-1
Pulses (right,left): 6,1, Motor on (right,left): 0,-1
Pulses (right,left): 7,1, Motor on (right,left): 0,-1
Pulses (right,left): 8,1, Motor on (right,left): 0,-1
Pulses (right,left): 9,1, Motor on (right,left): 0,-1
Pulses (right,left): 9,2, Motor on (right,left): 0,-1
Pulses (right,left): 9,3, Motor on (right,left): 0,-1
Pulses (right,left): 9,4, Motor on (right,left): 0,-1
Pulses (right,left): 9,5, Motor on (right,left): 0,-1

Pulses (right,left): 9,6, Motor on (right,left): 0,-1
Pulses (right,left): 9,7, Motor on (right,left): 0,-1
Pulses (right,left): 9,8, Motor on (right,left): -1,-1
Pulses (right,left): 9,9, Motor on (right,left): -1,-1
Pulses (right,left): 10,9, Motor on (right,left): -1,-1
Pulses (right,left): 11,9, Motor on (right,left): 0,-1
Pulses (right,left): 12,9, Motor on (right,left): 0,-1
Pulses (right,left): 13,9, Motor on (right,left): 0,-1
Pulses (right,left): 14,9, Motor on (right,left): 0,-1
Pulses (right,left): 15,9, Motor on (right,left): 0,-1
Pulses (right,left): 16,9, Motor on (right,left): 0,-1
Pulses (right,left): 17,9, Motor on (right,left): 0,-1
Pulses (right,left): 17,10, Motor on (right,left): 0,-1
Pulses (right,left): 17,11, Motor on (right,left): 0,-1
Pulses (right,left): 17,12, Motor on (right,left): 0,-1
Pulses (right,left): 17,13, Motor on (right,left): 0,-1
Pulses (right,left): 17,14, Motor on (right,left): 0,-1
Pulses (right,left): 17,15, Motor on (right,left): 0,-1
Pulses (right,left): 17,16, Motor on (right,left): -1,-1
Pulses (right,left): 17,17, Motor on (right,left): -1,-1
Pulses (right,left): 18,17, Motor on (right,left): -1,-1
Pulses (right,left): 19,17, Motor on (right,left): 0,-1
Pulses (right,left): 20,17, Motor on (right,left): 0,-1
Pulses (right,left): 21,17, Motor on (right,left): 0,-1
Pulses (right,left): 22,17, Motor on (right,left): 0,-1
Pulses (right,left): 23,17, Motor on (right,left): 0,-1
Pulses (right,left): 24,17, Motor on (right,left): 0,-1
Pulses (right,left): 24,18, Motor on (right,left): 0,-1
Pulses (right,left): 24,19, Motor on (right,left): 0,-1
Pulses (right,left): 24,20, Motor on (right,left): 0,-1

What bugs me about this output is that I am expecting the slower motor not to open such large gaps, and I also know that in reality it did not open such large gaps. I suspect some pulses don't get counted for some reason, perhaps I am putting too much work on the micro-controller.
If the problem is not in my code, I wonder if this problem can be solved on a single Arduino device and I just have a weak algorithm, or perhaps it requires a separate device for the ultrasonic and a separate device for the differential drive.
Thanks in advance for any helpers.
PS. I am using this motor shield: https://osoyoo.com/2020/08/06/osoyoo-motor-shield/

The NewPing library uses a hardware timer for doing the background measurement, so does analogWrite. I suspect that there is a conflict for a hardware timer in your code. I currently cannot verify, but you should make sure, that these don't want to use the same timer

Thanks, chrisl. indeed I am using pins 2 and 3 for rotary encoders, and I see that pin 3 belongs to Timer2 which is used by NewPing for UNO boards. I understand that only pins 2 and 3 are usable for interrupts on UNO, so I guess I cannot use the ping_timer function and also attachIntterup on pin 3 on the same board?

Thanks to @chrisl, here is the answer:
The NewPing library uses Timer2 on UNO, which means pin 3 (and 11) is not available for use. I have been using pin 3 for interrupts from a rotary encoder, which is probably the reason for the sluggish performance.
The bad news are there are only two interrupt pins on UNO - 2 and 3, so if I want to attach two rotary encoders to my two drive wheels, I cannot use interrupts to count the pulses. There may be a workaround, I couldn't think of one, but I think IR proximity sensors may be a better choice than my ultrasonic sensor because judging from code examples they are neither blocking nor do they need timers, but I didn't really dive deep into them yet so I may be wrong on this.

If you use the PinChangeInterrupt you can connect the rotary encoders do other pins. I think there are libraries available to handle that kind of interrupt easily. You can search for "Arduino library pin change interrupt". Though changing the design of your project in favor of IR proximity sensors is also a way of handling this.

Thanks! this is very useful. I didn't know this.

authors: יחזקאל הירשהורן


text:
How to connect Nodemcu ESP-32s and GSM SIM800L
The code that I use:
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(16, 17);

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

but if I run it, the GSM doesn't seem to respond or it show me different characters as its output "???".
Connection:

SIM800L
Nodemcu ESP-32s

RX
GIOP17

TX
GIOP16

the expected output:

the output I have:

how do you know that the GSM module is not responding? ... please edit your post with a description of what you expected to happen and what you observed

why don't you use hardware serial, instead of software serial?

The by default baud rate of sim800 is 115200 try using this baud rate if it works if it works then try changing the baudrate using AT command AT+IPR=<baudrate> and then use AT&W to store the baud rate


text:
Why is the value of this uint32_t always 0?
Setting up a method to calculate ID3 frame sizes, but the variable frsz always returns 0. I need to pass this variable back to another method so the program can loop through the ID3 frames.
void frameInfo(File track, char frame[4], uint32_t ltwo[4], int32_t frsz) {
 uint8_t buff[4];
 track.seek(10);
 track.read((uint8_t *)frame, 4);

 track.seek(14);
 track.read((uint8_t *)buff,4);
 ltwo[0] = buff[0];
 ltwo[1] = buff[1];
 ltwo[2] = buff[2];
 ltwo[3] = buff[3];

 ltwo[0] = ltwo[0] * 2097152;
 ltwo[1] = ltwo[1] * 16384;
 ltwo[2] = ltwo[2] * 128;

 frsz = ltwo[0] + ltwo[1] + ltwo[2] + ltwo[3];

 track.rewind();
}

Am I missing some sort of initialization for this uint32?

What do you mean by “I cannot assign a value to the variable”? Of course you can. Do you mean you would like a variable of the caller to be modified?

I think the question implies that, Edgar.

let the function return the value

void frameInfo(File track, char frame[4], uint32_t ltwo[4], int32_t frsz) {

The way you did it, frsz is passed by value (ie. a copy is made, and you have changed the copy, not the original). To make it change outside the function you need to pass it by reference:
void frameInfo(File track, char frame[4], uint32_t ltwo[4], int32_t &frsz) {

Note the ampersand.

normal would be to return the value as return of the function. but we don't know the context.

That was what I was missing. Thanks Nick!


text:
Why i am not getting the decimal number as output? The code is explained with the help of comments
// Defined three array arr0,arr1,arr2
int arr0[] = {0, 0, 0, 0, 0, 0, 0, 0};
int arr1[] = {0, 0, 0, 0, 0, 0, 0, 0};
int arr2[] = {0, 0, 0, 0, 0, 0, 0, 0};

//cord function takes binary number array as input and returns decimal
//number to a single variable as output
int cord(int a[]) {
  int v = 0;
  for (int i = 0; i < 8; i++)
  {
    int p = 1;
    for (int j = 0; j < i; j++)
    {
      p = p * 2;
    }
    v = v + a[i] * p;
  }
  return v;
}

//function bcord takes input row & col and updates the value in arr0,arr1,arr2 to 1 wherever
// there is some value in the row and column coordinate Eg.2,0 will make 2nd index of arr0
// to 1 or 2,1 will make 2nd index of arr1 to 1
int bcord(int row[], int col[])
{

  int n = sizeof(col) / sizeof(col[0]);

  for (int i = 0; i < n; i++)
  {
    int j;
    if (col[i] == 2)
    {
      j = row[i];
      arr2[j] = 1;
    }
    if (col[i] == 1)
    {
      j = row[i];
      arr1[j] = 1;
    }
    if (col[i] == 0)
    {
      j = row[i];
      arr0[j] = 1;
    }
  }
  int led0 = cord(arr0);
  Serial.print(led0);
  int led1 = cord(arr1);
  Serial.println(led1);
  int led2 = cord(arr2);
  Serial.println(led2);
  return 0;
}

void setup()
{
  Serial.begin(9600);
  int row[] = {0, 0, 2, 2, 1};
  int col[] = {0, 1, 0, 1, 1};
  bcord(row, col);
}

void loop() {}
// Output expected is decimal numbers which are stored in led0, led1 and led2 on the serial
// monitor

what output are you getting?

your code is improperly formatted ... code that should be indented, isn't indented ... code that should not be indented, is indented ... it's a mess

I just used the autoindent function of the Arduino IDE. You should make more use of it, because correct indenting comes in very handy to find certain syntax errors.

Thank you jsotola, Chrisl & Edgar! But i get 57 and then 0 in next line as output. How can i get the decimal values stored in led0, led1 and led2?

“570” is correct: led0 is 5, led1 is 7 and led2 is 0.

Thank you Edgar, i totally missed that!

In C++, you cannot pass an array as a parameter to a function. When you
write the function prototype
int bcord(int row[], int col[], int n)

the compiler considers it a synonym of:
int bcord(int *row, int *col, int n)

In other words, both row and col are pointers, not arrays.
When you call the function like this:
bcord(row, col);

the compiler implicitly converts the call into this:
bcord(&row[0], &col[0]);

In other words, you are really passing pointers to the first element of
each array. This is a standard language behavior called “decay to
pointer”.
When I compile your code with warnings enabled, I get the following:
In function 'int bcord(int*, int*)':
warning: 'sizeof' on array function parameter 'col'
will return size of 'int*' [-Wsizeof-array-argument]
   int n = sizeof(col) / sizeof(col[0]);
                     ^
arr-ind.ino:31:30: note: declared here
 int bcord(int row[], int col[])
                              ^

Thus the compiler is telling you what is wrong. The variable n is not
what you expect.
The standard solution is to pass the size of the array from the caller:
move the definition of n to setup(), define bcord() as:
int bcord(int row[], int col[], int n)

and call it as
bcord(row, col, n);


text:
Arduino ESP8266WebServer hangs after a while but responds pings
I have an ESP8266 module that I use to be able to power on three computers if they are off. The ESP8266WebServer has what I needed to have a POST method rather than a simpler GET one since I am sending a password and I want that little extra security.
The code works and the circuits work as expected but only for a while. I have not been able to track down what is happening but whatever I do, it always hangs after some time but only the web server, it stills continues to respond pings so I know it is still connected and the serial monitor writes back my debug texts.
What I have tried after researching for some time:

The HTML output string probably gets too big for the memory and should use PROGMEM but in the end, I sill need to manipulate it and something breaks. Gave up on it.
The HTML output had an embedded image for the logo that also probably gets too big for the memory. Erased the image but stills hangs about the same time with or without it.
Looked for a way to hardreset the ESP8266 module, could not find how and it is surely bad practice and may come with other kind of problems.
Add a timeout for the connection, did not make any difference either.

I am missing something with the handle of the web server that gets the memory or something full and it stops answering request after a while because of it.
Here is the code:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid     = "";
const char* password = "";
const char* hostname = "";
const String imgLogo = "";

ESP8266WebServer server(9080);

String header = "";

String output1State = "off";
String output2State = "off";
String output3State = "off";

const int output1 = D1;
const int output2 = D2;
const int output3 = D8;

const int input1 = D5;
const int input2 = D6;
const int input3 = D7;

const int ledPin =  LED_BUILTIN;

unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long timeoutTime = 2000;

unsigned long previousMillisOff = 0;
unsigned long previousMillisOn = 0;
unsigned long previousMillisMsg = 0;

void setup() {
  Serial.begin(9600);
  pinMode(output1, OUTPUT);
  pinMode(output2, OUTPUT);
  pinMode(output3, OUTPUT);
  pinMode(input1, INPUT);
  pinMode(input2, INPUT);
  pinMode(input3, INPUT);

  digitalWrite(output1, LOW);
  digitalWrite(output2, LOW);
  digitalWrite(output3, LOW);

  WiFi.disconnect();
  delay(500);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);

  WiFi.mode(WIFI_STA);
  WiFi.hostname(hostname);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
    digitalWrite(ledPin, !digitalRead(ledPin));
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.getAutoConnect());
  digitalWrite(ledPin, HIGH);

  server.on("/", HTTP_GET, handleRoot);
  server.on("/serverAction", HTTP_POST, serverAction);
  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void)
{
  server.handleClient();

  unsigned long currentMillis = millis();
  if(currentMillis - previousMillisOff > 5000)
  {
    previousMillisOff = currentMillis;
    digitalWrite(ledPin, LOW);
    previousMillisOn = currentMillis;
  }

  currentMillis = millis();
  if(!digitalRead(ledPin) && currentMillis - previousMillisOn > 250)
  {
    previousMillisOn = currentMillis;
    digitalWrite(ledPin, HIGH);
    previousMillisOff = currentMillis;
  }

  currentMillis = millis();
  if(currentMillis - previousMillisMsg > 30000)
  {
    Serial.println(WiFi.localIP());
    previousMillisMsg = currentMillis;
  }
}

void handleRoot()
{
  boolean PC01 = digitalRead(input1);
  boolean PC02 = digitalRead(input2);
  boolean PC03 = digitalRead(input3);

  String HTML = String("<!DOCTYPE html>\r\n\r\n") +
    " \r\n    <meta charset=\"UTF-8\">\r\n    <meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate, post-check=0, pre-check=0\" />\r\n    <meta http-equiv=\"cache-control\" content=\"max-age=0\" />\r\n   <meta http-equiv=\"expires\" content=\"0\" />\r\n   <meta http-equiv=\"expires\" content=\"Tue, 01 Jan 1980 1:00:00 GMT\" />\r\n    <meta http-equiv=\"pragma\" content=\"no-cache\" />\n\r   <link href=\"data:image/x-icon;base64," + imgLogo + "\" rel=\"icon\" type=\"image/x-icon\" />\r\n   \r\n \r\n \r\n    \r\n\r\n
Server switch
\r\n  " +
    "
Estado PC01 - " + (PC01 ? "Encendido" : "Apagado") + "\r\n" +
    "
\r\n" +
    "   <form action=\"/serverAction\" method=\"post\">\r\n" +
    "     Contraseña: <input type=\"password\" name=\"pwd\">\r\n" +
    "
\r\n" +
    "     <input type=\"text\" name=\"server\" value=\"PC01\" hidden>\r\n" +
    "     <button class=\"button " + (PC01 ? "" : "button2") + "\" type=\"submit\"" + (PC01 ? " disabled> PC01 encendido" : ">Encender PC01") + "</button>\r\n" +
    "   </form>\r\n\r\n" +
    "
Estado PC02 - " + (PC02 ? "Encendido" : "Apagado") + "\r\n" +
    "
\r\n" +
    "   <form action=\"/serverAction\" method=\"post\">\r\n" +
    "     Contraseña: <input type=\"password\" name=\"pwd\">\r\n" +
    "
\r\n" +
    "     <input type=\"text\" name=\"server\" value=\"PC02\" hidden>\r\n" +
    "     <button class=\"button " + (PC02 ? "" : "button2") + "\" type=\"submit\"" + (PC02 ? " disabled> PC02 encendido" : ">Encender PC02") + "</button>\r\n" +
    "   </form>\r\n\r\n" +
    "
Estado PC03 - " + (PC03 ? "Encendido" : "Apagado") + "\r\n" +
    "
\r\n" +
    "   <form action=\"/serverAction\" method=\"post\">\r\n" +
    "     Contraseña: <input type=\"password\" name=\"pwd\">\r\n" +
    "
\r\n" +
    "     <input type=\"text\" name=\"server\" value=\"PC03\" hidden>\r\n" +
    "     <button class=\"button " + (PC03 ? "" : "button2") + "\" type=\"submit\"" + (PC03 ? " disabled> PC03 encendido" : ">Encender PC03") + "</button>\r\n" +
    "   </form>\r\n \r\n";

  server.send(200, "text/html", HTML);

}

void serverAction()
{

  if( ! server.hasArg("pwd") || ! server.hasArg("server") || server.arg("pwd") == NULL || server.arg("server") == NULL)
  {
    server.send(400, "text/plain", "400: Invalid Request");
    return;
  }

  if(server.arg("pwd") == "0123456789")
  {
    String redirect = String("");
    if(server.arg("server") == "PC01")
    {
      if(!digitalRead(input1))
      {
        server.send(200, "text/html", "
Encendiendo " + server.arg("server") + "
" + redirect);
        digitalWrite(output1, HIGH);
        delay(1000);
        digitalWrite(output1, LOW);
      }
      else
        server.send(200, "text/html", "
" + server.arg("server") + " ya encendido
" + redirect);

    }
    else if(server.arg("server") == "PC02")
    {
      if(!digitalRead(input2))
      {
        server.send(200, "text/html", "
Encendiendo " + server.arg("server") + "
" + redirect);
        digitalWrite(output2, HIGH);
        delay(1000);
        digitalWrite(output2, LOW);
      }
      else
        server.send(200, "text/html", "
" + server.arg("server") + " ya encendido
" + redirect);
    }
    else if(server.arg("server") == "PC03")
    {
      if(!digitalRead(input3))
      {
        server.send(200, "text/html", "
Encendiendo " + server.arg("server") + "
" + redirect);
        digitalWrite(output3, HIGH);
        delay(1000);
        digitalWrite(output3, LOW);
      }
      else
        server.send(200, "text/html", "
" + server.arg("server") + " ya encendido
" + redirect);
    }
    else
    {
      server.send(401, "text/plain", "401: Unauthorized");
    }
  }
  else
  {
    server.send(401, "text/plain", "401: Unauthorized");
  }
}

void handleNotFound(){
  server.send(404, "text/plain", "404: Not found");
}

Any suggestions would be appreciated.

When you use String the way you do, you're doing a lot of memory allocations. The ESP8266 doesn't have a lot of memory and is easily subject to a problem called "heap fragmentation" - memory is allocated from a fixed pool called a "heap". Over time the free parts of the heap may become so fragmented that you can no longer allocate chunks of memory over a certain size. The way that you're building the string in the variable HTML will probably cause this to happen quickly.
To check for heap fragmentation, add this code to the end of handleRoot():
  Serial.print("getFreeHeap: ");
  Serial.println(ESP.getFreeHeap());
  Serial.print("getHeapFragmentation: ");
  Serial.println(ESP.getHeapFragmentation());
  Serial.print("getMaxFreeBlockSize: ");
  Serial.println(ESP.getMaxFreeBlockSize());

And use your web server, especially reloading the root page, until you see the problem happen.
If you have a memory leak (memory is being allocated but never freed), you'll see getFreeHeap drop and not go back up.
If you have heap fragmentation, you'll see getMaxFreeBlockSize get smaller until it's smaller than the biggest strings you're trying to allocate (probably the total length of the root web page). You'll also see getHeapFragmentation get bigger over time - it's a metric from 0 to 100% of how fragmented the heap is. If it gets to 40 or 50% you're in trouble.
If you are seeing heap fragmentation you're going to need to rethink the way you build the web page you're serving. You need to minimize the number of times that you allocate memory. You may not know it but every time you add something on to a String, it frees the memory for the old string and allocates memory for the new one.
For instance, you build the web page like this:
 String HTML = String("<!DOCTYPE html>\r\n\r\n") +
    " \r\n    <meta charset=\"UTF-8\">\r\n    <meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate, post-check=0, pre-check=0\" />\r\n    <meta http-equiv=\"cache-control\" content=\"max-age=0\" />\r\n   <meta http-equiv=\"expires\" content=\"0\" />\r\n   <meta http-equiv=\"expires\" content=\"Tue, 01 Jan 1980 1:00:00 GMT\" />\r\n    <meta http-equiv=\"pragma\" content=\"no-cache\" />\n\r   <link href=\"data:image/x-icon;base64," + imgLogo + "\" rel=\"icon\" type=\"image/x-icon\" />\r\n   \r\n \r\n \r\n    \r\n\r\n
Server switch
\r\n  " +
    "
Estado PC01 - " + (PC01 ? "Encendido" : "Apagado") + "\r\n" +
    "
\r\n" +
    "   <form action=\"/serverAction\" method=\"post\">\r\n" +

Every time you use + to add to the String here, you're causing the compiler to unnecessarily allocate memory. It's completely unnecessary to add most of these strings together. The C++ compiler will automatically concatenate strings written on separate lines, like so:
 String HTML = String("<!DOCTYPE html>\r\n\r\n") +
    " \r\n    <meta charset=\"UTF-8\">\r\n    <meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate, post-check=0, pre-check=0\" />\r\n    <meta http-equiv=\"cache-control\" content=\"max-age=0\" />\r\n   <meta http-equiv=\"expires\" content=\"0\" />\r\n   <meta http-equiv=\"expires\" content=\"Tue, 01 Jan 1980 1:00:00 GMT\" />\r\n    <meta http-equiv=\"pragma\" content=\"no-cache\" />\n\r   <link href=\"data:image/x-icon;base64," + imgLogo + "\" rel=\"icon\" type=\"image/x-icon\" />\r\n   \r\n \r\n \r\n    \r\n\r\n
Server switch
\r\n  "
    "
Estado PC01 - " + (PC01 ? "Encendido" : "Apagado") + "\r\n"
    "
\r\n"
    "   <form action=\"/serverAction\" method=\"post\">\r\n"

Just making that change will reduce the heap fragmentation. This won't solve the problem but it should allow your program to run longer without crashing.
This is a big subject. The best way to do it is to use C strings (character arrays) and avoid allocating memory altogether, but this is difficult and tedious even for experienced programmers. The ESP8266 Arduino Core documentation offers some advice (see the section "Memory, memory, memory"), including using PROGMEM for constant literal strings and creating String objects with all the space they'll need when they're allocated, to avoid freeing and re-allocating the internal buffer they use to store the string.
If you're having heap fragmentation issues, do everything you can to reduce String use in your program. If that doesn't get your web server working reliably, search the web and Stack Overflow for more advice on how to avoid heap fragmentation, and post new questions here about specific issues.

Hi, thank you and sorry for not getting back here sooner. I will try what you suggest and give a follow up of what is going with this.

i bet $20 is the String (mis)usage...


text:
I am trying to add a countdown to my Arduino code but it does 0 days, 04:09:36 instead of starting at 7 days
The code I use probably has a math problem since an Arduino can only count a 16 bit integer. This problem is with the WeekDelay() function.
The project is for an Aerogarden. It pumps water into the garden every week from information based on my collected data. It writes on the LCD information like if it is pumping, waiting (it should have the timer here and display on the LCD), and it can show when it is going to pump with a beep warning. After beeping, pumping, and waiting for a few times I run out of information and do a loop and show a warning message, blinking the LCD and pumping a set amount.
More specifically WeekDelay() should be a delay for a week. It clears the LCD, Sets the cursor to 0,0 and prints "Waiting one week". It should then have a countdown of 24 hours on the screen and then just how many days it is waiting. It does that through clearing the LCD, Setting the cursor, printing days and waiting.
Because of the glitch it does not display any days even though it should show 7. It displays 04:09:36. Somebody was helping me out and said this:
Ah, it is the integer math interacting with the size of days. 04:09:36 = 43600+960+36 = 14976 which happens to be equal to 7243600 % 32768. See gammon.com.au/forum/?id=12146 and https://wiki.sei.cmu.edu/confluence/display/c/INT35-C.+Use+correct+integer+precisions for what's happening.
This is some cut-down version of my code:
int beeper_pin      = 2; //Naming buzzer pin
int resetGarden_pin = 3; //Naming the warning led pin
int pump_pin        = 6; //Naming the pump pin

#include <LiquidCrystal_I2C.h> // Driver Library for the LCD Module

LiquidCrystal_I2C lcd(0x27, A4, A5);

void clearLCDLine(int line)
{
  lcd.setCursor(0, line);
  for (int n = 0; n < 20; n++) // 20 indicates symbols in line. For 2x16 LCD write - 16
  {
    lcd.print(" ");
  }
}

void beepWarning() {            //Makes beeping a subroutine

  lcd.setCursor(0, 0);
  lcd.print("WARNING");
  delay(100);
  lcd.setCursor(0, 1);
  for (int x = 0; x < 3; x++) {

    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE");
    delay(100);
    clearLCDLine(1);
    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE.");
    delay(100);
    clearLCDLine(1);
    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE..");
    delay(100);
    clearLCDLine(1);
    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE...");
    delay(100);
    clearLCDLine(1);
  }

  lcd.setCursor(0, 1);
  lcd.print("WATER PUMP ACTIVE...");

  for (int x = 0; x < 3; x++) {   //Repeats 3 times

    digitalWrite(beeper_pin, HIGH); //Turn on buzzer
    delay(100);                     //Delay of 400 milliseconds
    digitalWrite(beeper_pin, LOW);  //Turns off buzzer
    delay(100);                     //Delay of 400 milliseconds

  }
}

void SOSWarning() {            //Makes SOS a subroutine

  clearLCDLine(1);
  lcd.setCursor(0, 0);
  lcd.print("WPA Reset Aerogarden");

  for (int x = 0; x < 3; x++) {   //Repeats 3 times

    for (int d = 0; d < 3; d++) {   //Repeats 3 times
      digitalWrite(beeper_pin, HIGH); //Turn on buzzer
      delay(200);                     //Delay of 400 milliseconds
      digitalWrite(beeper_pin, LOW);  //Turns off buzzer
      delay(200);                     //Delay of 400 milliseconds
    }

    for (int a = 0; a < 3; a++) {   //Repeats 3 times
      digitalWrite(beeper_pin, HIGH); //Turn on buzzer
      delay(400);                     //Delay of 400 milliseconds
      digitalWrite(beeper_pin, LOW);  //Turns off buzzer
      delay(400);                     //Delay of 400 milliseconds
    }

    for (int d = 0; d < 3; d++) {   //Repeats 3 times
      digitalWrite(beeper_pin, HIGH); //Turn on buzzer
      delay(200);                     //Delay of 400 milliseconds
      digitalWrite(beeper_pin, LOW);  //Turns off buzzer
      delay(200);                     //Delay of 400 milliseconds
    }

    delay(500);                     //Delay of 500 milliseconds
  }
}

void weekDelay() { //Makes waiting for a week a subroutine
  clearLCDLine(1);
  clearLCDLine(0);
  lcd.setCursor(0, 0);
  lcd.print("Waiting One Week");

  unsigned long start = millis();
  unsigned long week_secs = 7 * 24 * 3600;
  unsigned long countdowntime_seconds;

  while (countdowntime_seconds = week_secs - (millis() - start)/1000){
     char buff[80];
     int countdown_day = countdowntime_seconds / 3600 / 24;
     int countdown_hour = (countdowntime_seconds / 3600) % 24;
     int countdown_minute = ((countdowntime_seconds / 60) % 60);
     int countdown_sec = countdowntime_seconds % 60;
     sprintf(buff,"%1d days, %02d:%02d:%02d",
            countdown_day,
            countdown_hour,
            countdown_minute,
            countdown_sec
            );
     Serial.print(buff);
     clearLCDLine(1);
     lcd.setCursor(2, 1);
     lcd.print(buff);
     delay(1000);
     }
}

void pumpOn() {               //Makes turning on the pump a subroutine
  clearLCDLine(1);
  lcd.setCursor(0, 1);
  lcd.print("PUMPING");
  delay(100);
  digitalWrite(pump_pin, HIGH); //Turning on the pump
}

void pumpOff() {              //Makes turning off the pump a subroutine
  digitalWrite(pump_pin, LOW);  //Turning off the pump
  clearLCDLine(1);
  lcd.setCursor(0, 1);
  lcd.print("WATER PUMP OFF");
  delay(1000);
}

void setup() {
  //run once:
  lcd.backlight();
  lcd.init();

  lcd.setCursor(4, 0);//////////////////////////////////////////////////////
  lcd.print("HH:MM:SS"); //////////////////////////////////////////////////

  lcd.clear(); // Clear the screen
  lcd.setCursor(0, 0);
  lcd.print("Aero_Pump V3");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("By Alex");
  delay(1000);
  pinMode (beeper_pin,      OUTPUT); //Setting outputs
  pinMode (resetGarden_pin, OUTPUT); //Setting outputs
  pinMode (pump_pin,       OUTPUT); //Setting outputs
  lcd.clear(); // Clear the screen

  digitalWrite(resetGarden_pin, LOW); //Turning off the reset garden light

  beepWarning(); //Beeps a warning
  pumpOn();      //Turns on the pump
  delay(3000);  //Adds a delay of 24000 milliseconds
  pumpOff();     //Turns off the pump
  weekDelay();   //Waits a week

  beepWarning(); //Beeps a warning
  pumpOn();      //Turns on the pump
  delay(12000);  //Adds a delay of 24000 milliseconds
  pumpOff();     //Turns off the pump
  weekDelay();   //Waits a week
}

void loop() {

  SOSWarning(); //Beeps an SOS warning
  pumpOn();      //Turns on the pump
  delay(48000);  //Adds a delay of 48000 milliseconds
  pumpOff();     //Turns off the pump

  for (int x = 0; x < 3024000; x++) {
    lcd.backlight(); // turn on backlight.
    delay(100);
    lcd.noBacklight(); // turn off backlight
    delay(100);
  }
  lcd.backlight(); // turn on backlight.
}

This is the function that needs to be fixed:
void weekDelay() { //Makes waiting for a week a subroutine
  clearLCDLine(1);
  clearLCDLine(0);
  lcd.setCursor(0, 0);
  lcd.print("Waiting One Week");

  unsigned long start = millis();
  unsigned long week_secs = 7 * 24 * 3600;
  unsigned long countdowntime_seconds;

  while (countdowntime_seconds = week_secs - (millis() - start)/1000){
     char buff[80];
     int countdown_day = countdowntime_seconds / 3600 / 24;
     int countdown_hour = (countdowntime_seconds / 3600) % 24;
     int countdown_minute = ((countdowntime_seconds / 60) % 60);
     int countdown_sec = countdowntime_seconds % 60;
     sprintf(buff,"%1d days, %02d:%02d:%02d",
            countdown_day,
            countdown_hour,
            countdown_minute,
            countdown_sec
            );
     Serial.print(buff);
     clearLCDLine(1);
     lcd.setCursor(2, 1);
     lcd.print(buff);
     delay(1000);
     }
}

tip: do lcd.print("WATER PUMP ACTIVE"); ... delay(100); ... lcd.print("."); ... there is no need to clear LCD and print same line over and over

As the comment already tells, you are trying to calculate a constant with int literals that overflows:
unsigned long week_secs = 7 * 24 * 3600;
This is 604800 (0x93A80), but since ints are just signed 16 bits numbers (with your compiler system), only the lower 16 bits are taken into account. Fortunately these lower 16 bits are positive in two's complement, and so you get 14976 (hex 0x3A80).
The correct statement uses at least one unsigned long value, and the integer promotion rules make sure that all values are converted to that type, too.
unsigned long week_secs = 7UL * 24 * 3600;

I hope I see you in heaven. Thank you so much. This has taken so long to figure out.


text:
Power to triac dimmer and arduino uno
I am building 2 channel triac dimmer to control led strip lights in my pantry.  Have 4 channel Krida module (just use two, I guess) and Uno.  Have had some success with the triacDimmer library examples, but now realize I'm not sure of my basic approach.
I want to have two light circuits ramp up to a preset light level, then stay on until the power cuts out.  My question is this:  is it possible to power the Arduino Uno and the AC going into the triac module from the same switch?    Will the microcontroller just "start over" every time the power comes on to it - and will the triac be in "off" status without power to its gate?
This is a matter of design, and I'm way out of my depths.  I want to power this project, and write the sketch, so that the two circuits fade on to a  pre-set level when the power comes on.  Is it ok to plan to turn off the lights by just 'pulling the plug?'
Please let me know if this is still not an appropriate question for this forum.  I appreciate any help or feedback.  Thanks

please remove all the non-arduino parts of your post ... ask a specific answerable question about the arduino ... it would help a lot if you provided a diagram of your proposed wiring configuration

You ask: "is it possible to power the Arduino Uno and the AC going into the triac module from the same switch? Will the microcontroller just "start over" every time the power comes on to it - and will the triac be in "off" status without power to its gate?"
Yes you can put a switch in the line that powers the primary side that feeds both the lights and the UNO power supply. The 4 channel Krida module I have does not turn on the lights until I power the optocoupler. I also have one that has a processor on board and it behaves the same way. When you write your code get a 24V transformer and two 24V lamps to debug your project, that way you will not fry yourself. This is how I normally prototype 120 and 240 Volt circuits. I then test it with the mains when it is all assembled and the test equipment disconnected. Remember some best equipment especially bench type has a connection to the earth ground.

I appreciate your answer.  I have hit wall with trying to use/adapt either of two sketches.  Is there a good place in this forum to post software questions? I remember when dimmers we're really simple

The Krida module comes in many varieties. Go to the website where you purchased it they will probably have examples of the code for the Arduino. This link was my first try: https://www.tindie.com/products/bugrovs2012/ardutex-trailing-edge-i2c-ac-led-light-dimmer/


text:
Matrix Keyboard
I'm trying to program a mechanical keyboard running on the Arduino Pro Micro (5V/16MHz). I'm using a matrix approach (4x12), and while I believe the code and the wiring (both of which I've checked multiple times) are correct, I can't get the first two rows to work no matter what. I've tried wiring it up to other pins, which works, but only for two rows at a time, when I hook up all the 4 rows, the two ones on top don't work. The code:
/*cols and rows*/
byte rows[] = {2,3,4,5};
const int row_Count = 4;
byte cols[] = {6,7,8,9,10,14,15,16,18,19,20,21};
const int col_Count = 12;

byte keyboard[col_Count][row_Count];

void read_layout() {
    /*do the columns*/
    for (int col_Index=0; col_Index < col_Count; col_Index++) {
        /*setup for registering the column state*/
        byte cur_Col = cols[col_Index];
        pinMode(cur_Col, OUTPUT);
        digitalWrite(cur_Col, LOW);

        /*do the rows*/
        for (int row_Index=0; row_Index < row_Count; row_Index++) {
            byte row_Col = rows[row_Index];
            pinMode(row_Col, INPUT_PULLUP);
            keyboard[col_Index][row_Index] = digitalRead(row_Col);
            pinMode(row_Col, INPUT);
        }
        /*disable the column*/
        pinMode(cur_Col, INPUT);
    }
}

void print_layout() {
    for (int row_Index=0; row_Index < row_Count; row_Index++) {
        Serial.print(row_Index);
        Serial.print(F(": "));

        for (int col_Index=0; col_Index < col_Count; col_Index++) {
            Serial.print(keyboard[col_Index][row_Index]);
            if (col_Index < col_Count) Serial.print(F(", "));
        }
        Serial.println("");
    }
    Serial.println("");
}

void setup() {
    Serial.begin(115200);
    delay(2000);
    /*init the rows*/
    for(int i=0; i<row_Count; i++) {
        pinMode(rows[i], INPUT);
    }
    /*init the cols*/
    for (int i=0; i<col_Count; i++) {
        pinMode(cols[i], INPUT_PULLUP);
    }
}

void loop() {
    read_layout();
    print_layout();

}

This is the schematic, a "dirty sketch":

two ones on top is meaningless ... how are they connected?

have you checked if a matrix keypad library is available?

Did you "rotate" the rows, to see whether the port pins or the matrix give the issue? Did you try with a smaller number of rows, and increase it one by one? Why do you change the pin modes of the rows, they can always be INPUT_PULLUP? -- Unrelated: the condition in print_layout() does not prevent the printing of the last comma. col_Index is always lower than col_Count there. -- Unrelated: You can automate the calculation of the sizes, for example const int col_Count = sizeof cols / sizeof cols[0];.

@jsotola I made a dirty sketch, "two ones on top" refers to R1 and R2, and I'm not using the keypad library because I think it is unnecessary and apparently multiple key presses at the same time don't register.

@thebusybee I've tried switching around the row pins, there wasn't an issue with the "first two rows" in particular, the problem only began when I hooked up more than 2 rows to it, then only the "last two" would work. The idea with INPUT_PULLUP was to only check periodically whenever I wanted to, then switch to INPUT, I'm not sure if this makes sense because this is the first time I'm using this pinmode. Thanks for the other tips I've already implemented them.

Please add the sketch in your question, so it wont get lost over time. -- Do you really have all these diodes in series, for example 4 for the topmost row in the schematic? Their forward voltages add up, and the input might not recognize the "LOW" then. Please make an experiment with a static level on one column and measure the voltage at the rows' pin.

@thebusybee Not sure what you mean by "add the sketch", It's already in the OP, should archive it and post the link here or what? Anyways, you're right. I tried shorting one of the columns and it worked! But I want to have the diodes to prevent ghosting, how would you go about that? Connect the diodes in series but on the rows instead of the columns?

Leaving a link to an external resource in a comment is quite not "in the OP". ;-) I used the provided procedure and added it to your question; well, first it needs approval due to my low reputation.

@thebusybee, Ah, I apologize, I thought you meant the Arduino (code) sketch.

Apology accepted. :-D Well, it was your wording on the link to the schematic. ;-)

You are using the diodes in series, which leads to accumulating forward voltages in the lower rows of your schematic. Because of this accumulation the threshold for "low" will not be crossed, and the input pin cannot recognize a pressed key.
Instead, you should adopt this circuit (copied from "Keyboard Matrix Help" by Dave Dribin). Of course, you will put the cathods on your columns pins, and the anodes on the keys.

So the right circuit uses each diode-and-key combination in parallel, not in series.


text:
String to unsigned 16-bit integer
I'm currently working on a project with a 4DSystems Display. Im talking to the Display over SoftwareSerial with an ESP32. As soon as I want to use a Unicode character it requires me to convert my whole String to a uint16_t. Can somebody help me I have no idea how I should go on with this?
  #include <genieArduino.h>
  void loop() {
    uint16_t tn[] = { 0x2126,0 }; // Ω
    genie.WriteStrU(0, tn);
  }

This works but how could I inset a variable into the uint16_t?

Please provide the code that you have, error messages that you got and links to the used parts and libraries.

Which Arduino is this for?

I haven't seen that display library before, but probably it would be easier to only write the actual unicode characters via the unicode function and the rest with the normal write functions. Or is there a specific reason why you want to put another (probably numeric) variable inside that unicode string? From the documentation of the library it is unclear what encoding actually is used there. Maybe it would also work to just write the normal ASCII data in your unicode string, just casted to uint16_t (leaving the high byte empty).

As mentioned by chrisl in a comment, your best option is to to use the
regular WriteStr() method to print variables, and use WriteStrU() to
print Unicode string constants. For example:
float R = 12.34;  // dummy resistance value.
genie.WriteStr(0, "R = ");
genie.WriteStr(0, R);
genie.WriteStrU(0, (uint16_t *) u" Ω");

should print:
R = 12.34 Ω

Note the use of the u string prefix to write UTF-16-encoded strings in
the source code.

Edit: You wrote

the WriteStr always replaces the text inside a String object instead
of adding on.

This makes things more complicated. The only option I see is to format
the whole message as UTF-16 beforehand, then send it with WriteStrU().
Here is a class that does simple UTF-16 formatting. It inherits from the
Print class, meaning you can print() to it anything you could print
to Serial. In addition, it can print UTF-16 strings:
template <size_t max_length>
class UTF16Writer : public Print {
public:
    // Convert ASCII to UTF-16.
    size_t write(uint8_t c) {
        if (length >= max_length)
            return 0;  // buffer full
        buffer[length++] = c;
        buffer[length] = 0;  // terminate string
        return 1;
    }
    // Record UTF-16 data.
    size_t print(const char16_t *s) {
        size_t chars_written = 0;
        while (*s && length < max_length) {
            buffer[length++] = *s++;
            chars_written++;
        }
        buffer[length] = 0;  // terminate string
        return chars_written;
    }
    using Print::print;
    uint16_t buffer[max_length + 1];
private:
    size_t length = 0;
};

The template parameter is the capacity of the buffer. Once you have
written the whole message as UTF-16 using this class, you can pass its
buffer member to WriteStrU(). For example:
float R = 12.34;  // dummy resistance value.
UTF16Writer<16> writer;
writer.print("R = ");
writer.print(R);
writer.print(u" Ω");
genie.WriteStrU(0, writer.buffer);

Note: Do not forget the u prefix in the Unicode string, otherwise
the bytes of the string (UTF-8 in the source) would be interpreted as
latin1 by UTF16Writer::print(const char*). A message such as "martine écrit en UTF-8" would then be displayed as “martine Ã©crit en UTF-8”.


text:
WeMos D1 losing WiFi connection
I have a WeMos D1 connected to an air quality sensor and publishing the value on a self-hosted website.
Initially everything works fine (although router UI does not display WeMos). After an hour or two WiFi connection fails.
Other devices on the network are unaffected. Sensor data is still being polled, serial connection works fine, but the device doesn't respond to the ping and the website obviously doesn't work.
Here's the code:
#include <ESP8266WiFi.h>

#include "SerialCom.h"
#include "Types.h"

//WiFi setup:
const char* ssid = "mySSID";                    // Enter SSID here
const char* password = "myPASS";                // Enter Password here

IPAddress ip(192, 168, 0, 101);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

WiFiServer  server(80);                         // Server on port 80
String header;

// sensor setup:

uint32_t statusPublishPreviousMillis = 0;
const uint16_t statusPublishInterval = 30000;   // 30 seconds = 30000 milliseconds

particleSensorState_t state;

unsigned long currentTime = millis();           // Current time
unsigned long previousTime = 0;                 // Previous time
const long timeoutTime = 2000;                  // Define timeout time in milliseconds (example: 2000ms = 2s)

float average;
int rounded;

void setup() {

    Serial.begin(115200);
    SerialCom::setup();
    WiFi.config(ip, gateway, subnet);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);                 // Connect to the WiFi router
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");                         // If connection successful show IP address in serial monitor
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());             // IP address assigned to your ESP

    server.begin();                             // Start server
    Serial.println("HTTP server started");
}

void loop() {

    SerialCom::handleUart(state);               // communicate with the sensor
    average = SerialCom::forward(state);        // read sensor value
    rounded = round(average);                   // round the value so that we don't have .00

    const uint32_t currentMillis = millis();
    if (currentMillis - statusPublishPreviousMillis >= statusPublishInterval) {
        statusPublishPreviousMillis = currentMillis;
    }

    WiFiClient client = server.available();
    if (client) {                               // If a new client connects,
        Serial.println("Client connected");     // print a message out in the serial port
        String currentLine = "";                // make a String to hold incoming data from the client
        currentTime = millis();
        previousTime = currentTime;

        while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
            currentTime = millis();
            if (client.available()) {           // if there's bytes to read from the client,
                char c = client.read();         // read a byte, then
//              Serial.write(c);                // print it out the serial monitor
                header += c;
                if (c == '\n') {                // if the byte is a newline character
                    // if the current line is blank, you got two newline characters in a row.
                    // that's the end of the client HTTP request, so send a response:
                    if (currentLine.length() == 0) {
                        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                        // and a content-type so the client knows what's coming, then a blank line:
                        client.println("HTTP/1.1 200 OK");
                        client.println("Content-type:text/html");
                        client.println("Connection: close");
                        client.println();

                        // Display the HTML web page
                        client.println("<!DOCTYPE html>");
                        client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
                        client.println("<meta charset='utf-8'>");

                        // Values in the website title
                        client.print("<title>");
                        client.print(rounded);
                        client.println(" μg/m³</title>");
                        client.println("");

                        // Web Page Heading
                        client.println("");
                        client.println(rounded);
                        client.println("");

                        client.println("");      // The HTTP response ends with another blank line
                        break;                   // Break out of the while loop
                    } else {                     // if you got a newline, then clear currentLine
                        currentLine = "";
                    }
                } else if (c != '\r') {          // if you got anything else but a carriage return character,
                    currentLine += c;            // add it to the end of the currentLine
                }
            }
        }

        header = "";                             // Clear the header variable
        client.stop();                           // Close the connection
    }
}

EDIT:
I've read somewhere that String implementation in ESP8266 library is problematic, so I replaced every String with char*. That increased the uptime to around 30 hrs.

Before the edit you said that you'd added a check for wifi disconnection which rebooted the ESP8266 and it didn't help. Did it find that wifi disconnected and reboot, or did it do nothing?

It did nothing. If nothing helps, I will test and see if it didn't detect the issue or detected it but the restart didn't help. But I would like to find the root cause and avoid restarting if possible.

Can you try a different unit? I had a similar problem a few years back. Changing the board helped a lot but finally I changed the router and the problem vanished.

I've ordered a second one, but it will take some time and would like to make it work without additional hardware.


text:
Error while burning bootloader onto ATMega-8A using Arduino Mega 2560: avrdude: invalid byte value
So, I'm trying to burn the bootloader onto an ATMega 8A with an Arduino Mega 2560 as ISP.
I made the necessary connections, and got this error:
C:\Program Files (x86)\Arduino\hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega8 -cstk500v1 -P\\.\COM3 -b19200 -e -Ulock:w:0x3f:m -Uhfuse:w:0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}:m -Ulfuse:w:0b{bootloader.bod_bits}{bootloader.sut_cksel_bits}:m

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM3
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
         AVR Part                      : ATMEGA8
         Chip Erase delay              : 10000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom         4    20   128    0 no        512    4      0  9000  9000 0xff 0xff
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           flash         33    10    64    0 yes      8192   64    128  4500  4500 0xff 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lfuse          0     0     0    0 no          1    0      0  2000  2000 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           hfuse          0     0     0    0 no          1    0      0  2000  2000 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lock           0     0     0    0 no          1    0      0  2000  2000 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           calibration    0     0     0    0 no          4    0      0     0     0 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
avrdude: Send: A [41] . [80]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [02]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [81]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [01]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [82]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [12]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [98]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
avrdude: Send: A [41] . [84]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [85]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [86]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [87]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [89]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: Send: A [41] . [81]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [01]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [82]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [12]
avrdude: Recv: . [10]
avrdude: Send: B [42] p [70] . [00] . [00] . [01] . [01] . [01] . [01] . [02] . [ff] . [00] . [ff] . [ff] . [00] @ [40] . [02] . [00] . [00] . [00]   [20] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: P [50]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: AVR device initialized and ready to accept instructions

Reading | avrdude: Send: V [56] 0 [30] . [00] . [00] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [1e]
avrdude: Recv: . [10]
avrdude: Send: V [56] 0 [30] . [00] . [01] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [93]
avrdude: Recv: . [10]
################avrdude: Send: V [56] 0 [30] . [00] . [02] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [07]
avrdude: Recv: . [10]
################################## | 100% 0.06s

avrdude: Device signature = 0x1e9307
avrdude: Send: V [56] . [a0] . [01] . [fc] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [ff]
avrdude: Recv: . [10]
avrdude: Send: V [56] . [a0] . [01] . [fd] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [ff]
avrdude: Recv: . [10]
avrdude: Send: V [56] . [a0] . [01] . [fe] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [ff]
avrdude: Recv: . [10]
avrdude: Send: V [56] . [a0] . [01] . [ff] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [ff]
avrdude: Recv: . [10]
avrdude: erasing chip
avrdude: Send: V [56] . [ac] . [80] . [00] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [81]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [01]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [82]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [12]
avrdude: Recv: . [10]
avrdude: Send: B [42] p [70] . [00] . [00] . [01] . [01] . [01] . [01] . [02] . [ff] . [00] . [ff] . [ff] . [00] @ [40] . [02] . [00] . [00] . [00]   [20] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: P [50]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: reading input file "0x3f"
avrdude: writing lock (1 bytes):

Writing | avrdude: Send: V [56] X [58] . [00] . [00] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [ff]
avrdude: Recv: . [10]
################################################## | 100% 0.02s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x3f:
avrdude: load data lock data from input file 0x3f:
avrdude: input file 0x3f contains 1 bytes
avrdude: reading on-chip lock data:

Reading | avrdude: Send: V [56] X [58] . [00] . [00] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [ff]
avrdude: Recv: . [10]
################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of lock verified
avrdude: reading input file "0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}"
avrdude: invalid byte value (0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}) specified for immediate mode
avrdude: read from file '0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}' failed
avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

These are my fuse bits:
# General
8.name=ATmega8 (8MHz Internal Clock on breadboard)
8.upload.tool=avrdude
8.upload.maximum_data_size=1024
8.bootloader.tool=avrdude
8.bootloader.unlock_bits=0x3f
8.bootloader.lock_bits=0x0f
8.bootloader.low_fuses=0b{bootloader.bod_bits}{bootloader.sut_cksel_bits}
8.bootloader.high_fuses=0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}
8.build.core=MCUdude_corefiles
8.build.variant=standard
8.build.board=AVR_ATmega8
8.build.mcu=atmega8
8.build.bootloader_led=B5

# Upload port select
8.menu.bootloader.uart0=Yes (UART0)
8.menu.bootloader.uart0.upload.maximum_size=7680
8.menu.bootloader.uart0.upload.protocol=arduino
8.menu.bootloader.uart0.upload.port=UART0
8.menu.bootloader.uart0.build.export_merged_output=true
8.menu.bootloader.uart0.bootloader.bootrst_bit=0
8.menu.bootloader.uart0.bootloader.file=optiboot_flash/bootloaders/{build.mcu}/{build.f_cpu}/optiboot_flash_{build.mcu}_{upload.port}_{upload.speed}_{build.f_cpu}_{build.bootloader_led}.hex

8.menu.bootloader.no_bootloader=No bootloader
8.menu.bootloader.no_bootloader.upload.maximum_size=8192
8.menu.bootloader.no_bootloader.build.export_merged_output=false
8.menu.bootloader.no_bootloader.bootloader.bootrst_bit=1
8.menu.bootloader.no_bootloader.bootloader.file=empty/empty.hex

# EEPROM
8.menu.eeprom.keep=EEPROM retained
8.menu.eeprom.keep.bootloader.eesave_bit=0
8.menu.eeprom.erase=EEPROM not retained
8.menu.eeprom.erase.bootloader.eesave_bit=1

# Brown out detection - This is the first part of the low fuse bit concatenation
8.menu.BOD.2v7=BOD 2.7V
8.menu.BOD.2v7.bootloader.bod_bits=10
8.menu.BOD.4v0=BOD 4.0V
8.menu.BOD.4v0.bootloader.bod_bits=00
8.menu.BOD.disabled=BOD disabled
8.menu.BOD.disabled.bootloader.bod_bits=11

# Compiler link time optimization
8.menu.LTO.Os=LTO disabled
8.menu.LTO.Os.compiler.c.extra_flags=
8.menu.LTO.Os.compiler.c.elf.extra_flags=
8.menu.LTO.Os.compiler.cpp.extra_flags=
8.menu.LTO.Os.ltoarcmd=avr-ar

8.menu.LTO.Os_flto=LTO enabled
8.menu.LTO.Os_flto.compiler.c.extra_flags=-Wextra -flto -g
8.menu.LTO.Os_flto.compiler.c.elf.extra_flags=-w -flto -g
8.menu.LTO.Os_flto.compiler.cpp.extra_flags=-Wextra -flto -g
8.menu.LTO.Os_flto.ltoarcmd=avr-gcc-ar

8.menu.clock.8MHz_internal=8 MHz internal
8.menu.clock.8MHz_internal.upload.speed=38400
8.menu.clock.8MHz_internal.bootloader.sut_cksel_bits=100100
8.menu.clock.8MHz_internal.bootloader.ckopt_bit=1
8.menu.clock.8MHz_internal.build.f_cpu=8000000L

Should I try deleting unnescessary stuff from the fuse bits?
I tried checking the fuse bits, but they're pretty much alien to me. Any help is welcome.
Thanks in advance
Me
Edit: I am using Arduino IDE v1.0.5 and have selected "Arduino as ISP" in the programmer.

The existence of unreplaced placeholders (e.g. {bootloader.bod_bits}) is significant in the output. Include your IDE version number and the name and version number of the board package you're using for ATMega8A support, and what you have selected in the menus, etc.  Maybe someone can replicate the error even without an ATMega8 on hand.

Arduino 1.0.5, "Arduino as ISP" programmer, and custom boards.txt file

1.0.5 is from 2013 and a lot has changed in the IDE since then, particularly between the 1.0.x versions and the 1.5.x versions. Most people wind up with 1.0.5 because it's in the Ubuntu's (and other Linux distribution's) package repo(s).
Anyway, it's likely that this old version doesn't define some of the things your board definition is referencing. E.g. you're referring to names that exist in the 1.8.x platform.txt file that don't exist in the 1.0.5 IDE. When the IDE fails to replace a key placeholder, it leaves it like you're seeing in your avrdude commandline: -Uhfuse:w:0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}:m -Ulfuse:w:0b{bootloader.bod_bits}{bootloader.sut_cksel_bits}:m   You should not be seeing these {blah} references in your command-lines when compiling or uploading.
Actually, 1.0.5 predates the handling of .menu. style properties. E.g. They used to have entire separate boards.txt entries for the ATMega328P based nano and the ATMega168 based nano and these are now handled by a single board with a .menu.cpu. section for the selection of the MCU used. So under 1.0.5 none of your .menu. properties are failing to be replaced by the IDE.
So, I would start by getting rid of the old IDE and instead installing the latest from the official site and seeing if that improves things.
That said, if you want to use the ATMega8A with Arduino it would probably be better to use MCUdude MiniCore rather than modifying the regular boards.txt file. You'll need a new IDE in order to use that anyway.


text:
Ubuntu Serial Port Briefly showing on arduino IDE
I am using a NodeMcu with Arduino IDE on Ubuntu.
I have managed to upload the blink script and it work.
Now, when i plug the nodemcu, the serial port /dev/ttyUSB0 is briefly available in the IDE.
After 2 seconds, the port menu is grayed out again and I can't use it.
Same with ls /dev/tty* /dev/ttyUSB0 is briefly available.
/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22  /dev/ttyUSB0
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25

After 2 seconds:
/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25

How can I fix that? I have try all the usb ports.
The NodeMCU settings:

Actually Using Ubuntu 22.04 LTS
EDIT:
While running sudo dmesg -w and connecting the mcu I get:
[ 3726.038486] usb 1-1: new full-speed USB device number 13 using xhci_hcd
[ 3726.220532] usb 1-1: New USB device found, idVendor=10c4, idProduct=ea60, bcdDevice= 1.00
[ 3726.220536] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 3726.220537] usb 1-1: Product: CP2102 USB to UART Bridge Controller
[ 3726.220538] usb 1-1: Manufacturer: Silicon Labs
[ 3726.220539] usb 1-1: SerialNumber: 0001
[ 3726.229998] cp210x 1-1:1.0: cp210x converter detected
[ 3726.231005] usb 1-1: cp210x converter now attached to ttyUSB0
[ 3727.565688] usb 1-1: usbfs: interface 0 claimed by cp210x while 'brltty' sets config #1
[ 3727.566375] cp210x ttyUSB0: cp210x converter now disconnected from ttyUSB0
[ 3727.566391] cp210x 1-1:1.0: device disconnected

the USB device here is the USB chip on the NodeMcu board, not the esp8266,

You may tail -f /var/log/syslog right before plugging in the board, and see if anything interesting shows up.

sudo dmesg -w will show you what's going on. Maybe it's shutting down the port because it's drawing too much current?

I have edited the post with result of the command.

From these logs, it looks like the brltty daemon tried to mess with the serial port. Can you disable this daemon and try again?

I had this same problem and eventually I traced it down to two bad cables. It would appear, up then the port would disappear or change so the serial monitor would fault. Try several cables, it is the easiest solution if it is the problem. I generally do not unplug the cable from the Arduino, just the USB one and leave cables on each of the Arduino.

This could be happening because Brltty application. Remove it and try again.
sudo apt remove brltty
sudo apt autoclean && sudo apt autoremove

brother you don't know you just saved my life
for the last 2 days i was looking for this

I'm glad about it...


text:
Powering LEDs with Arduino uno 5v
I'm working on the sound reactive led lamp as my first project and have slightly different materials to start with. First I'd like to simply learn to power the LED strip.
from https://www.youtube.com/watch?v=5oRir4dck_w
I'm attaching pictures so it's as simple as possible, but I'd like to confirm where to attach the wires on the uno and the basic logic behind how to get from the attempt I have now, to actually turning on the LEDs. Thanks so much!
(I think the images show up but please let me know if not)

A good question, best asked as you did before frying something. My Arduino rule #1 A power supply the Arduino is NOT! Connect the ground of the LED power supply to the ground of the arduino. Then connect the data line, as you have it in your picture. If you try to operate as it is in the picture the odds are high that you will fry the regulator on the Arduino depending on the output of the wall wart. You have a 5V power supply connected to the Vin connector, that does not work as it goes through the regulator and protection circuitry before getting to the processor. You need to power via the 5V pin with a 5V power supply. This can also be used to power your LEDs assuming they do not pull much over 1 amp. If you want to power by the connector, my preference, you need about 7.5 to 12 VDC. The additional filtering does not hurt and can only help. It also helps to protect from transients.

Thanks for taking the time to help me. So the vin is what it has built in and I need a different power supply module connected to the 5v pin?

Your 5V DC power supply should work on the +5V and power the arduino just fine. Be careful and do not connect backwards even for nanoseconds as there is no protection for that as there is on the Vin. An external DC power supply between 7.5V 12VDC will work. As you approach 12V and beyond on Vin the on board regulator will start getting hot, such things as Motors will overheat it. The protection circuit will allow you to power it externally while connected to the USB and your computer.


text:
''Wire1' was not declared in this scope' in I2C_MPU6886 library
I recently purchased a 6-axis IMU MCP6886 module by M5Stack. Product link: https://github.com/m5stack/M5-ProductExampleCodes/tree/master/Unit/IMU_Unit. The example code provided by the manufacturer is as follows:
#include "I2C_MPU6886.h"

I2C_MPU6886 imu(I2C_MPU6886_DEFAULT_ADDRESS, Wire1);

void setup() {
  Serial.begin(115200);
  delay(1000);

  Wire1.begin(21, 22);

  imu.begin();
  Serial.print("whoAmI() = 0x%02x\n", imu.whoAmI());
}

void loop() {
  float ax;
  float ay;
  float az;
  float gx;
  float gy;
  float gz;
  float t;

  imu.getAccel(&ax, &ay, &az);
  imu.getGyro(&gx, &gy, &gz);
  imu.getTemp(&t);

  Serial.print("%f,%f,%f,%f,%f,%f,%f\n", ax, ay, az, gx, gy, gz, t);

  delay(100);
}

When I run this code on Arduino IDE 1.8.19, I get the following error: 'Wire1' was not declared in this scope. I believe this issue is with the I2C_MPU6886 library itself, but I am not able to troubleshoot it. I am using an Arduino Uno R3 board and running the IDE on Windows 11.

What CPU are you using?

I am using an Arduino Uno R3 board -- so... not an M5Stack...? So why are you using M5Stack code...?

"M5Stack" is an ecosystem of ESP32 based boards and peripherals.
All code for M5Stack peripherals is written for the M5Stack system. Not for the Uno.
You have to find code for the Uno, not for the M5Stack. M5Stack code will not work on the Uno since it is a completely different system.