text:
Nano33 BLE SPI speed and lag
(This is a question re-posted here from the Official Arduino Forum to reach as many people as possible, I hope it is not against the rules)
Hi everyone,
although I am new to the forum I have been using Arduino for a long time. I have recently started working on a project using the Nano33 BLE.
I have searched the web for an answer to my problem (including this forum) but it seems I only get contracdtictory information.
I am taliking to an ADC (MCP3911) via SPI, the comms work fine but I have some issues:

The max SPI speed on 33 BLE seems to be 8Mhz, despite the fact that I have read in many places that is should be 32 MHz (1/2 of closk speed). Please see below a screenshot from a logic analyser (I have tried to lower it and it is fine, I can get lower speeds, but not higher):

There is a lag of ~ 19-26 us between each SPI.transfer() command, I had not seen this lag on AVR (I have used mostly the Nano Every for the same applicaiton, same code and same ADC). Below a screenshot of the logic analyser showing the lag between each SPI.transfer() (I am sending 4 bytes each time, the first is the address, then 3 bytes to read the value fro the MCP3911). Also, the lag is not always the same, it varies.

Has anyone have any ideas? Is there something hidden in the way Arduino implements the SPI from mbed?
In case you ask, here is the routine to read data from the ADC (I am using the library by Ruben J. Stadler):
long MCP3911::read_raw_data(uint8_t channel)
{
    digitalWrite(CS_PIN, LOW);
    SPI.transfer(ADDR_BITS | (channel << 1) | 1);

    byte upper = SPI.transfer(0x00);
    byte middle = SPI.transfer(0x00);
    byte lower = SPI.transfer(0x00);

    digitalWrite(CS_PIN, HIGH);

    return ((((long)upper << 24) | ((long)middle << 16) | (long)lower << 8) >> 8);
}

I appreciate your help, thanks!

this site is not a forum ... it is a question and answer site

I don't know the Nano 33 BLE, but there might be some interrupts from other high level routines kicking in from time to time.
Is the code you used to compare this board with the AVR equivalent? If you use BLE for example, I wouldn't be suprised seeing this kind of delay/jitter...

Hi, the code used on AVR is identical, what changes is the SPI API used. Doing a bit more research looks like this is the normal behaviour for nRF52840 with mbed SPI implementation. It seems the delay is due to the way mbed handles the buffers in the SPI and it takes that long to complete one transaction. Solutions proposed involve DMA or writing the buffers directly (bypassing the APIs), I have seen many people commenting on this for various platforms but unfortunately I am not expert enough to apply any of those solutions to the nRF52840...


text:
Problem compiling sketches for the arduino wavgat uno R33
I am configuring the arduino IDE to be able to compile and upload sketches for the arduino wavgat uno R3. I have installed the Arduino IDE, as well as the required drivers for the board. I also have downloaded the zip containing the "hardware" and "librairies" folder that i copied into the "Arduino" folder.
In the IDE, I can select the wavgat uno R3 as a board and the board is detected by the IDE.
However, when I try to compile any sketch, I get the following error message :
avr-gcc: error: C:\Users\henry\AppData\Local\Temp\arduino\sketches\F2EF7F804783EB75A0A6457CF6D8C244/core\core.a: No such file or directory

exit status 1

Compilation error: exit status 1

I seems to be a problem related to the compilation. Is there something related to the compilation for the wavgat uno R3 that I forgot ?
Thank you in advance

did you try to restart the IDE?

Yes, I even tried to restart the computer altogether.

The problem was solved by using a specific version of the arduino IDE, the 1.8.15. You have to install the drivers and copy the correct driver files in the Arduino folder. The program then compile correctly and can be uploaded to the wavgat.
Also, when working on the wavgat nano, you have to select "WAVGAT UNO R3" as the board type, and not "WAVGAT NANO 3.0" as you might first think.

source: Stack Exchange

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

sort: votes


text:
How to get around passing a variable into an ISR
Okay so you aren't able to pass a variable into in ISR. This is causing problems for me. I'm using a rotary encoder, and I need it to be connected to an interrupt pin and running a ISR. When using this method, no pulses are ever skipped and the knob works great.
Currently I have the ISR setup like this:
void vhISR()
{
  // this checks the PINE register for a 1 or 0 on the 5th bit (or 6th)
  // I'm bit shifting the result so that variable is either true or false for comparison, not 16/0 or 32/0
  rotCurrentA = (PINE & B00010000) >> 4;
  rotB = (PINE & B00100000) >> 5;

  if (rotCurrentA != rotLastA)
    {
      if (rotCurrentA != rotB) // cw
        {
          voltageHigh += knobResolution;
          rotLastA = rotCurrentA;
        }
      else // ccw
        {
          voltageHigh -= knobResolution;
          rotLastA = rotCurrentA;
        }
    }
}

The code simply varies voltageHigh by 0.1V increments. The problem is this: I need to do this same 0.1 variations on several other variables, depending on which one I select. I need to increase/decrease a voltageLow, a timer, and a resistance, all that need +/- 0.1 increments (but on different ranges. For instance, voltLow is somewhere between 0.1 & 5, and VH is somewhere between 6 & 10). Normally what I would do is just pass the variable I needed by reference into the function and have the function increment/decrement that variable....but an ISR is not a normal function and you cannot pass a variable into it.
How do I get around this? I'm not sure if that's enough information to go off of let me know.

why not use the Encoder library?

Not an option. This is working perfectly, aside from this small issue.

a switch statement based on a global variable with the current selected setting?

Don't change the variable in the ISR.  Just keep track of the number of clicks and add them to the appropriate variable in code.  You'd need to be turning off interrupts to use those variables anyway, so just replace that code with the read and modify.

I would follow Delta_G's advice, and write an ISR that counts the steps
and does nothing more. As a general rule, you want to do as little as
possible within an ISR. I would even avoid floating point and just count
the raw number of steps:
// Count of rotational steps updated in the ISR. Must be unsigned in
// order to avoid signed overflow, which is undefined behavior.
volatile uint16_t rotation_count;

void vhISR()
{
    static uint8_t rotLastA;
    uint8_t rotCurrentA = (PINE >> 4) & 1;
    uint8_t rotB = (PINE >> 5) & 1;

    if (rotCurrentA != rotLastA)
        return;
    if (rotCurrentA != rotB) // cw
        rotation_count++;
    else // ccw
        rotation_count--;
    rotLastA = rotCurrentA;
}

// Return the number of rotational steps since the last call. Should be
// called often enough to avoid overflowing an int16_t.
int16_t get_rotation()
{
    static uint16_t last_count;

    // Avoid a data race: rotation_count should not be modified while we
    // are reading it.
    noInterrupts();
    uint16_t count_copy = rotation_count;
    interrupts();
    int16_t delta = count_copy - last_count;  // this is signed!
    last_count = count_copy;
    return delta;
}

Note that the raw count is an unsigned number which can roll over modulo
216. The value returned by get_rotation(), however, is a
signed number which, owing to the rules of modular arithmetic, is
immune to the rollover of the raw count. As long as you call
get_rotation() often enough (more often than every 32767 steps),
the returned value will always be correct.
Then, in your main program, you can use this to update whatever variable
you want:
const float knobResolution = 0.1;
float voltageHigh, voltageLow, resistance;

// The variable that the user has selected for changing.
enum {VOLTAGE_HIGH, VOLTAGE_LOW, RESISTANCE} selection;

void loop()
{
    // Set a pointer to the selected variable.
    float *selected_var;
    switch (selection) {
    case VOLTAGE_HIGH:
        selected_var = &voltageHigh;
        break;
    case VOLTAGE_LOW:
        selected_var = &voltageLow;
        break;
    case RESISTANCE:
        selected_var = &resistance;
        break;
    }

    // Update the selected variable.
    *selected_var += get_rotation() * knobResolution;
}

Note here that the selection enum is probably redundant with
selected_var. You could use the latter to keep track of the user
selection, then you would not need the switch/case.

This is awesome! Thank you for typing it all out for me. I'll have to mull this over soon and implement once I understand everything. Thanks!

Okay so you aren't able to pass a variable into in ISR ...

Not as such, because the ISR is triggered by hardware, and therefore you don't pass arguments to it.
However there is nothing stopping you having a global variable which the ISR can access (preferably declared volatile) so the ISR can change its behaviour depending on what the global variable holds.

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


text:
ESP32 WiFi server.send(); is it exclusive to ESP328266 modules, Arduino?
Is the function server.send(); exclusive to ESP8266 modules, Arduino?  Where can I find documentation regarding the application of this function with an ESP32 module with WiFi?

the ESP32 HTTPServer library

For ESP32, the equivalent implementation is in the WebServer library.

Thank you for your response, much appreciated!


text:
Does ESP32 can support WIFIDirect
I would like to establish a simple P2P connection between an ESP32 and an Android device without the use of an access point. I should be able to send and receive data from the ESP32 through the established connection. Is this possible, and if not, are there any alternative solutions?

From my research i for to know that we can't use wifi direct for esp32 i found an alternative for my problem!!!!

can you maybe share your alternative ?

I do know that you can host a web page on an esp8266, sending and receiving data on that. You can from there connect the Android to that web page. I am not sure what you mean by access point, and I hope that this method is not using an access point.

Acccess point means router

so this approach should work?


text:
How to ignore garbage values in serial communication between arduino and python
I have arduino uno. I am trying to send and receive serial data from arduino to python. I have usb to uart converter. I have connected its tx to rx of Arduino and rx to tx of Arduino and gnd is connected to gnd. I have connected this usb to my laptop where I have written below python script:
import serial

ser = serial.Serial(port='COM6')

res = ser.read(10)
print(bytes.hex(res))
data = b"\x7E\x7E\xAA\x03\xAB\x77"
ser.write(data)

ser.close()

In above code, I am first reading the serial data, once the data is received, I sent out some hex packets. Below is the Arduino code:
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  const byte message[] = {0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03 };

  Serial.write(message, sizeof message);
  Serial.println("data sent");
  delay(1000);

  char buffer[6];
  if (Serial.available() > 0)
  {
    int size = Serial.readBytesUntil('\x77', buffer, 6);
    for (int i = 0 ; i < size ; i++)
    {
      Serial.println(buffer[i], HEX);
    }
  }
}

In above code, I am first sending out the hex packets (which is received fine on python side) and then it waits for serial data. Once serial data is available to read, it reads it unitll \x77 and prints out all data. This is received on serial console of Arduino:

You will notice that it has received the data but there are some extra FF being received. Why have we recived these FF. Also in the python code, we know we are sending data of length 6 so accordingly we have defined char buffer[6] in arduino but what if we have to receive data which we do not what length it will be. Please help. Thanks

How did you configure the serial port on the Python side? It is not done in the Python code itself.

@EdgarBonet Sorry I didn't get you by configuring the serial port. On the Python side, I have just mentioned the port number and thats it. About the hardware, its the same as mentioned in the question.

You cannot connect another USB-to-Serial converter on the same rx and tx pins. Serial ports cannot work in "parallel". Define a software serial using any other digital pins and connect your converter on those pins. The hardware rx and tx pins are already connected to the on-board "serial-to-USB" converter.

@Fahad I know and this is why when uploading the code, I need to remove the jumper wires rfom tx and rx pins. Once code is uploaded, I just press reset to start it again. Is that okay?

@SAndrew But you are still using the same pins for two serials! One is the onboard serial that you are watching on the Arduino IDE serial window (COM7) and one is in the python (COM6). That is a problem. Serials are not meant to be used as parallel buses.

@Fahad Thanks for your help. Using software serial is actually a good option.

The effect that you see is type promotion, in the C++ standard called "integral promotion", which happens implicitly. Values of type char are cast to int. Commonly, and in your case too, the char is by default signed.
The values 0xAA and 0xAB have a set most significant bit, which commonly designates a negative value in two's complement. This holds true for your case. And so these negative values are cast to the same negative values, but in full width of an int. In your case, an int has 32 bits.
Hex 0xAA as (by default signed) char is -86 decimal. And -86 decimal as (by definition signed) int is 0xFFFFFFAA hex.
Printed as hex, all bits are shown. So you see all these FF.
The solution is to mask only the interesting lower 8 bits:
    {
      Serial.println(buffer[i] & 0xFF, HEX);
    }

Good catch! Well, it's actually a bit more complicated: the char gets promoted to a 16-bit int by the overload resolution of Serial.println(), then explicitly casted to long by Print::print(int, int), then converted to unsigned long by the call to printNumber().

@EdgarBonet This issue happens a lot with beginners, and I had it many times already. :-D -- Thanks for going deep into the details! I feel the official Arduino documentation in the web as unsatisfactory, because I always miss the exact and complete prototypes. We should not have to look into the library source...

Thanks for your answer. Any idea why some of the garbage and random values are being received? Thansk

@SAndrew Which garbage and random values do you mean? I don't see any. Please post a new question if this is a separate issue, else edit your question.


text:
Program crashes when calling external library code via function pointer
I've written a user library for the Pi Pico that uses the TaskScheduler library to abstract timing away from the user. The user provides a function in their sketch which the library calls periodically via function pointer passed in the constructor.
When I stick to standard Arduino or functions from my library, everything works fine. If I include a function from the ADC library I'm using, core1 hangs while the comms on core0 continue to respond. If I run the same ADC operation from a non-callback function on the same core it works as expected. What is happening?
The relevant code snippets follow:
Library:
class Card {
public:
  typedef void (*ExtCbPtr)();  //pointer type to call sketch code from library
  ExtCbPtr _readCB;            //function pointer, points at user routine in sketch
  ExtCbPtr _writeCB;

  Card(ExtCbPtr readFunc, ExtCbPtr writeFunc); //constructor
private:
  Task readInputs;
  Task writeOutputs;
  Scheduler ts1;
};

Card::Card(ExtCbPtr readFunc, ExtCbPtr writeFunc) {
  this->_readCB = readFunc;    //use to call user's sketch code
  this->_writeCB = writeFunc;
}

void Card::begin() {
  //init scheduler tasks
  ts1.init();
  ts1.addTask(readInputs);
  ts1.addTask(writeOutputs);

  readInputs.setInterval(100);
  readInputs.setIterations(10);
  readInputs.setCallback(_readCB);
  writeOutputs.setInterval(100);
  writeOutputs.setIterations(10);
  writeOutputs.setCallback(_writeCB);
}

void Card::core1Loop() {
  ts1.execute();
}

Sketch:
static void writeOut();
static void readIn();
Card card(readIn, writeOut);
Adafruit_ADS1115 ads;  //ADC

void setup(){

rp2040.idleOtherCore();

//setup ADC
  if (!ads.begin()) {
    Serial.println("Failed to initialize ADS.");
  }
  ads.setDataRate(0x00E0);  //860 samples per second, every conversion takes ~1.2mS
  ads.setGain(GAIN_ONE);    //0.125mV/LSB

  card.begin();  //initialise
  rp2040.resumeOtherCore();
  Serial.println("Ready 0");
}

void setup1(){
  delay(1);
  Serial.println("Ready 1");
}

void loop1();
  card.core1Loop();
}

void readIn() {
  Serial.println("Read start");
  uint16_t adc =  ads.readADC_SingleEnded(0);  //problematic line
  Serial.println("Read end");
}

void writeOut(){
   //Doesn't matter, task not reached if read fails
}

Are interrupts involved? Try taking out the serial prints from the callback function.

Did you try a simpler sketch to verify the compatibility of the Adafruit_ADS1115  readADC_SingleEnded(0) method with Scheduler?

I spent three hours on this yesterday. Come in today, turn the system on, and everything works. PEBKAC?


text:
arduino nano fried (TWICE!!)
Having the skill to be stupid has managed to fry not one but 2 Arduino nano boards in the same place (I think it is because this part that smoke came out from of has a lump on it that was not there before). I have heard that Arduino boards are open source, but I have not found anything explaining which part I have fried. Therefore, I don't know the function, so I cannot replace it. It would be greatly appreciated if anyone could point out the part name or a link to a shop with it in stock so I could purchase it or give me a copy of the PCB schematics to make my own Arduino.
I think the part is called the "usb diode"
Thanks

what exactly is your question?

is there a way to fix it without getting a new one?

From the several Arduino Nano schematics I've found, the "fried" part you identify as the USB diode, might be a MBR0520 Schottky diode or a similar diode with a low forward voltage drop. These parts are polarized and should be replaced in the same orientation as the original part.
There is no guarantee that this is the only damaged component on your Nano.

would the anwser change if i mentioned that this is an arduino clone

The clones that I've found schematics for, have similar Schottky diodes. Still, no guarantees.

somehow, one still works! I don't know how, and don't want to question it!


text:
What wrong with my Arduino code?
I have a rotary encoder (ppr = 600) and I want to write code to achieve the implementation to read current angle and direction.
Here is my code. I think it is correct but it donot have any output on the serial monitor.
#include <Servo.h>

// Rotary Encoder Connections
int encoderPinA = 2;  // Connect the CLK pin of the encoder to digital pin 2
int encoderPinB = 3;  // Connect the DT pin of the encoder to digital pin 3

// Variables
volatile int encoderPos = 0;   // Current position of the encoder
volatile int lastEncoderPos = 0;  // Previous position of the encoder
int clockwiseSteps = 0;  // Total clockwise steps turned
int counterclockwiseSteps = 0;  // Total counterclockwise steps turned
int latestOperation = 0;  // Latest rotation operation (1 for clockwise, -1 for counterclockwise)
int degreesPerStep = 360 / 600;  // Degrees per step for a 600-pulse rotary encoder
int aLastState = digitalRead(encoderPinA); // Default state of Pin A

void setup() {
    // Set encoder pins as inputs
    pinMode(encoderPinA, INPUT_PULLUP);
    pinMode(encoderPinB, INPUT_PULLUP);

    // Attach interrupts to the encoder pins
    attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
    attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);

    // Initialize Serial communication
    Serial.begin(9600);
}

void loop() {
    // Print the total degrees turned in both directions
    if (encoderPos != lastEncoderPos) {
        int rotation = encoderPos - lastEncoderPos;
        if (rotation > 0) {
            clockwiseSteps += rotation;
            latestOperation = 1;
        } else {
            counterclockwiseSteps += rotation;
            latestOperation = -1;
        }
        lastEncoderPos = encoderPos;

        int currentAngle;
        if (latestOperation == 1) {
            currentAngle = (clockwiseSteps - counterclockwiseSteps) * degreesPerStep;
            Serial.print("CW | ");
        } else {
            currentAngle = (clockwiseSteps - counterclockwiseSteps) * degreesPerStep;
            Serial.print("CCW | ");
        }
        Serial.println(currentAngle);
    }
}

void updateEncoder() {
    int aState = digitalRead(encoderPinA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
    if (aState != aLastState){
   // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(encoderPinB) != aState) {
       encoderPos++;
     } else {
      encoderPos--;
     }
   }
   aLastState = aState; // Updates the previous state of the outputA with the current state
 }

Why there is no output? Seem like the interrupt function not working. How to fix it?

Can you add the exact type of your rotary encoder (and the link to a datasheet, if you can find it)? Because your code reads a "raw" rotary encoder, but the pin names CLK and DT in your code comment suggest that the encoder rather speaks something like SPI. Also, all variables declared outside and used inside an interrupt handler should be declared volatile. aLastState does not have this flag.

We definitely need to know the part number of the rotary encoder and a link to the datasheet, or at least more information about it.

@NickGammon I update the information in the text

@orithena I modify int to volatile int, but still not work

I just got this information from my teacher.

This is a "raw" rotary encoder with open collector output, so INPUT_PULLUP should be right. Let's debug "no output at all". Add in your setup() after Serial.begin(9600): delay(100); Serial.println("----- Hello -----");. If this is not printed on the Serial Monitor when you press the reset button, you probably have the wrong baud rate (i.e. not 9600) set in your Serial Monitor. If that works, add a simple volatile counter variable, increased unconditionally on each interrupt and printed unconditionally in each loop(). If this does not increase, there's something wrong with the wiring.

You can also remove the encoder and manually connect and disconnect the interrupt pins to/from ground. This will take the characteristics of the encore out of the equation.

Add in your setup() after Serial.begin(9600): delay(100); Serial.println("----- Hello -----"); - so what happened when you did that? Please edit the question to describe.

Your tag Arduino-Uno is completely contradicted by your photograph showing a Arduino Mega 2560. Please edit the tags and get that part right. Also, you did not mention the part number of the encoder.

Since the interrupt routine only does anything if the A pin has changed, the second attachInterrupt line is not needed.  You don't need an interrupt for the B pin if you aren't going to react to changes on the B pin.

int degreesPerStep = 360 / 600; This integer division resolves to 0. Use a float datatype instead of int. If this solves the problem then create an answer showing the code changes you made.

if (encoderPos != lastEncoderPos). This may cause sporadic problems. encoderPos is a 16 bit int. Your Mega is an 8 bit processor. If the interrupt comes during the time that this variable is read in the loop, the variable may be corrupted by the write operation in the interrupt handler. To eliminate that risk, use an noInterrupts()/interrupts() block to make a copy of encoderPos. (topic: non-atomic read operation. Note that this  is not the same as declaring the variable as volatile which signals the compiler not to retain possibly stale versions of the variable )


text:
Speedometer for car
I want to build a speedometer for a car using Arduino UNO.
For the display, I'm using an LCD screen that will be located behind the steering wheel.
For context, I'm building the speedometer for a Tesla, which does not have a speedometer behind the steering wheel.
Because this speedometer is for a car, and for driving purposes, I need the speedometer to be very accurate.
I am planning to calculate the current speed of the car using a GPS module, but not sure which GPS module would have the best accuracy but is not too expensive?
I am also open to other methods that may be available to measure current speed.

An interesting project. I will not vote, but since there is no mention of an Arduino, likely people will vote to close this question as off topic. As for GPS, most inexpensive modules will only be accurate to about +/- 10 meters and only work (well) w/a clear view of the sky. Some will calculate bearing and speed for you (i.e. likely all you have to do is pluck this data out of the stream of data coming out of the GPS). Before investing time building this, consider using an old Android phone & an application which reports the data of interest to you.

For me, it would make more sense to read the speed from CAN

I built a GPS speedometer for an old Corvette using the TinyGPSPlus library with a GY-NEO6MV2 NEO-6M with an Arduino Uno.
http://www.carols62.com/speedo
Speed readings were very accurate.

hey thanks, this seems like exactly what I need!


text:
My Led blinks rapidly at the reset and stop blinking instantly
So ive been trying to make a program to test if the pins are working correctly but all it does is make my led blink rapidly on reset. the point of the program is that all my pins are connected to the same led, so blink each one of them once and send the number of the blinked pin to the serial.
but the led just doesnt blink and the program gets stuck at the start of pwmoutputtest.

boolean byteinarray(byte array[], byte pbit){
  for(int i=0; i<6; i++){
    if(array[i]==pbit){
      return true;
    }
  }
  return false;
}

void outputtest(){
  for(byte i=2;i<13;i++) {
    pinMode(i, OUTPUT);
  }

  for(byte i=2;i<14;i++){
    if (byteinarray(pwm, i)==false){
      Serial.println(i);
      digitalWrite(i, HIGH);
      delay(1000);
      digitalWrite(i, LOW);
      delay(1000);
    }
  }
}

void analogoutputtest(){
  for(byte i=0;i<5;i++) {
    pinMode("A"+i, OUTPUT);
  }

  for(int i=A0;i<A5;i++){
    Serial.println(i);
    digitalWrite(i, HIGH);
    delay(1000);
    digitalWrite(i, LOW);
    delay(1000);
  }
}

void pwmoutputtest (){
  for(int i=0; i<6; i++) {
    pinMode(pwm[i], OUTPUT);
  }

  for(int i=0; i<6; i++) {
    Serial.println(pwm[i]);
    for(int j=0; i<200; i++){
      analogWrite(pwm[i], j);
      delay(5);
    }
    analogWrite(pwm[i], 0);
  }
}

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

void loop() {
  outputtest();
  pwmoutputtest();
}```

You have connected all the pins together. Then you are setting one pin HIGH (5V) at a time while all others are LOW (0V, aka ground).
So basically you are creating a short each time you set a pin HIGH. The current won't flow through the LED to ground (which would light up the LED), but the current flows through the pins, that are LOW, to ground. And since you didn't mention any current limiting resistors, you are straining the pin output hardware with this massively. If you do this too much, the pin output hardware will fail at some point, making the pin unusable for digital IO.
Instead of keeping the other pins LOW, you need to keep them at high impedance , which means configuring them as INPUT. That would be a function like this (not tested):
void outputtest(){
  for(byte i=2;i<13;i++) {
    pinMode(i, INPUT);
  }

  for(byte i=2;i<14;i++){
    if (byteinarray(pwm, i)==false){
      Serial.println(i);
      pinMode(i, OUTPUT);
      digitalWrite(i, HIGH);
      delay(1000);
      digitalWrite(i, LOW);
      pinMode(i, INPUT);
      delay(1000);
    }
  }
}

tysm i hope i didnt break anything

@Lucas If you think this answered your question, then you can accept my answer to mark your question as solved


text:
Receive data from ESP32 with HTTPClient
I need to receive data from sensors on the websites located on my PC (hosted with XAMPP).
When I was first using AsyncWebServer library and hosting them on ESP32 everything was working with a combination of those two:
response = String(digitalRead(button1)) + "," +String(digitalRead(button2)) + "," +
                String(digitalRead(button3)) + "," +String(digitalRead(button4)) + "," +
                String(angleX) + "," + String(angleY) + "," +
                String(sensor1value);

server.on("/state", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send(200, "text/plain", response);
  });

and:
setInterval(function ( ) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            var Answer = this.responseText;
            console.log(Answer);
            let values = Answer.split(',');
            document.getElementById("led1").style.backgroundColor = (values[0] == 0) ? 'green' : 'red';
          }
        };

        xhttp.open("GET", "/state", true);
        xhttp.send();
      }, 100 ) ;

JS script was linked on dashboard.html page and changed the appearance of elements on it according to the values.
Now I need the same result with HTTPClient
String serverName = "http://192.168.0.20/glove/state.html";

/*response = String(digitalRead(button1)) + "," + String(digitalRead(button2));*/

response = "?button1=" + String(digitalRead(button1)) +  "&button2=" + String(digitalRead(button2));

/*response = "button1=" + String(digitalRead(button1)) +  "&button2=" + String(digitalRead(button2)); */

    WiFiClient client;
    HTTPClient http;

    //String serverPath = serverName + response;
    String serverPath = serverName;
    //Serial.println(serverPath);
    http.begin(client,serverPath);

    http.addHeader("Content-Type","application/x-www-form-urlencoded");
    //http.addHeader("Content-Type","text-plain");
    //http.POST(response);
    int httpCode = http.GET();
    //Serial.println(response);

    //int httpCode = http.sendRequest("POST",response);
    Serial.println(httpCode);

But I can't get it to work (was trying different combinations with GET and POST methods).

Why do you use /glove/state.html in the new client instead of just/state?

Please, show your attempt at using POST, as this is the relevant HTTP method. Are you sure you have WiFi connectivity? Are you able to send the data to your XAMPP server manually with either curl or HTTPie? Can you capture the HTTP dialog with a network sniffer? Could you show us the on-the-wire requests, both a successful (with curl or HTTPie) and an unsuccessful one (with your HTTPClient code)? Comparing them should tell you what is going wrong.

I've written a set o ESP32 libraries. One of them is for a web server. Check it out here: https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries#readme . ilnd "routes.cpp". Hope it helps

@PeterPaulKiefer because with old library there was no additional file called "state" (or state.html or whatever) - it was declared in that server.on. When i tried using only "/state" with new library i was getting error that  there is no file/page with that name (so i created state.html)

@EdgarBonet i think i had connection with my xampp server, because when i was serial printing response status code i was getting 200 (or some error ones depending on my changes in code)


text:
Sim800l doesn't respond to AT commands
My SIM800L doesn't respond to AT commands. The serial monitor is simply blank.
And the led blinks every 3 seconds which means it is connected to a network
I power it through an LM2596 buck down converter with 4.0 v (I've tried to power with voltages until 4.4v), From a 12v power supply.
Can you help me?
(Please keep in mind that I'm an absolute beginner in this field. Thanks)
I used this wiring diagram from Last Minute Engineers.

And also their code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup() {

    Serial.begin(9600);

    mySerial.begin(9600);

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

    delay(1000);
    mySerial.println("AT");

    updateSerial();

    mySerial.println("AT+CMGF=1");

    updateSerial();

    mySerial.println("AT+CNMI=1,2,0,0,0");

    updateSerial();
}

void loop()

{
    updateSerial();
}

void updateSerial() {

    delay(500);

    while (Serial.available()) {

        mySerial.write(Serial.read());
    }

    while(mySerial.available()) {

        Serial.write(mySerial.read());
    }
}

Check the Tx and Rx wiring carefully. Do the Arduino Tx and Rx LEDs blink?

Yes. I used the same wiring diagram with a GPS module (minus the resistors) and it worked fine


text:
How do I set the DHCP pool for an ESP-WIFI-MESH?
I'm building a mesh with ESP32 dev kits (ESP32-DevKitC V4) using the ESP-IDF VS Code extension and the ip_internal_network example project. The code for the example, common project components, and the API is linked. When the mesh nodes power on and build the network, they use the 10.0.0.0 network. How do I change the internal mesh network?
My operating assumptions:

The root node receives an external IP address from an external DHCP
server.
The root node acts as an internal DHCP server to the mesh nodes.
The root node performs network address translation.
Its DHCPv4 server runs on the lwIP TCP/IP stack.
Internal IP addresses are leased from a pool governed by the root
node (but it's possible that nodes request a particular address from
this network and the server provides the next available; I'm unsure).
The network address is 10.0.0.0/8 (I inferred the subnet mask; it
could be anything).

Obviously, the first thing I tried was searching for this network address in files. There was nothing in the project workspace and too many hits in the repo to be useful. I tried decimal and hex with no luck.
I also tried tracing the function that prints the IP address to the serial terminal to find the IP var, and working backwards to locate the statement that initializes this variable. I'm still reading event handler API documentation so I haven't made quick progress here either.
The programming interface is split among ESP-IDF component header files, build systems (CMake and Ninja?), KConfig options and host tools (idf.py?). C, FreeRTOS and build systems are all new to me so I would appreciate if someone with more experience could weigh in. Thank you.

I figured it out; it's in mesh_netif.c:43. I'm not sure why I passed over this file initially but it caused a lot of unnecessary headache. The relevant struct is this:
const esp_netif_ip_info_t g_mesh_netif_subnet_ip = {
    .ip = { .addr = ESP_IP4TOADDR( 192, 168, 0, 1) },
    .gw = { .addr = ESP_IP4TOADDR( 192, 168, 0, 1) },
    .netmask = { .addr = ESP_IP4TOADDR( 255, 255, 255, 0) },
};

I changed the 10.0.0.0/16 network to 192.168.0.0/24. The root node assumes the address in .ip. I assume child nodes check the ARP table and increment until an address is available, then send the DHCPREQUEST for that address to root. I say "assume" because although root runs lwIP, I am not sure child nodes run lwIP (they may just communicate in layer 2 ESP-WIFI-MESH frames).
Make sure your DHCP server publishes an IPv4 DNS address or ESP_ERROR_CHECK(esp_netif_set_dns_info(netif, ESP_NETIF_DNS_MAIN, &dns)) (mesh_netif.c:70) will fail and cause the board to power cycle. A way around this is to enable Use global DNS IP in menuconfig. The global DNS field is in hex format, so 10.32.64.128 is written 0x0A204080.
Mesh-internal IP messages are published with MQTT so the name/address .broker.address.uri in mqtt_app.c:74 must be accessible from the router.


text:
does ATtiny85 handles the size of the libraries mentioned below `<MD_Parola.h>` and `<MD_MAX72xx.h>`
The ATtiny85 microcontroller has very limited resources, including program memory (flash) and RAM. It has 8KB of flash memory and only 512 bytes of RAM.
does ATtiny85 handles the size of the libraries  mentioned below
<MD_Parola.h> and <MD_MAX72xx.h>
what microcontroller would you recommend?
https://www.arduinolibraries.info/libraries/md_max72-xx
https://reference.arduino.cc/reference/en/libraries/md_parola/

Can you at least please give a link to the libraries you mention? Are you expecting us to Google for where they are and then read all the documentation for them? Asking for recommendations is a bit broad. It depends. What else are you trying to do? What are your price constraints? A quick Google search indicates the libraries do not mention what processor they target, so it is hard to answer. Just as a guess (and this is a guess) they probably are for the larger processors like the Atmega328P.

Thank you @NickGammon for the quick response. Please  find the docs reference of the library and I will check Atmega328P
https://reference.arduino.cc/reference/en/libraries/md_parola/
https://www.arduinolibraries.info/libraries/md_max72-xx

It is very simple to test.

Install the ATTinyCore in IDE
Install the MD_Parola library in Library Manager. It will install the MD_MAX72xx library too
Go to IDE Examples menu, search for the MD_Parola library examples and select the Parola_HelloWorld example
select the ATTiny85 in the Tools menu
hit Verify

output:
avr/bin/ld: region `text' overflowed by 11820 bytes
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board ATtiny45/85 (Optiboot)

which means it will not fit.
If you select Arduino Uno in the Tools menu and Verify you get:
Sketch uses 20692 bytes (64%) of program storage space. Maximum is 32256 bytes.
Global variables use 288 bytes (14%) of dynamic memory, leaving 1760 bytes for local variables. Maximum is 2048 bytes.

thank you @Juraj !!!I will consider Atmega328P


text:
Internet in ESP32 is not working with IPv6
I am using ESP-WROOM-32D in STA mode with Arduino IDE(2.0.5) ESP32 board(2.0.9).
I am trying to do http post request with ESP32. Router that provides internet supports only IPv6.
Here I am getting http code -1. I have tried different network with IPv4 which works fine and returns 200.
So my question is do I need to enable something to make this work ? I have used WiFi.enableIpV6(); and got IPv6 IP also.
void setup() {

Serial.begin(115200);
  delay(2000);
  WiFi.onEvent(WiFiEvent);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.println(".");
  }
  Serial.println("wifi connected");
  delay(2000);

  HTTPClient http;
  http.begin("https://www.google.com/");
  int httpCode = http.GET();
  Serial.printf("HTTP code: %d\n", httpCode);
  http.end();
}

void loop() {

}

void WiFiEvent(WiFiEvent_t event) {
  switch (event) {
    case ARDUINO_EVENT_WIFI_STA_CONNECTED:
      Serial.println("Enabling IPv6");
      WiFi.enableIpV6();
      break;
    default:
      break;
  }
}

This is the debug message I got
[     4][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
[  2053][D][WiFiGeneric.cpp:1035] _eventCallback(): Arduino Event: 0 - WIFI_READY
[  2144][D][WiFiGeneric.cpp:1035] _eventCallback(): Arduino Event: 2 - STA_START
[  2313][D][WiFiGeneric.cpp:1035] _eventCallback(): Arduino Event: 4 - STA_CONNECTED
Enabling IPv6
.
[  2620][D][WiFiGeneric.cpp:1035] _eventCallback(): Arduino Event: 7 - STA_GOT_IP
[  2620][D][WiFiGeneric.cpp:1098] _eventCallback(): STA IP: 192.168.1.3, MASK: 255.255.255.0, GW: 192.168.1.1
.
wifi connected
[  4035][D][WiFiGeneric.cpp:1035] _eventCallback(): Arduino Event: 8 - STA_GOT_IP6
[  4774][D][HTTPClient.cpp:263] beginInternal(): unexpected protocol: https, expected http
[  4775][D][HTTPClient.cpp:303] beginInternal(): protocol: https, host: www.google.com port: 443 url: /
[  4781][D][HTTPClient.cpp:598] sendRequest(): request type: 'GET' redirCount: 0

[  5035][D][WiFiGeneric.cpp:1035] _eventCallback(): Arduino Event: 8 - STA_GOT_IP6
[  9829][I][ssl_client.cpp:112] start_ssl_client(): select returned due to timeout 5000 ms for fd 48
[  9830][E][WiFiClientSecure.cpp:144] connect(): start_ssl_client: -1
[  9833][D][HTTPClient.cpp:1163] connect(): failed connect to www.google.com:443
[  9840][W][HTTPClient.cpp:1483] returnError(): error(-1): connection refused
HTTP code: -1
[  9858][D][HTTPClient.cpp:408] disconnect(): tcp is closed

Did you find an answer? I'm having this issue now, and it's pretty much what you're describing.

They said it is pending from the development. It will be solved in ESP 3.0 version. Follow this roadmap for update : https://github.com/orgs/espressif/projects/3/views/14. There are other alternatives on there GitHub page but are quite complicated. You can dig into that, I didn't.


text:
connecting 4 scales to microcontroller for use as dog force plate
I want to build a system to measure the force distribution between the 4 legs of a dog. I plan to use this method:
http://www.rehabtools.org/scales.html
This setup seems to be for 1 scale. I want to use 1 scale for each leg, so that adds up to  4 scales. I assume I need 4 amplifiers, but can I connect those 4 to one microcontroller?
I currently have the Arduino Uno coming, will that work?
The connection from the 4 legs of the scale to the load amplifier I understand. But how do I go about having the 4 readings and then getting them in the software program?
Any advice would be greatly appreciated.

use the search terms arduino load cell in your research

If you follow the links in the tutorial you linked to, you will find

this library for interfacing the HX711 load-cell amplifier

this example sketch for reading the scale

The library uses a bit-banging method (pulseIn()) for communicating
with the amplifier. This method can work with any of the Arduino
digital pins. In the example sketch you have the instantiation:
HX711 scale(3, 2);

where the numbers (3, 2) tell the library the pins you want to use.
Given all this, you should be able to interface four identical scales
simply by using four separate pairs of pins. For example:
HX711 scale1(3, 2);
HX711 scale2(5, 4);
HX711 scale3(7, 6);
HX711 scale4(9, 8);

The adapt the example sketch to read all the scales.


text:
Which temperature sensor is accurate?
I have an Arduino Nano RP2040 Connect with two temperature sensors. A DHT22 is connected to D2 and pulled up with a 5 kΩ resistor to 5V, and a LSM6DSOX IMU is built in to the board. Here's my code:
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Arduino_LSM6DSOX.h>

#define DHTPIN 2
#define DHTTYPE    DHT22

DHT_Unified dht(DHTPIN, DHTTYPE);

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

void loop() {
  delay(1000);

  sensors_event_t event;
  dht.temperature().getEvent(&event);
  Serial.print(F("DHT22: "));
  Serial.print(event.temperature);
  Serial.print(F("°C and "));

  float temperature_float = 0;
  IMU.readTemperatureFloat(temperature_float);
  Serial.print("LSM6DSOX: ");
  Serial.print(temperature_float);
  Serial.println(" °C");
}

When I run it, I get this in the serial monitor:
DHT22: 24.50°C and LSM6DSOX: 28.94°C

Why is there such a large difference (4.5°C/8.1°F) between the sensors?

Your 1st stop should be the specification sheets for the two parts.  You should find the STMicro accelerometer spec sheet at st.com.  I'm not sure about the DHT22.  Since I've had my share of problems with the DHT22, I'd look else where.  But that's just personal preference.

Also, where is the accelerometer?  If it's buried next to heat generating parts then it may not reflect ambient temperature.  Remember, the accelerometer needs its temperature to compensate for its own acceleration sensors.  Not for telling you what the ambient temperature is.

you title question cannot be answered without knowing the ambient temperature ... you can answer it yourself anyway


text:
How can I get the serial monitor in vs code to automatically connect and disconnect when uploading to my arduino?
I am using an Arudino Nano with VS Code and PlatformIO.
When developing. I want to streamline the process so that when I press 1 hotkey.
It will automatically disconnect the Serial Monitor. Build. Upload. Then reconnect the Serial Monitor.
I can partially do it with the "Upload and Monitor" project task:

However, it connects to the serial via the Terminal which means I can't send commands like I do with the serial monitor:

If I connect the serial monitor manually. It does not automatically disconnect so that it can do the upload.
How can I set up vs code with platform io to build, upload, and reconnect the serial monitor with a single hotkey?
Edit:
I managed to get the terminal to allow sending input by adding:
monitor_echo = on

monitor_filters = send_on_enter

To platformio.ini, but it messes up if you try to edit the message with backspace and it does not repeat the last message by pressing the up arrow key like the Serial Monitor tab does.


text:
16 bit PWM on Nano Every
I need to drive a LED strip via MOSFET module. The module needs a high resolution PWM for very dim conditions. How can I set my pin to a 16 bit PWM resolution on an Arduino Nano Every?

It's possible for D5 (TCA0-WO2) + D9 (TCA0-WO0) + D10 (TCA0-WO1) all three of them will be 16bit if you change TCA0 top value, but you can't use analogWrite.
void setup() {
  // change period of TCA0 (already configured and started by arduino core)
  TCA0.SINGLE.PER = 0xFFFF; // change top value from 255 to 65535

  // set PWM value of D9 (channel 0)
  TCA0.SINGLE.CMP0 = 0; // initial value
  // enable PWM output (needed only once in setup)
  pinMode(9, OUTPUT); // setup pin as an output
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP0EN_bm; // enable pwm->pin

  // D5
  TCA0.SINGLE.CMP2 = 1; // initial value
  pinMode(5, OUTPUT);
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP2EN_bm;

  // D10
  TCA0.SINGLE.CMP1 = 65530; // initial value
  pinMode(10, OUTPUT);
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP1EN_bm;
}

and in the code you'll use only TCA0.SINGLE.CMPn = val; where n is 0..2
(untested, but should be working)
EDIT: I forgot the period will be 3.8Hz, so you'll need to change also TCA0 prescaller or use smaller precision like 10b or so. Changing prescaller will mess up the all the TCB counters periods along with the one used for millis counter so you'd need also change that
EDIT2: for classic UNO/nano it'll look like this:
TCCR1B = 0; // stop timer

ICR1  = 0xFFFF; // f = 16MHz / (2*N*ICR1) = 16MHz / (2*65536) => ~122Hz
OCR1A = 1;             // PB2 -> D9  (PWM value)
TCCR1A = _BV(COM1A1);  // enable PWM output on PB2
TCCR1B = _BV(WGM13) | _BV(CS10);  // mode=8 (phase and freq correct, ICR1 as top) and start timer with prescaller /1

Thanks for the detailed code. Will try these days. I used an analogWrite function on the Uno, which wrote uint16_t to OCR1A (pin9). Is this still the same?

No, classic uno/nano (with Atmega328) has different settings for timer1 - but on the other side it has independent prescaller, so you won't break anything.

@awado added changes for classic uno (pinMode omitted)

Thanks again for your help KIIV. I can confirm it works. This an example of a low light PWM for an LED on Pin 10. Maybe it helps others.
int brightness = 0;  // how bright the LED is
int fadeAmount = 1;  // how many points to fade the LED by

void setup() {
  TCA0.SINGLE.PER = 0x4000;
  TCA0.SINGLE.CTRLA = TCA_SINGLE_CLKSEL_DIV16_gc | 1 << TCA_SINGLE_ENABLE_bp
  TCA0.SINGLE.CMP1 = 65530; // initial value
  pinMode(10, OUTPUT);
  TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP1EN_bm;
}

void loop() {
  // set the brightness of LED pin:
  TCA0.SINGLE.CMP1 = brightness;

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 64) {
    fadeAmount = -fadeAmount;
  }
  // wait to see the dimming effect
  delay(50);
}


text:
Arduino NANO RF reciever and Digispark Attiny 85 transmitter issues
I am trying to send RF signal from Digispark Attiny 85 (this one) and receive the signal with Arduino NANO V3.0 ATmega328 (this one). Transmitter and receiver are STX882 and SRX882 (these). Library used is RCSwitch.h.
The goal is to light up the external LED connected to NANO when I press the button connected to Attiny.
I am not skilled in Arduino stuff, but I have really tried to figure this one out on my own and find answers online. Sorry if this question does not belong here. Anyways, here is the problem:
// NiceRF 433MHz reciever SRX887

#include <RCSwitch.h>

RCSwitch reciever = RCSwitch();

void setup() {
  Serial.begin(9600);
  reciever.enableReceive(2);
  pinMode(7, OUTPUT);
}
void loop() {
  if (reciever.available()) {
    int size = reciever.getReceivedValue();
    if (size == 0) {
      Serial.print("Unknown message"); //probably kinda useless line
    }
    else {
      digitalWrite(7, HIGH); // Turn on the LED
      delay(1000); // Wait for 1 second
      digitalWrite(7, LOW); // Turn off the LED
      delay(1000); // Wait for 1 second
    }
    // reset of module to be able to recieve next message
    reciever.resetAvailable();
  }
}

I understand the code like this: The Receiver will check if it receives anything and if so, it will light up pin 7 and therefore the LED connected to the pin 7 will be on.
Now for the Digispark Attiny 85 transmitter:
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  pinMode(1, OUTPUT);
  mySwitch.enableTransmit(2);
}

void loop() {
    mySwitch.send("000110110001010100010001");
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
}

I found this piece of code online and did not modify it. If I understand this correctly, it is not important, what the message is, but if it is sent at all. The receiver should light an LED up in every time it receives the signal.
I am confident that the wires are connected correctly.
Do you have any idea why this setup does not work?

Edit: As @jsotola suggested, I tried to make a circuit that will simply send HIGH signal to transmitter module, receive this signal at receiver module and if arduino board recognises that there is HIGH signal coming from receiver, it will send HIGH signal to the LED pin and LED would light up.
For this experiment, I switched Digispark for generic Arduino UNO ATmega clone to make things simpler. There is no library used in this example.
TRANSMITTER CODE:
const int TPin = 10;

void setup() {
  // Initialize the LED pin as an output
  pinMode(TPin, OUTPUT);
}

void loop() {
  // Turn on the LED
  digitalWrite(TPin, HIGH);
  delay(500); // Wait for 1 second

  // Turn off the LED
  digitalWrite(TPin, LOW);
  delay(500); // Wait for 1 second
}

RECEIVER CODE:
// Pin connected to the LED
const int ledPin = 7;
// Pin connected to input signal
const int inputPin = 2;

void setup() {
  // Initialize the LED pin as an output
  pinMode(ledPin, OUTPUT);
  // Initialize the input pin as an input
  pinMode(inputPin, INPUT);
}

void loop() {
  // Read the state of the input pin
  int inputState = digitalRead(inputPin);

  // Check if the input pin is HIGH
  if (inputState == HIGH) {
    // Turn on the LED
    digitalWrite(ledPin, HIGH);
  } else {
    // Turn off the LED
    digitalWrite(ledPin, LOW);
  }
}

TRANSMITTER SETUP:

(note that there is an antenna soldered to the transmitter module, but it is out of frame) The LED is simply for me to see when a signal is send to the transmitter. (Blinks in intervals as intended)
RECEIVER MODULE SETUP:
Pins on receiver from left to right (form orange to green wire) are GND, CS, DATA, VCC.
GND and CS are connected to the GND pin on Nano, VCC is connected to the 5V pin on Nano (this receiver works on 5V and does not require the usual ~3.3V). DATA is connected to the D2 pin on Nano.

The LED is simply connected to GND and pin D7 on Nano (out of frame) and does light up even if I touch the pin. LED stays off when D2 is grounded.
This setup does not work correctly and I have tried it for different Receivers/Transmitters (i have multiple of each). Once again thank you for all your suggestions. Does anyone have any idea what do I do wrong in here?
Thanks!

If you open the serial monitor what do you see?  Is it printing "Unknown message"?

you have not said that you verified the LED ... start with that ... write simple code that blinks the LED

the two radio modules act as a wire ... set the output data pin high and the receiver data pin should follow ... write a simple sketch to "blink" the output every second ... write a simple sketch to light an LED when receive pin is high, turn off LED if the pin is low

Thank you all for help. @Delta_G when i open the correct (9600) serial monitor, I do not see anything. If I try to SerialPrint any other message paralel to the RF transmit code it does work and print the test message.

@jsotola I am sorry that I did not mention it before, but the LED is checked and works correctly. About your other comment: I have tried to make a new circuit, that will just "blink" every second as you have described. However, I does not work and reciever does not recognise any sent signal. I will post new code and photos in the original post.


text:
Watchdog don't work with Atmega328PB
I have a code that is working fine using WatchDog timer to auto reset in case something goes wrong, but now i got a arduino with ATMega328PB, and the old code just don't active the watchdog.
#include <avr/wdt.h>

wdt_enable(WDTO_8S);
for(int i = 0; i < 10; i++)
{
    delay(1000);
}

This is the code to test, but the reset that should happen just doesn't happen.
In the datasheet say that the watchdog still there to use, but i have no idea how to active it now.

have a look at some of the tutorials that are available on the web

I didn't find no tutorials for the 328PB model

section 15.8 of https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega328PB-Automotive-Data-Sheet-40001980B.pdf

I already saw the example in the datasheet, but I couldn't compile it, is there any other option?

couldn't compile it ... what does that mean? ... what error did you get?

For example __watchdog_reset(); there are 3 functions that I don't know how to replace or implement to keep the code functional, and there is also how to set the watchdog time


text:
I am trying to control 4 servos with a joystick, but after a few seconds, they start spinning and don't stop until the power source is cut
Here's my code. I don't know if the issue is the power source though. I only have access to my computer for a power source.
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int joyX = A2;
int joyY = A5;
int Joyx = A2;
int Joyy = A5;

int servoVal;

void setup()
{
  servo1.attach(A0);
  servo2.attach(A1);
  servo3.attach(A3);
  servo4.attach(A4);
}

void loop()
{

  servoVal = analogRead(joyX);
  servoVal = map(servoVal, 0, 1023, 0, 180);
  servo1.write(servoVal);
  delay(15);

  servoVal = analogRead(joyY);
  servoVal = map(servoVal, 0, 1023, 70, 180);
  servo2.write(servoVal);
  delay(15);

  servoVal = analogRead(Joyx);
  servoVal = map(servoVal, 0, 1023, 0, 180);
  servo3.write(servoVal);
  delay(15);

  servoVal = analogRead(Joyy);
  servoVal = map(servoVal, 0, 1023, 70, 180);
  servo4.write(servoVal);
  delay(15);
}

If you think it is a current limitation problem (power) try only controlling 1 servo (disconnect the other servos).  Also check you are using common servos and not continuous servos.

how are the joysticks connected? ... your code indicates that you may be shorting out your power supply

Why are you reading twice from each joystick acis (since joyx and joyX are defined with the same pin)?

... Ah! Nice catch @chrisl.

@jsotla I have the joystick connected to the A2 pin. I am quite a noob to this and would appreciate if you could explain what in my code could be shorting out my power :(

your code shows joyx and  joyX ... that indicates two joysticks ... both are connected to pin A2 ... if you turn one joystick to maximum and the other joystick to minimum, then that provides a low resistance path between Vcc and GND through the common connection at A2


text:
Using interrupts as flags/latches without any ISR
I've got an Arduino Mega periodically running an (~400ms) operation that is sensitive to repeatable timing, so I don't ever want it to be interrupted.  But, I'd like to be able to use an interrupt flag from one of the built-in peripherals (PCINT, comparator, etc.) to check afterward if an external event (say, a pin going high momentarily) ever happened during the operation.
That is, it'd be nice if I could just treat one of the interrupt flags as a kind of async hardware latch that I can check (and reset) at my next earliest convenience instead of having my code interrupted.
It wouldn't be hard to add a discrete latch IC, but I was hoping I could get away with just using what was already built into the AVR without adding more hardware (and using an extra pin to reset the latch).
Looking at the documentation for each of the peripherals, it was unclear whether the flags will still be set when the interrupts themselves are disabled.  I saw a mention someplace of an "EMPTY_INTERRUPT" macro, but I'm guessing that still generates an interrupt vector with a single "return" instruction, so I'd still be losing cycles to the interrupt preamble, etc.
Can this be done without any ISR being called at all?  Or do I need to add more hardware?  I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice unless that also doesn't interfere with UART receiving.  Thanks!

According to my page about interrupts the minimum time to execute an ISR is  2.625 µs plus whatever the code does (like set a flag). Is that not acceptable? Once? In your 400ms routine? That's a tiny fraction of how long your code takes.

I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice unless that also doesn't interfere with UART receiving. - so some interrupts are actually OK?

If you are receiving from a UART then time isn't really of the essence, is it? What is the baud rate?

What are the specific requirements of that periodic operation, jitter, frequency, tolerances, and so on?

I'm strobing LEDs to provide uniform illumination for a dozen or so successive industrial camera exposures (using a busy-wait).  It's less about exact timing and more about repeatable timing.  Each exposure is only a couple hundred microseconds, so even 2.625µs of periodic jitter would increase the exposure time by at least 1%.  I could use one of the timers, but I preferred the simplicity of the straight-line code.  I didn't know the UART interrupts the CPU; I'll have to check out the datasheet and maybe ask a separate question about that.

For your requirements, I would consider adding external hardware to detect and buffer the condition, giving you a GPIO that you can poll, where high means "the event happened since the last time you reset it". My guess is you could do it easily and cheaply. You might ask over on the electronics stack exchange for the best way to approach it. Then you wouldn't need to deal with interrupts at all.

... Sorry, on reread I see that you considered that option and were looking for alternatives.

The answer to your question is: yes, you can use an interrupt flag even
if the interrupt itself is disabled. The flag is raised whenever the
peripheral detects the relevant event. You can check it at your
convenience.
As for resetting the flag, the way to do it varies from flag to flag.
Most are reset by writing a 1 bit to it (yes, it is kind of backwards,
but that's how it works). Others are reset by removing the condition
that raised them in the first place (e.g. the USART Data Register Empty interrupt). You will have to check the datasheet for the specific
interrupt flag you are interested in.
That being said, I would question your idea that you don't want your
code to be interrupted at all. As Nick Gammon writes in a comment, the
minimum time to execute an ISR is 2.625 µs. This is about 0.0007%
of the process period. If your operation is so time-sensitive that it
cannot tolerate this kind of variation, then it cannot run on a Mega at
all. The ceramic resonator that clocks a Mega has a typical accuracy of
about 0.1%, which is 150 time worse than the effect of a minimal
interrupt. Even if you calibrate this oscillator against an atomic
clock, in only a few hours its frequency will drift past 0.0007%.
In addition, if you want the code to work with no interrupts, you will
have to disable them explicitly with noInterrupts(). You will then
loose the Arduino timing function millis(), delay(), etc. And you
will not be able to receive data from the UART unless you write your own
code that polls the “receive complete” UART interrupt flag and then
grabs the data from the UART data register.

Are you certain about that? In the datasheet it says The External Interrupts 7 - 4 are activated by the external pins INT7:4 if the SREG I-flag and the corresponding
interrupt mask in the EIMSK is set. My reading of that was that the flag is set if the interrupt is enabled. Otherwise, how would it know if it is rising or falling?

I might be wrong about that, I admit.

@NickGammon: In edge-detection mode, the flag is set even if the interrupt is disabled (I just checked). However, this is a bad example, as the interrupt flag does not work in level-detection mode: “These flags are always cleared when INT7:0 are configured as level interrupt.” I changed the example in my answer.

I left a comment above, too, but the actual process period is ~200µs (repeated many times) while exposing an image to a camera sensor.  And it's less sensitive to any particular clock rate.  I just want each identical busy-wait to take the same wall-clock time so there isn't any brightness difference between each exposure.  Even that 2.6µs gives around 1.3% additional illumination.  On a 12-bit sensor, that starts to add up quickly.  The UART intentionally isn't sending or receiving during that period, so hopefully it's alright to just leave it enabled...

It seems to me that the question of whether the flag is set or not might be somewhat implementation-specific. Even if it is 100% guaranteed for AVR chips it might not be for others, hence relying on that behaviour is not very good practice.

@MarkMorganLloyd the entire code is specific to one particular chip, so that doesn't really make sense.

@hobbs: Not my Mega, nor the one shown on the Arduino store. Unless you are talking about the quartz clocking the 16U2 that does the USB-to-serial conversion, which is irrelevant to the question being asked.

@hobbs actually, OP specifies "Arduino Mega" rather than a specific chip- even if that is tightened up somewhat in subsequent discussion. However using the interrupt flags in this way appears (to me at least) to be a fundamental design decision, and even if this is expected to be a one-off hobby project that sort of thing is risks cause enormous problems in the future if somebody else tries to use the code, or if a more appropriate chip comes onto the market.

I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice ...

That's right. Turning off interrupts would stop the timing/delay working so you wouldn't be able to time your 200 µs (unless you use delayMicroseconds).

Each exposure is only a couple hundred microseconds, so even 2.625µs of periodic jitter would increase the exposure time by at least 1%.

I think you might be better off using a hardware timer to time the exposure, rather than a loop. I generated VGA signals in a post here where I wanted the horizontal and vertical sync to have no jitter whatsoever. The timers can be set to turn on, or off, an output pin, so that could be used to control your shutter. Then it would be completely precise.

I didn't know the UART interrupts the CPU ...

Incoming (or indeed outgoing) serial communications causes interrupts. The timers cause interrupts. In particular, if you haven't disabled it, Timer 0 generates interrupts which are counted so that millis() and micros() can function. You can disable interrupts but then timing exact intervals becomes problematic. My suggestion of using the timer hardware will give the most reliable and repeatable performance, in the same way that my VGA signal generation was completely without jitter.
Because of the timer interrupts, if you haven't disabled interrupts, some of your exposures may have the timer interrupt in the middle (making them longer) and some not, or at least, a different number of interrupts. This will make the exposure time non-precise.

Another approach would be to turn off interrupts for the exposure only (ie. your 200 µs, not the 400 ms you mention), and then use delayMicroseconds() to time the exposure. Then when interrupts are back on the closure of a switch (an external interrupt) could be processed by a normal ISR. This might add slight differences to the time between exposures, but the exposure time itself would be constant.
Even with interrupts off, an external interrupt is "remembered" and would be processed when interrupts are enabled again.

This is turning into an XY problem somewhat. It would have been better to mention your exact requirements (the photography part) rather than launching into questions about using interrupts as latches.

Example code
To demonstrate how you can do this with timers, I have written some sample code:
// Example of strobing a flash FRAMES_TO_TAKE times to take pictures
// The time between each flash is in TIME_BETWEEN_SEQUENCES
// The flash "on" time is in STROBE_ON_TIME
//
// For Atmega328P (Arduino Uno and similar)
// and Atmega2560 (Arduino Mega)

// Author: Nick Gammon
// Date: 4 July 2023

const byte FRAMES_TO_TAKE = 12;
const byte CPU_CLOCK_SPEED = 16;  // MHz

const unsigned long TIME_BETWEEN_SEQUENCES = 20000;  // µs
const unsigned long STROBE_ON_TIME = 200;  // µs
const byte PRESCALER = 64;

// set correct output pin
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
  const byte FLASH_PIN = 10;  // OC1B (Output Compare Timer 1: B side) - Atmega328P
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  const byte FLASH_PIN = 12;  // OC1B (Output Compare Timer 1: B side) - Atmeg12560
#else
  #error Processor not supported
#endif

volatile byte count;  // how many times it fired

// Timer 1 Compare "B" ISR vector
// count up to the required number of exposures, then stop
ISR (TIMER1_COMPB_vect)
  {
  if (++count > FRAMES_TO_TAKE)
    {
    // stop timer 1
    TCCR1A = 0;
    TCCR1B = 0;
    } // end if number of frames reached

  }  // end of TIMER1_COMPB_vect

// does one sequence of FRAMES_TO_TAKE shots and then stops
void startSequence ()
{
  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A = bit (WGM10) | bit (WGM11);  // fast PWM - top at OCR1A
  TCCR1B = bit (WGM12) | bit (WGM13);  //  (mode 15)

  TCCR1A |= bit (COM1B1);   // Set OC1B during duty cycle

  OCR1A = ((TIME_BETWEEN_SEQUENCES * CPU_CLOCK_SPEED) / PRESCALER) - 1;  // total cycle time
  OCR1B = ((STROBE_ON_TIME * CPU_CLOCK_SPEED) / PRESCALER) - 1;          // duty cycle time
  count = 0;

  TCNT1 = 0;    // reset timer count

  TIFR1   = bit (OCF1B);    // clear "compare B" flag
  TIMSK1  = bit (OCIE1B);   // interrupt on compare B match
  TCCR1B |= bit (CS10) | bit (CS11);     // start timer with prescaler of 64
} // end of startSequence

void setup ()
  {
  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  // set up pin so we can toggle it
  pinMode (FLASH_PIN, OUTPUT);
  digitalWrite (FLASH_PIN, LOW);

  // for debugging etc.
  Serial.begin (115200);
  }  // end of setup

void loop ()
  {
  startSequence ();
  delay (20);
  Serial.print ("But does it get goat's blood out?\n");
  delay (1000);
   }  // end of loop;

Code explanation
What this code does is use Timer 1 to time the intervals you require. Based on what you posted earlier, I have assumed:

12 exposures in a "session" (FRAMES_TO_TAKE) - you said "a dozen or so"
Exposures are to be 20 ms apart (TIME_BETWEEN_SEQUENCES) - so a session is 240 ms
Exposure time is to be 200 µs (STROBE_ON_TIME) - you said "a couple of hundred microseconds"
You want to do other stuff like serial comms, checking switches etc.

The function startSequence initiates the timer which has a period of 20 ms and a duty cycle of 200 µs. At the completion of a duty cycle the ISR is called which counts duty cycles. At the end of the nominated number (12) the timer is turned off.
The output pin (pin 12 on the Mega, pin 10 on the Uno) is turned on during the duty cycle (ie. for 200 µs and off the rest of the time). Because this is done in hardware there is no jitter at all. In my demo I am doing serial comms to show that the intervals are exactly correct, despite the interrupts caused by the comms.

Logic analyser output
The logic analyser screenshot shows that the intervals are exactly correct (to within a fraction of a percent). In any case the intervals are consistent with each other.

This second screenshot shows that there are 12 pulses in that interval.

I have used a prescaler of 64 to get a nice long interval that can be timed (without overflowing the 16-bit counter size). This gives a granularity of 64 clock cycles (4 µs).

Timer 1 cheat sheet

These are all good suggestions.  Disabling interrupts for the individual exposures sounds like it might be the way to go.  I was only avoiding timers out of the convenience of not having to reason about the usual ISR problems: atomic (16-bit) read/writes, etc., but my scheme is simple enough that I could probably just set the timer, busy wait until it fires, and then continue on my way.  Regarding the XY problem, this is still an interesting question to me and I'm happy I know the answer for future projects, even if I don't end up using the interruptless-flags approach here.

@Nicholas If you let the timer itself change the pin state then you eliminate the (small) jitter based on where in your tight loop checking the timer to finish, it actually finishes. The read of the timer state, the compare, and the branch would probably amount to 6 to 8 clock cycles.

You are right that checking a timer flag in software introduces some jitter, but it's not as bad. A tight loop testing a flag on timer 1, 3, 4 or 5 is just sbis + rjmp. It takes 3 cycles, thus you have a 2-cycle jitter. Timers 0 and 2 require an lds, making it a 5-cycle loop.

@Nicholas See amended answer with example code of using a timer.


text:
How does arduino pro micro reset via USB?
The pro micro has no hardware reset circuitry that would allow host PC to cause a reset via USB.  But when programming using the bootloader, the host PC must have a way to reset the pro micro to allow it to enter bootloader mode and then upload code.
How is it reset?  Is the pro micro sensing the serial rate in some kind of way?  And if so, what is it looking for?  Or does the PC just disconnect the USB and then reconnect (but surely this would not work if the board was externally powered)


text:
I2C cabling rules for 2+ devices
I'm attempting to wire two breakout boards with i2c devices to a Mega2560:

a HD44280 LCD with PCF8574 i2c backpack
a combo board with DS1307 + AT24C32

There are two obvious possibilities for cabling:

two 10-inch ribbon cables that come together right before connecting to the Arduino's SDA and SCL pins. Technically, one could be 6 inches... but I know that with RS485, you're asking for trouble if you do a star with branches of unequal length. The cables can't really be any shorter without seriously impairing my ability to debug it while partially disassembled (the LCD is mounted to the lid, and the cables are long enough to allow me to lay the lid on the desk next to the enclosure and power everything up without putting stress on the cables).

Same 10-inch segments of ribbon cable, but daisy-chained... Arduino to LCD, LCD to RTC. In this case, the second one really needs to be 10", because it's mounted to the only clear spot inside the case I have.

Is one likely to be better or worse than the other?
Are there any rules about WHERE the pullup resistors have to go? The DS1307 module has built-in pullup resistors. Do I have to somehow disable them & use resistors right at the point where the bus connects to the Arduino's SDA & SCL pins, or can the pullups go pretty much anywhere on the bus (including at one end of a star, or at the far end of a daisy chain)?

I2C is generally slow. You don't have to worry about how to route the device connection. Because propagation delay won't be a matter. The main goal should be to minimize the capacitance of the wiring, which means minimizing the total wire length. But as you mentioned one of the cable lengths is fixed, then keep the other one to a minimum. The star topology will work if you keep the wire lengths within 10 inches.


text:
Why is the serial monitor not printing a variable?
I connected an Adafruit color sensor to my Arduino and am having it make calculations. However, when the calculations are done and sent to the serial monitor, it says "NDVI: " without printing the value. The code is attached below. Thanks!
Code:
/* TSL2591 Digital Light Sensor */
/* Dynamic Range: 600M:1 */
/* Maximum Lux: 88K */

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"

#define IR850 5
#define IR940 6
#define BLUE 9
#define GREEN 10
#define RED 11

// Example for demonstrating the TSL2591 library - public domain!

// connect SCL to I2C Clock
// connect SDA to I2C Data
// connect Vin to 3.3-5V DC
// connect GROUND to common ground

Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)

/**************************************************************************/
/*
    Displays some basic information on this sensor from the unified
    sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/
void displaySensorDetails(void)
{
  sensor_t sensor;
  tsl.getSensor(&sensor);
  Serial.println(F("------------------------------------"));
  Serial.print  (F("Sensor:       ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:   ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:    ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:    ")); Serial.print(sensor.max_value); Serial.println(F(" lux"));
  Serial.print  (F("Min Value:    ")); Serial.print(sensor.min_value); Serial.println(F(" lux"));
  Serial.print  (F("Resolution:   ")); Serial.print(sensor.resolution, 4); Serial.println(F(" lux"));
  Serial.println(F("------------------------------------"));
  Serial.println(F(""));
  delay(500);
}

/**************************************************************************/
/*
    Configures the gain and integration time for the TSL2591
*/
/**************************************************************************/
void configureSensor(void)
{
  // You can change the gain on the fly, to adapt to brighter/dimmer light situations
  //tsl.setGain(TSL2591_GAIN_LOW);    // 1x gain (bright light)
  //tsl.setGain(TSL2591_GAIN_MED);      // 25x gain
  tsl.setGain(TSL2591_GAIN_HIGH);   // 428x gain

  // Changing the integration time gives you a longer time over which to sense light
  // longer timelines are slower, but are good in very low light situtations!
  //tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS);  // shortest integration time (bright light)
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS);  // longest integration time (dim light)

  /* Display the gain and integration time for reference sake */
  Serial.println(F("------------------------------------"));
  Serial.print  (F("Gain:         "));
  tsl2591Gain_t gain = tsl.getGain();
  switch(gain)
  {
    case TSL2591_GAIN_LOW:
      Serial.println(F("1x (Low)"));
      break;
    case TSL2591_GAIN_MED:
      Serial.println(F("25x (Medium)"));
      break;
    case TSL2591_GAIN_HIGH:
      Serial.println(F("428x (High)"));
      break;
    case TSL2591_GAIN_MAX:
      Serial.println(F("9876x (Max)"));
      break;
  }
  Serial.print  (F("Timing:       "));
  Serial.print((tsl.getTiming() + 1) * 100, DEC);
  Serial.println(F(" ms"));
  Serial.println(F("------------------------------------"));
  Serial.println(F(""));
}

/**************************************************************************/
/*
    Program entry point for the Arduino sketch
*/
/**************************************************************************/
void setup(void)
{
  pinMode(IR850, OUTPUT);
  pinMode(IR940, OUTPUT);
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  digitalWrite(IR850, LOW);
  digitalWrite(IR940, LOW);
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, LOW);
  Serial.begin(9600);

  Serial.println(F("Starting Adafruit TSL2591 Test!"));

  if (tsl.begin())
  {
    Serial.println(F("Found a TSL2591 sensor"));
  }
  else
  {
    Serial.println(F("No sensor found ... check your wiring?"));
    while (1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();

  /* Configure the sensor */
  configureSensor();

  // Now we're ready to get readings ... move on to loop()!
}

/**************************************************************************/
/*
    Shows how to perform a basic read on visible, full spectrum or
    infrared light (returns raw 16-bit ADC values)
*/
/**************************************************************************/
void simpleRead(void)
{
  // Simple data read example. Just read the infrared, fullspecrtrum diode
  // or 'visible' (difference between the two) channels.
  // This can take 100-600 milliseconds! Uncomment whichever of the following you want to read
  uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
  //uint16_t x = tsl.getLuminosity(TSL2591_FULLSPECTRUM);
  //uint16_t x = tsl.getLuminosity(TSL2591_INFRARED);

  Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
  Serial.print(F("Luminosity: "));
  Serial.println(x, DEC);
}

/**************************************************************************/
/*
    Show how to read IR and Full Spectrum at once and convert to lux
*/
/**************************************************************************/
uint16_t ir, full;
void advancedRead(void)
{
  // More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
  // That way you can do whatever math and comparisons you want!
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
  Serial.print(F("IR: ")); Serial.print(ir);  Serial.print(F("  "));
  Serial.print(F("Full: ")); Serial.print(full); Serial.print(F("  "));
  Serial.print(F("Visible: ")); Serial.print(full - ir); Serial.print(F("  "));
  Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
}

/**************************************************************************/
/*
    Performs a read using the Adafruit Unified Sensor API.
*/
/**************************************************************************/
void unifiedSensorAPIRead(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  tsl.getEvent(&event);

  /* Display the results (light is measured in lux) */
  Serial.print(F("[ ")); Serial.print(event.timestamp); Serial.print(F(" ms ] "));
  if ((event.light == 0) |
      (event.light > 4294966000.0) |
      (event.light <-4294966000.0))
  {
    /* If event.light = 0 lux the sensor is probably saturated */
    /* and no reliable data could be generated! */
    /* if event.light is +/- 4294967040 there was a float over/underflow */
    Serial.println(F("Invalid data (adjust gain or timing)"));
  }
  else
  {
    Serial.print(event.light); Serial.println(F(" lux"));
  }
}

int lightvalue;
int NDVIred;
int NDVIinfrared;
int NDVI;
boolean (hasrun) = false;

/**************************************************************************/
/*
    Arduino loop function, called once 'setup' is complete (your own code
    should go here)
*/
/**************************************************************************/
void loop(void)
{
  lightvalue = 255;
  //simpleRead();
  //advancedRead();
  //unifiedSensorAPIRead();
  if(hasrun==false){
  analogWrite(RED, lightvalue);
  advancedRead();
  NDVIred = full;
  delay(5000);
  analogWrite(IR940,lightvalue);
  advancedRead();
  NDVIinfrared=full;
  NDVI=(NDVIinfrared-NDVIred)/(NDVIinfrared+NDVIred);
  Serial.print("NDVI: "); Serial.write(NDVIred);
  delay(1000);
  exit(0);
  }
}

You wrote:

Serial.print("NDVI: "); Serial.write(NDVIred);

You are misusing here the Serial.write() method. This method is meant
for sending raw bytes through the serial port. Since you are printing
text, you probably want the numeric value NDVIred to be printed out as
text, as a decimal number.
For printing text, use Serial.print() and Serial.println():
Serial.print("NDVI: "); Serial.println(NDVIred);

I did that and it now prints "NDVI: 0". Is there a problem with the variables?

@Chris: No, no problem with the variable. You are just seeing its value, which happens to be zero.

No, the code does what it's supposed to do. There is however a problem with the scope of the variable named full. It is defined as a global variable and again as a local variable inside of advancedRead(). Which explains why NVDIred is assigned a value of zero (which is the value of the still unchanged global full variable). Remove the definition of full from advancedRead() to fix this.


text:
Arduino uno R4 vs ESP32 Dev board
I was wondering what product would work best for my application. I need a web server interface to control several digital outputs connected to my board, and it needs to be as polished as it can be.
In the past I have extensively used ESP32 Dev boards with async web server and often used the integrated memory to save both html and image files to make the web server interface nicer. I was going to buy an ESP32 Dev board once again but then the uno R4 came out and now I am a bit confused on what to choose.
In short, my questions are:

can I load a source file alongside images and html files on the new uno like I did with the ESP32 (since from what I understand you could not do that in previous revisions of the uno)?
can I use the uno R4's ESP32 GPIO pins alongside the ones already provided on the uno?
is there any real advantage of the uno R4 over the ESP32 Dev board for the application I described?
Thanks in advance and sorry if the question is ill posed, I am not really practical with some of the hardware concepts involved!

first of all, the Uno R4 has a 5 V MCU and esp32 is a 3.3 V CPU. The Uno R4 WiFi has esp32-s3 as second MCU, but only as a WiFi adapter with AT firmware. (the Uno R4 Minima doesn't have WiFi.)

I did not test the UNO R4 yet, so this is completely based on the technical documents.
For a polished web interface, you will need some space to save all the data. Remember you need some space for the code, too, so these numbers are an upper bound and free space for HTML, CSS and images is a good portion less.

Standard ESP32 Dev Board: mostly 4 MB flash ROM (but can be 8 or 16).
UNO R4: 256 kB Flash ROM on the main chip, 384 kB ROM on the ESP32-S3-Mini-1-N8 that is used for WiFi.

This suggests that you do have way more space on the ESP32 DevBoard, making it more future-proof.
Another point that may be of interest is interrupts. WiFi does not like to be blocked by interrupt handlers, so if your code relies on interrupts, you may like multiple cores: That way, your code is not hampered by transferring the website.

The ESP32 has two cores, but you may need to keep an eye on which threads run on which cores. (I sometimes do have problems with time-critical applications like updating a string of WS2812b LEDs while loading the control website.)
The UNO R4 has completely separate chips for your sketch and the WiFi stack, but to run the web interface completely from its ESP32-S3-Mini-1-N8, I assume that you have to re-flash it with your own sketch. This probably (again, I'm interpolating from datasheets) means that you have program the UNO R4 as if it has two completely separate chips on it; and you'd have to create their communication protocol by yourself.

For your needs, this sounds as if you're better off using ESP32 DevBoards; maybe two if you run into the same problem as me.
Now, to directly answer your questions:

For serving files via webserver from Arduino UNO R4, I did not find much. Presumably the LittleFS filesystem works on Arduino UNO; and "just serving files" on ESP8266/ESP32 requires them to be in SPIFFS or LittleFS (to my knowledge). It may be that library support for this use case will improve with the release of the UNO R4, but for now, it looks like ESP32 is your best bet.
You may be able to use the GPIOs of the ESP on the UNO R4, but I'd assume that you will have to provide your own sketch/firmware for the ESP. Also, keep in mind that the UNO itself has 5V GPIOs, while the ESP has 3.3V GPIOs and you must not mix those voltages.
The only advantage of the UNO R4 over a ESP32 that I can see for you is: The GPIOs have 5V and you can run the board on 7-24V or USB. This makes the board more compatible with a lot of modules sold "for Arduino".

In the end, I probably would go for ESP32 and design every periphery on 3.3V or with level shifters; and add a second ESP32 if you run into the problem of the web interface interfering with your basic operation.


text:
Run Arduino Uno with battery AND use 5V output
Newbie here: I built a working binary clock with my Arduino UNO R3, see Picture 1. From my understanding the power supply for the Arduino itself is via USB, and I use the 5V output to supply power to the switch. Now, I would like the Arduino to run on battery and keep using its 5V power output - instead of only when it is connected to the PC.

From what I gathered on the internet, e.g. this page, I can simply connect the + end of my battery to the Vin port and the - end to GND. However, none of the pages I found deal with what to do with the "surrounding power infrastructure". Can I just keep it as is and use the wiring as in Picture 2 (USB is disconnected), i.e. is it safe to connect my 9V battery now? Or is there a better alternative?

Sorry for the beginner question. I am having so much fun learning with the Arduino (blasted through half the starter kit project handbook in just two days -> this is my variant of the digital hourglass) and don't want it to go up in flames already.
UPDATE: After the answers suggested that my idea should work, I tried it and, indeed, it works OK. I am getting a lot of Arduino resets/restarts though. Thanks for the replies!

"I am getting a lot of Arduino resets/restarts though."  Are you sure?  Do the unexpected events happen with using the switch?  If so, consider the switch bouncing causing the unexpected events.

These events occured without me pressing the switch. What do you mean by "switch bouncing"? I attributed this to loose contacts due to my unprofessional wiring or to the battery not providing sufficient power.

Almost all mechanical switches bounce slow enough that the SW will detect many events.  This makes it difficult for people not familiar with this problem to make use of switches in combination with software.  I think I see where you simply inserted the battery wires into the Arduino header.  It may help if you pushed a pin into the same hole to more securely connect the battery.  Or use the proper connector.

It is almost always better to add a schematic to your question. Backwards engineering from a picture can be confusing at times and lead to incorrect assumptions.
What you want to do appears to be possible. It looks like you are injecting 9 Volts positive at VIN (Pin 8 of the POWER header).  Examining the Arduino Uno R3 schematic here we see the VIN net connected to the input Pin 8 of the POWER header and also to the input side of the 5 Volt regulator (NCP1117ST50T3G).  This distributes the 5 Volts to the Atmel processor (appears to power the LED directly) and to the external switch which is assumed to be normally open but when closed connects to a 10Kohm resistor to ground.
The total current needed by external devices connected to the Arduino Uno R3 5 Volt regulator should be considered in such a design.  The NCP1117ST50T3G data sheet here state the regulator can handle in excess of 1 Amp (or 1000mA).
Assuming the LEDs take at most 20mA each and a worse case of all LED in the on state, that is 6 x 20mA or 120mA.  Also, when the switch is closed there is a current path from 5 Volts to ground through a 10Kohm resistor.  Using V = A x R we see that A = V / R = 5 / 10000 = 0.5mA when the switch is closed.  So the total current the external devices might use is likely no more than 120.5mA.  This is far less than 1000mA (the upper limit of the Arduino's 5 Volt regulator) so appears well withing safety margins.
However, an Alkaline 9 Volt battery only contains about 550mAh.  Ignoring the current it takes to run the Arduino Uno R3, we see that dividing the worst case external current demand of 120.5mAh into 550mAh we get 4.6 hours of use.  An Alkaline AA 1.5 Volt battery contains about 2000mAh.. You would need 6 AA 1.5 Volt batteries in series to generate 9 Volts. But they should last about 4 times longer.

Sorry @EdgarBonet, pushed the button a bit eary.  I'll add more text to clarify that (i.e. Pin 8 of connector such-n-such on the schematic).

Thanks, I would upvote your answer but it seems I haven't got enough reputation. I will try and add a schematic next time. I was also wondering about the different GND pins on the Arduino. Are they connected, i.e. could I alternatively plug the - end of the battery into my "ground bus line" on the breadboard? I can't tell from the schematics you linked.

That's actually a good question. Usually all grounds are connected together. In this case ping 6 and 7 of the POWER header and pin 7 of the IOH header are connected together. In general, all grounds should be connected back to one point which should be substantial enough to handle the total current and then some. However, in this case none of the devices draw enough current to be much of a concern. What you have should work.

The voltage regulator in an Arduino might be rated at 1 amp in theory, but they don't have proper heat sinks, and I would expect the linear power supply to overheat in fairly short order under anywhere near that load. (Linear power supplies work by converting excess voltage to heat. So a 9V source dropped down to 5V needs to burn 4V as heat. At one amp output, that's .8 amps converted to heat, assuming my math is right. )

True, and even the 1 Amp talked about in the part spec also considered that part is kept at a reasonable temperature. But likely this project will require a quarter of that.  Maybe even less. Low current / battery operation is difficult even for experienced engineers.  Using a battery pack which supplies the necessary 5 or 3.3 Volts and avoiding the linear regulator is an option (as suggested by @Edgar Bonet). Or switching to a more efficient switching (buck) power supply is another (as you (@Duncan C) suggested).

Yes, that should work, albeit inefficiently: for every milliwatt of power
consumed by an LED, you will have roughly 0.7 mW dissipated in the
series resistor, and 1.3 mW dissipated in the Arduino's voltage
regulator. Given the low capacity of 9 V batteries, I doubt your
clock will run for very long.

Thanks, I would upvote your answer but it seems I haven't got enough reputation. Are there any quick and easy improvements that would lead to a longer uptime?

@Krawabbel: You may use higher capacity batteries, as explained by st2000. Or you may build a breadboard Arduino, run it at 8 MHz, and power it from unregulated 3 V (a pair of C- or D-sized batteries) for maximum power efficiency.

By "breadboard Arduino" you mean something like this? Do I understand it correctly that the idea of using only 3V would be to basically run it at the lowest possible voltage and/or current where the LED is still working? Sorry for the dumb questions, I only took one electrical engineering course at university.

@Krawabbel: Yes, that “breadboard Arduino” tutorial is what I was referring to. The idea of running from 3 V is to reduce the energy loss in the resistors, and completely remove the loss happening in the voltage regulator by removing the regulator itself.

You could certainly use a 9V battery into the VIN port on your Arduino, but the built-in power supply uses a "linear voltage regulator", which is quite inefficient. If your goal is long battery life you'd be much better off with a buck style power supply or a switching power supply. Those are a LOT more efficient.
You should be able to find modestly priced power supplies built for Adruino online that are a lot more efficient than the built-in supply.
(And as mentioned, 9V batteries have a very small capacity. 6 AA or even C batteries would last a lot longer.)