message:
Nano 33 BLE Sense powered with Vin and USB at the same time

I have a project where I would like to power an Arduino Nano 33 BLE Sense
with USB and Vin at the same time.

The idea is to charge an external LiPo 3.7V through a charger module
that would take the load from the 3.3V pin (that would be powered through USB)
and at the same time keep powering the Arduino through Vin
because I want to avoid a power interruption when I unplugged the USB cable
that would interrupt the writing operation (on a text file on an SD card).

So the goal is to prevent data corruption on a writing operation on a text file.
I know text files are supposed to be less corruptible (compared to a database)
but I want to be sure the operation would be uninterrupted.

I've seen this post:
https://arduino.stackexchange.com/questions/893/what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-power-voltage
But it's related to the Arduino UNO R3.

It basically says:
When Vin >6.6V the opamp turns the mosfet off.
>>> so the USB disconnects.

When Vin <6.6V the opamp turns the mosfet on.
>>> so the USB stays connected.

On Arduino's website:
https://store-usa.arduino.cc/products/arduino-nano-33-ble-sense
it says:

***
Vin: This pin can be used to power the board with a DC voltage source.
If the power is fed through this pin, the USB power source is disconnected.
***

It does not mention from what voltage it would disconnect the USB power.

I did not find the same schematic for the Arduino Nano 33 BLE Sense.
Just this:https://docs.arduino.cc/hardware/nano-33-ble-sense

>>> Interactive Viewer
Interact with the schematics, the PCB and a 3D model of the product.

and this: https://docs.arduino.cc/static/353d3c445c28b1da1fe1f9d6eafa948d/ABX00031-schematics.pdf

I'm not very familiar with reading schematics but I could not find similar information about vin and USBVCC.

That'd be great if somebody had some insight on that.

I would welcome any suggestion.

Cheers!

---

If I connect a battery charger/controller on VIN, my battery would be protected.

And I could connect a booster 5V and add a shottky diode so its connection to VIN would be closed if booster+ < VIN

Like this ?

[![charger + booster][1]][1]

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

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

In this power block you can see there is only one Schottky diode with the voltage drop under 0.5V@2A. That means D2 is closed around the condition: VUSB < VIN.

On the other side if you add 3.6-4.2V battery on VIN there will be current flowing from VUSB to battery.

Basically you need another shottky diode Bat+ -> [A|K] -> VIN  so when there is bigger voltage on the VIN it'll "shut off" the battery (otherwise it'll be charged by almost 5V)

Depending on the application and sensors you are planning to use, you might want to consider for example Seeed Studio XIAO nRF52840 Sense that has battery charging circuit and pads for the battery on the bottom (although it's not the "bread board" pins)

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


sender: user

message:
Motion-activated lights

I am attempting to follow [this tutorial](https://speedysignals.com/2013/08/01/how-to-assemble-stair-lights/) to light up a dark staircase with motion-activated LED strips. If my understanding of the tutorial is correct, essentially the Arduino's job is to power or depower transistors at the appropriate time to prohibit/allow enough voltage over the LED strips on the stairs.

I have assembled a few light strips and soldered the microcontroller to the PCB with the appropriate components and was ready to test the device. The author of the guide helpfully created [this video](https://www.youtube.com/watch?v=Lc4w2SDPnmE&embeds_euri=https://speedysignals.com/&feature=emb_imp_woyt&ab_channel=AndrewOng) demonstrating the expected behavior of the device on start-up: the lights should blink as shown and then turn off, awaiting activation from a motion sensor. However when I try to replicate this my lights simply turn on and never turn off, fade, or blink.

Consulting the FAQ on the guide, I tried reorienting my transistors, thinking I perhaps had them backward. This had no effect.

I then tried to verify that my microprocessor was working and programmed correctly. I modified the code in the setup section, adding the following commands:
```
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
for(int i=0; i<10; i++){
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    delay(2000);
}
```
The intention was to make the built-in LED on the board blink on and off a few times during startup. While the board was connected to the computer, it indeed blinked on and off after I hit upload. When it's attached to the power supply from the PCB it does not blink (though the LED lights for the stairs turn on as I have described).

It seems to me that the microprocessor is simply not getting power or is not connected properly to the PCB. However I have done my best to verify all the connections and cannot find any problem. This is my first project of this type and am not sure what else to try. Any guidance with troubleshooting would be very much appreciated.

I apologize for the long post but I wanted to be sure to include all the necessary information. Thank you for reading!

Below are images of the PCB and schematics from the guide, which hopefully correspond to how I've actually connected the components.

[![PCB diagram][1]][1]

[![PCB Schematic][2]][2]

[![My Device][3]][3]

Here is the code from the guide plus my blinking loop. The original is available at the [author's github](https://github.com/androng/Shift-stairs).

```
##Shift_Stairs.ino

#include <math.h>
#include <SPI.h>
//#include <MemoryFree.h>
//#include "expoDutyCycles.h"

//Data pin is MOSI (atmega168/328: pin 11. Mega: 51)
//Clock pin is SCK (atmega168/328: pin 13. Mega: 52)
const int ShiftPWM_latchPin=10;
const bool ShiftPWM_invertOutputs = 0; // if invertOutputs is 1, outputs will be active low. Usefull for common anode RGB led's.

#include <ShiftPWM.h>   // include ShiftPWM.h after setting the pins!

const int SWITCH_PIN = A0;
const int PHOTORESISTOR_PIN = A2;
const int MOTION_SENSOR_TOP_PIN = 2;
const int MOTION_SENSOR_BOTTOM_PIN = 3;

const unsigned char maxBrightness = 255;
const unsigned char pwmFrequency = 75;
const int numRegisters = 2;
const int NUMLEDs = 9;
const int MOTION_SENSOR_WARMUP_TIME = 10;
const int ON_TIME = 10000; /* The duration between turn on and turn off. */
const int LIGHT_THRESHOLD = 300; /* Anything below this sensor value will enable lights */

/* These are used to detect rising edges in the absence of interrupts.
   Using interrupts with ShiftPWM crashes the program. */
unsigned char lastReadTopPin = LOW;
unsigned char lastReadBotPin = LOW;

volatile unsigned char topActivated = false;
volatile unsigned char bottomActivated = false;
unsigned long lastMotionTime = 0;

const char BOTTOM_TO_TOP = 1;
const char TOP_TO_BOTTOM = 2;
/* For sake of the animation, stores the direction of propegation.
   Set when animation is active, cleared when animation is done.  */
char directionTriggered = 0;

const unsigned long BRIGHTNESS_SM_PERIOD = 2000; /* in μs */
unsigned long lastBrightnessSM = 0;

/* LED 0 is on the top of stairs */
unsigned char brightnesses[NUMLEDs] = {0};

void setup()   {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    for(int i=0; i<10; i++){
      digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
      delay(2000);
    }
    pinMode(ShiftPWM_latchPin, OUTPUT);
    SPI.setBitOrder(LSBFIRST);
    // SPI_CLOCK_DIV2 is only a tiny bit faster in sending out the last byte.
    // SPI transfer and calculations overlap for the other bytes.
    SPI.setClockDivider(SPI_CLOCK_DIV4);
    SPI.begin();

    Serial.begin(9600);

    /* Turn on pullup resistor for switch */
    digitalWrite(SWITCH_PIN, HIGH);

    ShiftPWM.SetAmountOfRegisters(numRegisters);
    ShiftPWM.Start(pwmFrequency,maxBrightness);
    // Print information about the interrupt frequency, duration and load on your program
    ShiftPWM.SetAll(0);
    ShiftPWM.PrintInterruptLoad();
    // Fade in all outputs
    for(int j=0;j<maxBrightness;j++){
        ShiftPWM.SetAll(j);
        delay(3);
    }
    // Fade out all outputs
    for(int j=maxBrightness;j>=0;j--){
        ShiftPWM.SetAll(j);
        delay(3);
    }
}
void loop()
{
    /* Detect rising edge with polling. Interrupts crash the program. */
    unsigned char pinRead = digitalRead(MOTION_SENSOR_TOP_PIN);
    if(pinRead == HIGH && lastReadTopPin == LOW){
        topActivated = true;
    }
    lastReadTopPin = pinRead;
    /* Detect rising edge with polling. Interrupts crash the program. */
    pinRead = digitalRead(MOTION_SENSOR_BOTTOM_PIN);
    if(pinRead == HIGH && lastReadBotPin == LOW){
        bottomActivated = true;
    }
    lastReadBotPin = pinRead;

    /* Resets flags */
    if(topActivated){
        if(directionTriggered == 0){
            directionTriggered = TOP_TO_BOTTOM;
        }
        lastMotionTime = millis();
        topActivated = false;
    }
    if(bottomActivated){
        if(directionTriggered == 0){
            directionTriggered = BOTTOM_TO_TOP;
        }
        lastMotionTime = millis();
        bottomActivated = false;
    }

    /* State machine */
    if(micros() - lastBrightnessSM > BRIGHTNESS_SM_PERIOD){
        brightnessSM();
        lastBrightnessSM = micros();
    }
}
/**
    Returns true if switch is in "1" position.
*/
boolean switchPressed(){
    return !digitalRead(SWITCH_PIN);
}
```

```
###brightnessSM.ino
enum brightnessStates {
    sFullyOn,
    sOff,
    sTurningOn,
    sTurningOff,
    sOverrideSwitch
};

int brightnessState = sOff;

void brightnessSM(){
    /* Actions */
    switch(brightnessState){
    case sFullyOn:
        break;
    case sOff:
        break;
    case sTurningOn:{
        /* Increase brightness of lights. This for loop goes from -NUMLEDs to 0 or
           0 to NUMLEDs depending on the direction of propegration. */
        char startLight = -1 * (directionTriggered - 1) * (NUMLEDs - 1);
        char endLight   = -1 * (directionTriggered - 2) * (NUMLEDs - 1);
        for(char l = startLight; l <= endLight; l++){

            /* Turn on the next LED only if the ones before it
               are on*/
            if(brightnesses[abs(l)] != maxBrightness){
                brightnesses[abs(l)] += 5;
                ShiftPWM.SetOne(abs(l), brightnesses[abs(l)]);
                break;
            }

            /* Turn on the next LED only if the one before it is partially on */
//            if(brightnesses[abs(l)] != maxBrightness){
//                if(l == startLight || (brightnesses[abs(l - 1)] > maxBrightness*3/10)){
//                    brightnesses[abs(l)] += 1;
//                    ShiftPWM.SetOne(abs(l), expoDutyCycles[brightnesses[abs(l)]]);
//                }
//            }
        }
        break;
    }
    case sTurningOff:{
        /* Decrease brightness of lights. This for loop goes from -NUMLEDs to 0 or
           0 to NUMLEDs depending on the direction of propegration. */
        char startLight = -1 * (directionTriggered - 1) * (NUMLEDs - 1);
        char endLight   = -1 * (directionTriggered - 2) * (NUMLEDs - 1);
        for(char l = startLight; l <= endLight; l++){
            /* Turn on the next LED only if the ones before it
               are on*/
            if(brightnesses[abs(l)] != 0){
                brightnesses[abs(l)] -= 5;
                ShiftPWM.SetOne(abs(l), brightnesses[abs(l)]);
                break;
            }

            /* Turn on the next LED only if the one before it is partially on */
//            if(brightnesses[abs(l)] != 0){
//                if(l == startLight || (brightnesses[abs(l - 1)] < maxBrightness*9/10)){
//                    brightnesses[abs(l)] -= 1;
//                    ShiftPWM.SetOne(abs(l), expoDutyCycles[brightnesses[abs(l)]]);
//                }
//            }
        }
        break;
    }
    case sOverrideSwitch:
        break;
    }

    /* Transitions */
    switch(brightnessState){
    case sFullyOn:
        if(millis() - lastMotionTime > ON_TIME){
            brightnessState = sTurningOff;
        }
        if(switchPressed()){
            transitionToOverrideSwitch();
        }
        break;
    case sOff:
        if(directionTriggered != 0){
            if(analogRead(PHOTORESISTOR_PIN) < LIGHT_THRESHOLD){
                brightnessState = sTurningOn;
            }
            else {
                directionTriggered = 0;
            }
        }
        if(switchPressed()){
            transitionToOverrideSwitch();
        }
        break;
    case sTurningOn:{
        /* If all the lights are on then proceed */
        unsigned char allOn = true;
        for(unsigned char l = 0; l < NUMLEDs; l++){
            if(brightnesses[l] != maxBrightness){
                allOn = false;
                break;
            }
        }
        if(allOn){
            brightnessState = sFullyOn;
        }
        if(switchPressed()){
            transitionToOverrideSwitch();
        }
        break;
    }
    case sTurningOff:{
        /* If all the lights are off then proceed */
        unsigned char allOff = true;
        for(unsigned char l = 0; l < NUMLEDs; l++){
            if(brightnesses[l] != 0){
                allOff = false;
                break;
            }
        }
        if(allOff){
            directionTriggered = 0;
            brightnessState = sOff;
        }
        if(switchPressed()){
            transitionToOverrideSwitch();
        }
        break;
    }
    case sOverrideSwitch:
        if(switchPressed() == false){
            /* Switch all LEDs off */
            for(char l = 0; l < NUMLEDs; l++){
                ShiftPWM.SetOne(l, 0);
                brightnesses[l] = 0;
            }
            directionTriggered = 0;
            brightnessState = sOff;
        }
        break;
    }
}
void transitionToOverrideSwitch(){
    brightnessState = sOverrideSwitch;
    /* Switch all LEDs on */
    for(unsigned char l = 0; l < NUMLEDs; l++){
        ShiftPWM.SetOne(l, maxBrightness);
        brightnesses[l] = maxBrightness;
    }
}
```
  [1]: https://i.stack.imgur.com/SBMoS.png
  [2]: https://i.stack.imgur.com/BJEUY.png
  [3]: https://i.stack.imgur.com/FkBuT.jpg

sender: assistant

body:
The image of the Printed Circuit Board (PCB) posted in the above question contains many examples of what are commonly referred to as [Cold Solder Joints][1].  These types of joints are unreliable and occasionally provide no electrical connectivity. And are often impossible to visually verify.  The [first 2 minutes of this video][2] demonstrate how heat and flux can be combined to remedy cold solder joints involving a PCB and feed-through pin.

*(I can edit/change the following as we narrow in on the solution for this problem. The objective is to make a good stackexchange question & answer.)*

Symptom:
 * The project behaves as expected when cabled to the PC.  This assumes the cable to the PC (likely to a USB/CDC to Serial Port) contains Ground, In, Out and Power. The expected behavior is to turn the LEDs on and off.
 * The project does not work when disconnected from the PC and is powered by an external power supply.  The LEDs only turn on.

Consider verifying power to the processor or, better, at the processor.  For the problem as described in the question, there may be an interruption of the power path from the external power supply to the processor.  Check all the solder joints involved in connecting the Arduino's power input to the PCB. Likely the processor (Arduino) was powered up during programming through the Ground and Power pins of the serial port cable.  Once that cable was removed, the processor may not be powered and may have not been running while the PCB was only powered from an external source.

  [1]: https://www.pcbdirectory.com/community/what-is-a-cold-solder-joint
  [2]: https://www.youtube.com/watch?v=VLubdi6aC3g


message:
best practice for performance: empty loop() when using interrupt?

I'm working on a little midi hardware project and I'm using `attachInterrupt()` to assign a callback function to an interrupt pin.

Nothing gets done in the loop function, so it looks like this:
```
void loop() { return; }
```

So far this seems to work out, but I'm wondering if this is a bad practice? I tried adding a short delay() call in there instead but I couldn't really measure if it performed better or worse.

body:
I think I can answer my own question.

I realized that I can keep my state change and debouncing logic in the interrupt routine and move everything else to the loop function, which seems cleaner.

edit: well not necessarily cleaner. I agree with @jsotola, ISR should only do the bare minimum.

In the end I figured not even using an ISR in the first place was even better for my use case.


body:
There is no particular reason to worry about doing nothing in `loop` - the processor has to be doing *something* -  you don't need to give it extra work.

Plus, there is an implied `return` at the end of functions, you don't need to add your own.

The bigger issue is that interrupt handlers should be short, so that you don't miss another interrupt while you are doing something lengthy in the first interrupt.


message:
Troubleshooting UART communication between nano 33 ble sense r2 and Adafruit Feather 32u4 with LoRa Radio Module

I've tried connecting the gnd's for both the boards and have connected rx to tx and vice versa in both the boards. I've powered both by batteries, and I'm trying to get sensor data from the nano, and trying to send it to the feather via UART, and long distance away using the Lora capabilities of the Feather.

I've loaded this program in the nano:
```lang-cpp
/*
Including libraries
*/
//Accelerometer{
#include "Arduino_BMI270_BMM150.h"
//Accelerometer}
//Temperature and humidity{
#include <Arduino_HS300x.h>
//Temperature and humidity}
//Pressure{
  #include <Arduino_LPS22HB.h>
//Pressure}

/*
Creating variables for sensors
*/
//Acceleration variables{
float x, y, z;
//Acceleration variables}
//Temperature and humidity variables{
float temperature;
float humidity;
//Temperature and humidity variables}
//Pressure variables{
float pressure;
//Pressure variables}

void setup() {

/*
Setting up sensors
*/
Serial1.begin(9600);
//Accelerometer{
  if (!IMU.begin()) {
    Serial1.println("Failed to initialize IMU!");
    int i = 0;
    Serial1.println("Trying again\n");
    while (!IMU.begin()){
      if(i>0){
        Serial1.print(" Failed\n");
      }
      Serial1.print("Try number ");
      Serial1.print(i);
      i++;
      delay(1000);
    }
    Serial1.print("Passed\nOn attempt number ");
    Serial1.print(i);
    Serial1.print("\n");
  }
//Accelerometer}
//Temperature and humidity{
if (!HS300x.begin()) {
  Serial1.println("Failed to initialize humidity temperature sensor!");
  int i = 0;
    Serial1.println("Trying again\n");
    while (!HS300x.begin()){
      if(i>0){
        Serial1.print(" Failed\n");
      }
      Serial1.print("Try number ");
      Serial1.print(i);
      i++;
      delay(1000);
    }
    Serial1.print("Passed\nOn attempt number ");
    Serial1.print(i);
    Serial1.print("\n");
}
//Temperature and humidity}
//Pressure{
if (!BARO.begin()) {
  Serial1.println("Failed to initialize pressure sensor!");
    int i = 0;
    Serial1.println("Trying again\n");
    while (!BARO.begin()){
      if(i>0){
        Serial1.print(" Failed\n");
      }
      Serial1.print("Try number ");
      Serial1.print(i);
      i++;
      delay(1000);
    }
    Serial1.print("Passed\nOn attempt number ");
    Serial1.print(i);
    Serial1.print("\n");
}
//Pressure}
}

void loop() {
  /*
  Read sensor data into the variables
  */
  //Read acceleration{
  if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(x, y, z);
  }
  //Read acceleration}
  //Read temperature and humidity{
  temperature = HS300x.readTemperature();
  humidity = HS300x.readHumidity();
  //Read temperature and humidity}
  //Read pressure{
  pressure = BARO.readPressure();
  //Read pressure}

  /*
  Print the sensor data to Serial1 (hopefully implement sending this data to the lora feather, which will radio it to a distant arduino)
  */
  Serial1.print("\nAcceleration (x, y, z): ");
  Serial1.print(x);
  Serial1.print(", ");
  Serial1.print(y);
  Serial1.print(", ");
  Serial1.print(z);
  Serial1.print("\nTemperature: ");
  Serial1.print(humidity);
  Serial1.print("\nHumidity: ");
  Serial1.print(humidity);
  Serial1.print("\nPressure: ");
  Serial1.print(pressure);
  delay(1000);

}
```
I've loaded this program in the transmitting feather:
```lang-cpp
/* The program for the feather1 to take information from nano 33 ble sense rev2 and radio it to  where the feather2
** will communicate to the ground station's program todisplay the data in a user friendly manner, and will display results
*/
#include <RH_RF95.h>

// LoRa settings
#define RFM95_CS 8
#define RFM95_RST 4
#define RFM95_INT 7
#define RFM95_FREQ 915.0

RH_RF95 rf95(RFM95_CS, RFM95_INT);

void setup() {
  Serial.begin(9600);
  pinMode(RFM95_RST, OUTPUT);
  digitalWrite(RFM95_RST, HIGH);
  delay(100);
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);
  if (!rf95.init()) {
    Serial.println("LoRa init failed. Check your connections.");
    while (1) ;
  }
  rf95.setFrequency(RFM95_FREQ);
  rf95.setTxPower(23, false);
  Serial.println("LoRa Transmitter Ready!");
}

void loop() {
  static uint16_t messageCount = 0;
  String input;
  while (Serial.available() > 0) {
    char c = Serial.read();
    input += c;
  }
  if (input.length() > 0) {
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    input.getBytes(buf, input.length() + 1);
    rf95.send(buf, input.length() + 1);
    rf95.waitPacketSent();
    Serial.println("Sent message #" + String(messageCount) + ": " + input);
    messageCount++;
  }
  delay(1000);
}
```

I've got this program in the receiving feather:
```lang-cpp
/* The program for the feather2 to recieve information from feather1 ** and will communicate to the ground station's program todisplay the data in a user friendly manner, and will display results
*/

#include <RH_RF95.h>

// LoRa settings
#define RFM95_CS 8
#define RFM95_RST 4
#define RFM95_INT 7
#define RFM95_FREQ 915.0

RH_RF95 rf95(RFM95_CS, RFM95_INT);

void setup() {
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  /* The infinite while loop above not needed if you're not using rx/tx for sending
  ** the recieved radio data to your program or are using some other method to
  */
  pinMode(RFM95_RST, OUTPUT);
  digitalWrite(RFM95_RST, HIGH);
  delay(100);
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);
  if (!rf95.init()) {
    Serial.println("LoRa init failed. Check your connections.");
    while (1) ;
  }
  rf95.setFrequency(RFM95_FREQ);
  rf95.setTxPower(23, false);
  Serial.println("LoRa Receiver Ready!");
}

void loop() {
  if (rf95.available()) {
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len)) {
      Serial.print("Received: ");
      Serial.println((char*)buf);
    } else {
      Serial.println("LoRa receive failed");
    }
  }
}
```
I have been able to establish UART communication between two Unos before, but I'm unable to find out why it isn't working in this case. I can confirm it isn't working because the Serial monitor for the recieving feather (feather2) only shows this:
```
17:52:39.840 -> LoRa Receiver Ready!
```
Why this is happening, and any potential fixes for this?

body:
As I see 32U4 I'd expect the Serial is used for native USB serial (CDC). If you want to use usart on pins 0 and 1, you'd have to use Serial1 instead.

Nano 33 BLE is the same, it has native USB and you are correctly using Serial1 for accessing serial pins 0 and 1 (however nRF52840 can use any pins).


message:
tone() corrupts the PWM on a different pin

I have to use PWM to control some lights. I do this successfully with:
`analogWrite(11, 127);`
for a 50% PWM pulse on `pin 11`.

Now, i also have to have `tone()` support on my code. When I do:
`tone(10, melodyArray[thisNote], noteDuration);`
I invoke the `tone()` function on `pin 10`.

When I do so, then PWM pulse is corrupted. Since I do not have an oscilloscope, I cannot exactly understand what happens.
But from the effects on the lights, I can speculate that the PWM pin (`pin 11`) is always `HIGH` or always `LOW`.

It is obvious that the PWM pin and the `tone()` pin are different.

Why does this happen? Perhaps the `tone()` uses some timers that interfere with the PWM?
When I comment out the `tone()` line, the PWM works as intended.

Is there a solution to this? Can I use the tone() function and still have `PWM` support (on another pin)?

body:
To quote from the [Arduino documentation][1] of `tone()`:

> Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

So yes, you should use a different pin than 3 or 11 for `analogWrite()`. This is because `tone()` will configure the hardware Timer2 for outputting these timed signals via hardware. PWM on these pins is also tied to Timer2. When both functions are trying to configure Timer2 in a different way, there will be conflicts.

Note: The documentation talks about "boards other than the Mega", which was true when there weren't other Arduino boards than the old Uno/Nano/Mini (based on the Atmega328p). Nowadays there are so much boards, which all can be programmed with the Arduino framework, that this sentence is a real stretch. Instead I would say "on boards based on the Atmega328p". Depending on your used board your mileage may very. Check the microcontrollers datasheet for the hardware Timers it has and their connected pins.

  [1]: https://reference.arduino.cc/reference/en/language/functions/advanced-io/tone/


message:
If I reduce ADC sample rate, do I get an average over the time period?

I am working with a ESP32-C3 devkit. I am using the internal ADC on that chip to read from an analog microphone. I initialize the ADC like this:

    adc_continuous_config_t dig_cfg = {
        .sample_freq_hz = 20000,
        // ...
    };
    ESP_ERROR_CHECK(adc_continuous_config(handle, &dig_cfg));

If I reduce the sample frequency to, say 1000 Hz, then will each sample represent, roughly, an average of 20 samples from my previous stream (where the sample frequency was 20,000 Hz)? Or is it more like I will get just one out of every 20 samples from the original stream?

The reason I ask is that I'm hoping to perform a kind of low-pass filter by changing the ADC sampling frequency and I'm wondering what's going on inside the ADC hardware when I change the sampling frequency.

body:
Possibly not. The ADC on the Arduino Uno (a different processor, I know) uses the "sample and hold" technique. This means that the ADC samples the input voltage at a point in time, copying it into a sample-and-hold capacitor. It then successively compares it to be above or below threshold voltages to generate the individual bits of the resulting number. I have some details about the Uno ADC [here](http://gammon.com.au/adc).

It probably does this so that, when sampling a rapidly changing signal (like audio) it samples a moment in time, rather than having the comparison be of a signal that is changing over time.

I can't find technical details for the ESP32 ADC sampling method, but it seems likely that a lower sample rate will simply sample less data points, not take an average. This  could lead to wildly inaccurate results.

You might want to check out the [Nyquist Frequency](https://en.wikipedia.org/wiki/Nyquist_frequency) to see the reasons for choosing a certain sample rate.

If you want an average, feeding the signal into a suitably-sized RC filter might be a good way of finding an average voltage.


message:
fastLED help - special reinforcements needed

Hello help needed trying to get fastLED to start and stop at specific points on the strip, i have this nice fade animation but need to split the strip intov about 3 sections and have it run at different times.

here is the mess i have made any help welcome...

```c++
#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6 //How boring and obvious!
#define COLOR_ORDER GRB //Green (G), Red (R), Blue (B)
#define CHIPSET WS2812B
#define BRIGHTNESS 60
#define VOLTS 5
#define MAX_AMPS 500 //value in milliamps

//ENOUGH NONSENSE!

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<CHIPSET,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.setMaxPowerInVoltsAndMilliamps(VOLTS, MAX_AMPS);
  FastLED.setBrightness(BRIGHTNESS);
  FastLED.clear();
  FastLED.show();
}

void loop() {
  fadeToBlackBy(leds, NUM_LEDS, 4);      // Smaller value = longer tail
  int i = (millis()/40) % NUM_LEDS;      // How fast it goes.
  leds[i] = CRGB::White;
  FastLED.show();
}
```

Cheers
Rob

body:
Here is an example sketch that shows how to manipulate data in a sub-section of an array.

https://wokwi.com/projects/362275278547275777

The important thing to understand, is that the `FastLED.show();` is the function that does the sending of the `leds[]` array contents to the physical LED strip.

That means that you can do anything you want to the `leds[]` array, and the changes will not be visible until the `show()` function is called.

You can make changes in bits and pieces, without seeing the change increments.

This sketch also shows how to use timers to synchronize actions

```lang-c++

#include <FastLED.h>

#define CHIPSET     WS2812B
#define COLOR_ORDER     GRB         // Green (G), Red (R), Blue (B)
#define NUM_LEDS         95
#define DATA_PIN          3
#define BRIGHTNESS      255
#define VOLTS             5
#define MAX_AMPS        500         // value in milliamps

CRGB leds[NUM_LEDS];                // main LED array
CRGB test[10];                      // set up separate array for merging with main LED array
                                    // kind of a sprite
int indx = 0;

boolean tick[4] = {false, false, false, false};    // countdown timers flags

unsigned long timeInterval  [4] = {10, 20, 1, 2};  // timers load with these values
unsigned long timeCounter   [4];                   // these are the actual timers

unsigned long previousMicros = 0;

void setup() {

  Serial.begin(115200);

  FastLED.addLeds<CHIPSET,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.setMaxPowerInVoltsAndMilliamps(VOLTS, MAX_AMPS);
  FastLED.setBrightness(BRIGHTNESS);
  FastLED.clear();

  memcpy(timeCounter, timeInterval, 4 * sizeof(long));  // preload timers
}

void loop() {

  unsigned long currentMicros = micros();

  if (currentMicros - previousMicros >= 1000) {   // 1 ms tick
    for (int i = 0; i < 4; i++) {
      previousMicros = currentMicros;

      timeCounter[i]-- ;                          // keep track of 4 time intervals
      if (timeCounter[i] == 0) {
        timeCounter[i] = timeInterval[i];         // reached zero, reload counter and emit a "tick"
        tick[i] = true;
      }
    }

    // fade sections of leds[] array at different rates
    // NOTE: "&leds[0]" and "leds" both point to the beginning of the array
    fadeToBlackBy(&leds [0], 30,  3);               //  long tail
    fadeToBlackBy(&leds[30], 30, 10);               //   mid tail
    fadeToBlackBy(&leds[60], 30, 20);               // short tail
    fadeToBlackBy(&leds[90],  5,  1);               // really long tail

    if (tick[0]) {    // 10 ms tick
      tick[0] = false;
      leds[indx] = CRGB::White;                   // add the "running dot" after fades are applied
      indx++;
      if (indx > (NUM_LEDS-1)) indx = 0;
    }

    if (tick[1]) {    // 20 ms tick
      tick[1] = false;

//    the &test[0] points to the array element directly
//    it allows the choice of a starting point for the fade function

//    fadeToBlackBy( test,    3, 16);               // these two lines are the same
      fadeToBlackBy(&test[0], 3, 16);               // fade only first three elements in the array
      fadeToBlackBy(&test[3], 1, 20);               // fade only the third element in the array

      if(test[0].r < 64){                           // pixels faded enough
        test[0]= CRGB(248, 11, 130);                // reload pixels
        test[1]= CRGB(221, 245, 6);
        test[2]= CRGB(112, 16, 236);
        test[3]= CRGB(16, 236, 53);
      }
    }
 memcpy(&leds[10], test,     4 * sizeof(CRGB));    // apply 4 pixels to leds[] array
 memcpy(&leds[50], &test[0], 4 * sizeof(CRGB));    // apply 4 pixels to leds[] array
 memcpy(&leds[80], &test[1], 3 * sizeof(CRGB));    // apply 3 pixels to leds[] array

    FastLED.show();                                   // send pixel data to the LED strip
  }
}
```


message:
How do I make the Arduino print on my Mac's Arduino IDE through Bluetooth?

This is a basic question, but I really have tried my best to find a solution on the internet to no avail.

I have a fairly normal setup. HC05 module connected to an Arduino. The HC05 is also connected to my Mac's Bluetooth (fairly sure of this bc I used AT Commands to confirm). However, when I select the HC05 port in the Arduino IDE, nothing is printed in that port's serial monitor. Am I fundamentally misunderstanding something?

How do I make the Arduino print on my Mac's Arduino IDE through Bluetooth?

Here's my code:

```
#include <SoftwareSerial.h>

SoftwareSerial MegaloDon(10, 11);

bool isConnected = false;

void setup() {
  pinMode(9, HIGH); //this pin is connected to "EN" on the HC05 and enables AT commands
  Serial.begin(9600);
  MegaloDon.begin(9600); //
  connectBluetooth();
}

void connectBluetooth() {
    digitalWrite(9, HIGH);
    MegaloDon.println("AT"); //AT command
    if (MegaloDon.find("OK")){
      MegaloDon.println("Bluetooth ON");
      digitalWrite(9, LOW);
      Serial.println("Connected");
    } else {
      Serial.println("Attempting to reconnect...");
      delay(2000); // wait 2 seconds before trying again
    }
  }

void loop() {
  if (isConneced()) {
    Serial.println("conneced?");
    **//I'd like to transmit data to my mac's serial monitor on the Arduino IDE here**

  } else {
    Serial.println("not conneced");
    connectBluetooth(); // Attempt to reconnect
  }
}

bool isConneced(){
  Serial.println("is it conneced?");
  digitalWrite(9, HIGH);
  MegaloDon.println("AT");
    if (MegaloDon.find("OK")){
      isConnected = true;
    }
    else{
      isConnected = false;
    }
    digitalWrite(9, LOW);
}

```

body:
I see two problems:

1. Your AT commands don't actually confirm, that the HC05's bluetooth is connected to anything. You are only ever sending "AT", which sets the HC05 to AT mode for a specific amount of time. So basically you are only testing the Serial connection between the Arduino and the HC05. If you want to get other information from the HC05, you need to get into AT mode and then use other AT commands (so commands with the "AT" at the start but other information following that) to check the connection.

    So the question is: Is the HC05 really connected to the Mac? The HC05 can be either in device or master mode for bluetooth. When in device mode, the Mac will be able to initiate the connection (like with any other bluetooth device like a headset). When it is in master mode, it itself has to initiate the connection (then the Mac would need to be the device), which would need to be done with AT commands. How exactly do you know, that the HC05 is connected to the Mac and that you are looking at the correct port in the Arduino IDE? Does the port vanish and reappear, when you turn the Arduino/HC05 combo off and a little bit later on again?

2. In your code you are only sending data through the `MegaloDon` interface at one point:

        MegaloDon.println("Bluetooth ON");

     All the other calls to `MegaloDon` are the "AT" command. And this line is executed directly after sending "AT" to the HC05 and getting "OK" back. Do you remember what I wrote above? The "AT" command will set the HC05 to AT mode for a limited amount of time (typically 1 or 2 seconds). The firmware on the HC05 will then try to interpret all data send in this time as AT commands. It will not send this data through the bluetooth interface! So, if you want to send that data to the Mac, then you should wait with sending it for a bit, so that the HC05 is no longer in AT mode.


message:
How to produce multiple DC voltages for a single project with different dc requirements

I have a project that has 2 12V .2 amp fans, and 1 30 3 amp LED COB panel, and a 5 V Arduino. I was wondering if there was a simple method to power all of these devices from a 120 V wall outlet?

As of right now considering a 30 volt AC to DC power supply. Then a series of switch buck converters. Or something along these lines.

Thanks for the help.(also I realize there was a similar post before but wanted some additional insight)

body:
If it wasn't for the LED panel then I'd say use a mains to 12V DC power supply. You can then get small off the shelf switching regulator modules that with the addition of a couple of capacitors will reduce that down to 5V for the arduino.

If you genuinely need 3A at 30V (90 Watts of LEDs? That's a LOT of light) then use a compatible mains supply for that.
You can get off the shelf switching modules that will drop from ~30V down to 12V 1A, they are a little more expensive than 12V to 5V parts, mainly because it's a less common requirement, but a quick search on RS shows up some options for around $15.


message:
Send data through SPI with DMA

I need to send data as fast as possible from an Arduino DUE to an extern DAC. To do so I use DMA & SPI and I want DMA to fetch data from the memory and send it to the SPI which will just relay it via its Master Output Slave input.
So far I did a DMA transfer from a variable to another, woked perfectly. I'm using the same code but change the address as SPI_TDR (Transmit Data Register), unfortunatly it's not working. I guess the address is not good but if so what should I do ?

Here is my code :
```
#include <dmac.h>
#include <SPI.h>

#define DMA_CH 0         //N° Canal du DMA
#define DMA_BUF_SIZE 32  //Taille mémoire DMA

uint32_t g_dma_buf2[DMA_BUF_SIZE];

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

  SPI0->SPI_WPMR = 0x53504900;             //Protection key
  SPI0->SPI_IDR = 0x0000070F;              //Desactivation interrupts
  SPI0->SPI_MR = SPI_MR_MSTR | SPI_MR_PS;  //SPI master
}

void loop() {
  Serial.println("+++++");
  pmc_enable_periph_clk(ID_DMAC);

  uint32_t i;
  uint32_t cfg;
  dma_transfer_descriptor_t desc;

  for (i = 0; i < DMA_BUF_SIZE; i++) {
    g_dma_buf2[i] = i;
    Serial.print(g_dma_buf2[i]);
  }
   Serial.println();

  dmac_init(DMAC);
  dmac_set_priority_mode(DMAC, DMAC_PRIORITY_ROUND_ROBIN);
  dmac_enable(DMAC);
  cfg = DMAC_CFG_SOD_ENABLE | DMAC_CFG_AHB_PROT(1) | DMAC_CFG_FIFOCFG_ALAP_CFG;  //Config registre CFG
  dmac_channel_set_configuration(DMAC, DMA_CH, cfg);

  desc.ul_source_addr = (uint32_t)g_dma_buf2;
  desc.ul_destination_addr = SPI0->SPI_TDR;
  desc.ul_ctrlA = DMAC_CTRLA_BTSIZE(DMA_BUF_SIZE) | DMAC_CTRLA_SRC_WIDTH_WORD | DMAC_CTRLA_DST_WIDTH_WORD;
  desc.ul_ctrlB = DMAC_CTRLB_SRC_DSCR_FETCH_DISABLE | DMAC_CTRLB_DST_DSCR_FETCH_DISABLE | DMAC_CTRLB_FC_MEM2MEM_DMA_FC | DMAC_CTRLB_SRC_INCR_INCREMENTING | DMAC_CTRLB_DST_INCR_FIXED;
  desc.ul_descriptor_addr = 0;

  SPI_Enable(SPI0);
  dmac_channel_multi_buf_transfer_init(DMAC, DMA_CH, &desc);
  dmac_channel_enable(DMAC, DMA_CH);
  Serial.println("*****");

  while (!dmac_channel_is_transfer_done(DMAC, DMA_CH)) { Serial.print('X'); }
Se
  Serial.print("SR : "); Serial.println(SPI0->SPI_SR, HEX);
  Serial.print("TDR : "); Serial.println(SPI0->SPI_TDR, HEX);
  Serial.print("PSR : "); Serial.println(PIOA->PIO_PSR, HEX);   //PIO_SODR
  Serial.print("OSR : "); Serial.println(PIOA->PIO_OSR, HEX);
  Serial.println(DMAC->DMAC_CH_NUM[0].DMAC_SADDR , HEX);
  Serial.println(DMAC->DMAC_CH_NUM[0].DMAC_DADDR, HEX);
  Serial.println("-----");
}
```
I use mainly this example : https://ww1.microchip.com/downloads/en/Appnotes/Atmel-42291-SAM3A-3U-3X-4E-DMA-Controller-DMAC_ApplicationNote_AT07892.pdf#_OPENTOPIC_TOC_PROCESSING_d91e3076
And here is the datasheet of the µc : https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

You can see at the bottom of my code sevral prints, from them I had many idea : does the PIO could block the data ? Does the address PIO_PA26A_SPI0_MOSI could work ? Could the SPI block the data because conditions are not met ?

Any idea is welcomed, I'm on this for some time now.

Edit :  SPI is not an necessity, the idea is to send data without length limit (unlike UART). I'm considering using SSC.

body:
I managed to solve it but not with SPI, I use the SSC of the µcontroller (which does I²S and uses DMA automatically) :
```
uint32_t liste[] PROGMEM = { 0x8F66F1, 0x0, 0xAAAAAB };  //Data to send
#define DMA_BUF_SIZE (sizeof(liste) / sizeof(liste[0]))  //Size DMA buffer

uint32_t i;

void setup() {
  uint clk_div = 0x90;  //Clock divider wanted
  clk_div = (clk_div / 24) / DMA_BUF_SIZE;
  clk_div = floor(clk_div + 0.5);
  clk_div = clk_div * 24 * DMA_BUF_SIZE;  //Clock divider adjusted -> MCK/2*clk_div

  PMC->PMC_WPMR = 0x504D4300;                                    //Desactivation protection PMC
  PMC->PMC_PCER0 = (1 << ID_SSC);                                //Activation SSC clock
  PMC->PMC_SCER |= 0x100;                                        //Activation clock
  PIOA->PIO_WPMR = 0x50494F00;                                   //Desactivation protection Port I/O A
  PIOA->PIO_PDR = PIO_PDR_P14 | PIO_PDR_P15 | PIO_PDR_P16;       //I/O controlled by the peripheral
  PIOA->PIO_ABSR |= PIO_PA14B_TK | PIO_PA15B_TF | PIO_PA16B_TD;  //Assignation of I/O to SSC

  SSC->SSC_CR = SSC_CR_RXDIS | SSC_CR_TXDIS | SSC_CR_SWRST;                                                     //Desactivation and reset SSC
  SSC->SSC_WPMR = 0x53534300;                                                                                //Desactivation protection SSC
  SSC->SSC_IDR = 0xFFFFFFFF;                                                                                //Desactivation Interrupts
  SSC->SSC_IER = 0x00000000;                                                                                //Desactivation Interrupts bis
  SSC->SSC_CMR = clk_div;                                                                                //Clock management
  SSC->SSC_TFMR = SSC_TFMR_DATLEN(0x18) | SSC_TFMR_MSBF | SSC_TFMR_DATNB(0);                                    //Data transfert management
  SSC->SSC_TCMR = SSC_TCMR_CKS_MCK | SSC_TCMR_CKO_CONTINUOUS | SSC_TCMR_START_CONTINUOUS | SSC_TCMR_STTDLY(0);  //Clock during transfert management
  SSC->SSC_CR = SSC_CR_TXEN;                                                                                //Activation transmission SSC
}

void loop() {
  for (i = 0; i < DMA_BUF_SIZE; i++) {
    ssc_write((Ssc*)SSC, (uint32_t)liste[i]);  //Transmission SSC
  }
}
```
In case someone try the same thing.


message:
How to connect NRF24L01 to Wemos D1 R2

I have troubles to connect a NRF24L01 to a Wemos D1 R2 board. I succeeded on an Arduino Uno. Does anyone knows the pinout?

I used (same as with Uno):
```
D13 - SCK
D12 - MI
D11 - MO

D8 and D9 for CE and CSN
```
Code:
```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

// NRF24 Radio
#define CE_PIN   'D8'
#define CSN_PIN  'D9'

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

  // NRF24 Radio
  radio.begin();
  if (!radio.isChipConnected()) {
    Serial.println("ERROR: NRF24 Chip not connected");
  } else {
    Serial.println("NRF24 Chip connected");
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
  }
```
Result:
ERROR: NRF24 Chip not connected

If I use
```
#define CE_PIN   8
#define CSN_PIN  9
```
then Wemos crashes (reboot exception (4)) so I tried with D, but I get warning, maybe related:
```
 warning: multi-character character constant [-Wmultichar]
   22 | RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
      |            ^~~~~~
 warning: multi-character character constant [-Wmultichar]
   22 | RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
```

body:
Select Wemos D1 R2/mini in Tools menu in IDE. Then you can use the Dx names of the pins. Don't put them in quotes.

Since D8 is CS pin at the Uno pin 10 location, you can't use it as CE. And because esp8266 has less pin than Atmega328 of Uno, there is no pin D9. I recommend you to use pins D1 and D2 for CE and CSN.

```
RF24 radio(D1, D2);
```
[Here][1] you can read how the Dx pins are mapped to esp8266 pins and what is the common function of the pins.

[![enter image description here][2]][2]

  [1]: https://arduino.stackexchange.com/questions/75704/what-are-the-best-gpio-pins-to-use-for-my-project/75706#75706
  [2]: https://i.stack.imgur.com/ZH4X5.jpg


message:
MKR 1010 VOLTAGE CONFUSION

Very confused about powering my MKR 1010 on a breadboard. it says use USB , but that is 5.5 v and it specifically says never go above 3.3 v. yet there is a 5 volt pin. So WHAT size EXTERNAL power supply do I need and where to attach it? Some sites say anywhere from 3.3 to 7 and even 12v????

body: As per the reference at [Arduino Docs](https://docs.arduino.cc/hardware/mkr-wifi-1010)! it's nominal input voltage is between 5-7V. But make sure you apply in between 3.3V - 5V. And remember to supply it at power socket and not the 5V port itself.


message:
What kind and where to find power cable for mkr1010?

I see very confusing documentation on powering the arduino mkr 1010. But I would like to know what kind of cable to power (a weird connector port on its side) it with and also can I just put 5 volts + (ac or dc?) into the vin port and connect a ground?

body:
The documentation shows three ways of powering the board see FAQs section Batteries, [Pins and board LEDs][1]

1. Using a USB connector to provide 5V to the board. Typically, this is connected to a USB port on the PC you are using to program the board. Alternatively, a USB cable connected to a standard USB power supply could be used after the program has been loaded.

2. Using the Vin pin to supply a REGULATED 5V (maximum 6V). Of course, this is DC. Yes, you would also connect the power supply GND to the board's GND pin.

3. LiPo battery. This is a little more complicated to use safely and there is documentation on that as well - see the [app note here][2] to start. You **absolutely** need to understand how to use a battery with that board - there are safety concerns in this regard that can't be ignored.

Hope it helps.

  [1]: https://store-usa.arduino.cc/products/arduino-mkr-wifi-1010
  [2]: https://docs.arduino.cc/tutorials/mkr-wifi-1010/mkr-battery-app-note


body: Just if you are wondering,The mkr1010 uses Micro USB (USB-B) arduino doc says. https://docs.arduino.cc/hardware/mkr-wifi-1010


message:
What's Memory Allocation technique in Arduino

I am currently working on an assignment for my embedded systems course, and my professor has asked us to determine the memory allocation technique employed in Arduino. Specifically, I need to identify whether it utilizes best fit, quick fit, worst fit, next fit, or first fit memory allocation methods.

Despite conducting online research and seeking input from my colleagues, We have been unable to find an answer to this question.

I would greatly appreciate any insights or information on the memory allocation technique used in Arduino.

Thank you.

body:
Use the source, Luke!

The AVR-based Arduinos rely on the [avr-libc][] library, which provides
`malloc()` and friends. You can read [the source code][source] online.
It is generously commented, and you can understand pretty well the
allocation strategy by reading the comments alone.

[avr-libc]: https://www.nongnu.org/avr-libc/user-manual/index.html
[source]: http://svn.savannah.gnu.org/viewvc/avr-libc/tags/avr-libc-2_0_0-release/libc/stdlib/malloc.c?revision=2516&view=markup


body:
Long answer short, it used both first-fit and best-fit.

The [malloc][1] function in the [avr-libc][2] makes use of a so-called free list to track the free spaces in the memory.

When there is a memory request, it starts by looping over this list searching for the first exact match **[First Fit]**.

While looping over the list, it keeps track of the piece of memory that will leave the least amount of space(best-fit). If it didn't find the exact match, it uses this piece of memory **[Best Fit]**.

Furthermore, it doesn't use this piece of memory directly, it checks for its size first, if it is big enough, it takes the amount of memory needed and adds the leftover to the free list, else, it allocates the whole piece of memory.

N.B. it allocates new memory space to the heap if it doesn't find the first-fit or best-fit.

---
### Example Scenarios:

1. First Fit:
- Free list: [64, 128, 128, 256, 512, 128]
- Request: 128
- Action: Take the first 128.

2. Best Fit:
- Free list: [64, 256, 512]
- Request: 128
- Action: Take the 256, use 128, and add the other 128 to the free list.

3. Best Fit:
- Free list: [64, 256, 512, 130]
- Request: 128
- Action: Take the 130 and use it all.

Hope things are clear now!

  [1]: http://svn.savannah.gnu.org/viewvc/avr-libc/tags/avr-libc-2_0_0-release/libc/stdlib/malloc.c?revision=2516&view=markup
  [2]: https://www.nongnu.org/avr-libc/user-manual/index.html


message:
Creating an IPAddress object from an unsigned int

If I create an IPAddress object using a decimal IP address, it appears to be reversed.
What am I doing wrong? See code examples below.

```
IPAddress addressOne(192,168,50,1);
Serial.print(addressOne);                // ==> prints "192.168.50.1"

//The decimal version of 192.168.50.1 is 3232248321
unsigned int iAddress = 3232248321;
IPAddress addressTwo(iAddress);
Serial.print(addressTwo);                // ==> prints "1.50.168.192"
```

body:
You just found out that this `IPAddress` constructor interprets its
parameter in little endian order. Then encode your address as
little-endian:

```c++
//The decimal version of 192.168.50.1 is 20097216
unsigned int iAddress = 20097216;
```


message:
help with error: cant open device "\\.\COM6":Access is denied

I built a new pc which I use as a flight simulator. On my old PC I had ArduinoIDE for programming a pro micro as well as a teensy 4.1 using the teensyduino library. I installed all the necessary libraries and can make revisions to the code for the Teensy and successfully upload them. However when I try to upload anything to the arduino I get the above mentioned error.  The old pc could program the arduino without a problem.

The arduino is showing up in device manager and it disappears when the usb cable is unplugged. The correct port is chosen in the tools menu and I can get the board info. I just can upload it to the board. Still using  windows 10 pro, the same OS as on the previous pc.

Running the arduino IDE (v2.1.0) as admin does not help.

body: Installing Arduino 1.8.19 solved the problem. I guess v2.1.0 has some  code that trips over itself.


message:
Tone() generates a high pitched sound when button is released

I have a simple circuit that makes use of the `tone()` function to produce some sounds.
I also have a button, hooked with an interrupt function, that whenever is pressed, a variable changes.

Sometimes, when the button is pressed, a high pitched sound is produced. What is weird is that this does not happen every time.

You can take a look at this simulation:
https://wokwi.com/projects/291958456169005577

If you press the buttons continuously, you will hear the sound.

Why is this sound triggered? Is there a way to mitigate this?
Perhaps making changes to the `tone()` function? Or perhaps placing a low-pass filter - as this seems like a high frequency sound?

body:
My explanation for this issue is that the last pulse generated by the `tone()` function is interrupted while the output is on a high level. This results in the last pulse being shorter than it should be to correspond to the desired sound frequency.

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

While the pulse length doesn't matter for a continuous output (where the pulse frequency determines the sound frequency), a single short pulse can be interpreted as a pulse of a higher frequency.
According to Fourier theory at least its fundamental frequency will be higher than the one of the longer pulses.

## Observations that might substantiate my theory:
  - the issue happens randomly in ~50% of the cases (for a 50% duty cycle signal).
  - the frequency of the erronous tone varies and is always higher than the desired frequency, depending on how short the trailing pulse is.

These seem to be the case for the simulation.

## Possible fixes:

  a) provide the `tone()` function with the optional `duration` argument and hope the library itself addresses this problem (which it actually might not as the issue is even in the simulation)

  b) make sure to only use multiples of the square wave period for `duration`, so the wave always stops on a low level

According to my theory, a low-pass filter will not work as a fix because the fault frequency can be close to the desired frequency and is the "primary signal", not just some low amplitude harmonic which would be easier to filter from a (much stronger) fundamental.

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


body:
Here is the result of my investigation.

The problem is caused by two factors.

First one is the contact bounce of the switch.

Second one is inadequate pullup strength at the switch, but this may be a simulator issue.

The attached picture shows the data that was captured by the Wokwi logic analyzer module.

The top trace pair shows the tone when the switch bounce is turned off in the simulator.

The rest of the traces are labeled.

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

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


message:
Why does the interrupt not work after pressing the button

Implement interrupt processing when the button is pressed, and the very start on the rising edge, the interrupt pin and to which the button is connected 11. Why does the interrupt not work after pressing the button?

    #include <PinChangeInterrupt.h>

    const uint8_t buttonPin = 11;
    volatile bool buttonPressed = false;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      attachPCINT(buttonPin, buttonISR, RISING);
      Serial.begin(9600);
    }

    void loop() {
      if (buttonPressed) {
        Serial.println("Button pressed!");
        buttonPressed = false;
      }
    }

    void buttonISR() {
      buttonPressed = true;
    }
Model: [![enter image description here][1]][1]

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

body:
I just tested proper code with some changes:

<!-- language: c++ -->

    #include <PinChangeInterrupt.h>

    const uint8_t buttonPin = 11;

    volatile bool buttonPressed = false;

    void buttonISR() {
      buttonPressed = true;
    }

    void loop() {
      if (buttonPressed) {
        delay(20);
        buttonPressed = false;

        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
      }
    }

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      attachPCINT(digitalPinToPCINT(buttonPin), buttonISR, RISING);

      pinMode(LED_BUILTIN, OUTPUT);
    }

And with `attachPCINT(digitalPinToPCINT(buttonPin), buttonISR, RISING);` it works flawlessly. Only difference is that `digitalPinToPCINT` (as every example for PinChangeInterrupt library tries to suggest).

You also tried attachInterrupt + digitalPinToInterrupt with the pin 11, but Arduino Uno has only two external interrupt capable pins D2 and D3. So it couldn't work with D11. It also depends on MCU (see [attachInterrupt() reference](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/)).

The PCINT is more or less related to the old AVRs like Atmega328 or Atmega2560. And PCINT in Atmega2560 isn't available on all port (it uses ISR per port and it has many ports.

If the proteus simulator is the cause, you can also ommit the ISR (as you are not doing anything big here) and just poll the pin:

    const uint8_t buttonPin = 11;
    bool buttonPressed = false;

    void loop() {
      bool pinHigh = (digitalRead(buttonPin) == HIGH);

      if (pinHigh && buttonPressed) { // button released
        delay(20);
        buttonPressed = false;
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
      } else if (!pinHigh && !buttonPressed) {
        buttonPressed = true;
      }
    }

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(LED_BUILTIN, OUTPUT);
    }


message:
How much time does it take to propagate the control signal through all LEDs in the ws2812b strip?

In my next small Arduino project, I wanted to use some addressable rgb led strips.
I made some small research and choose to use a strip with ws2812b.
Generally, I know how this works but I am not 100% sure if what I think is correct. So please correct me if I am wrong.

For each pixel in the strip, we need to send 24 bits to control it.
If we have 10 pixels in a strip then we need to send 240 bits. Then first pixel reads all 240 bits, sets itself color, and lastly propagates other 216 bits to the next pixel. And so on to the last pixel.

I am wondering, how much time does it take to update state of the last pixel in strip?

If sending 24 bit takes something about 30us (1.25us for 1 bit) then is that mean that sending signals to the last pixel in a strip with 10 pixels would take 300us + 270us + 240us + ... + 30us or is it rather just 300us?

body:
I have [a page about the WS2812 chip](http://www.gammon.com.au/forum/?id=13357) along with a suggested way of writing code simply for it. It also describes the timing.

The documented timing for a 0-bit is 1150 ns and for a 1-bit is 1300 ns.

[![NeoPixels timing][1]][1]

Thus, if we assume all bits are on, then 24 bits would take 24 * 1300 ns which is 31.2 µs.

Since the bits are propagated along the strip, then it would take 10 * 31.2 µs (312 µs) to send all 10 colours.

What I mean by "propagated" is that as each bit arrives at each chip it also forwards it onward to the next chip, much like a shift register. Thus the more bits you send the further the original ones are "pushed" towards the end of the strip.

As the documentation describes, each chip "reshapes" the incoming bit, so that any jitter or noise in the arriving bit is cleaned up as it is forwarded so that the individual bits do not degrade as they are forwarded. Think of [Chinese Whispers](https://en.wikipedia.org/wiki/Chinese_whispers) - because of the reshaping by each chip the information is **not** corrupted as it is passed on.

Then you send 50 µs of 0V to latch the new colours to the entire strip.

So, the answer to your question is 362 µs (roughly).

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


message:
Same Bin file to similar ESP32 boards yields different results

Sorry for the confusing title. It is a bit hard to explain.

We have a remote developer who compiles his code into a bin file and sends it to all of us. He loads it onto his ESP32 boards and they work just fine. However, when we load the bin file onto our ESP32 boards, they do not work. We are all using the same configuration ESP32 boards. We are all using Expressif Flash Download tool to load the bin file.

Where would y'all recommend I start my investigation? What additional info do you need from me to help figure this out? I have confirmed that we are all using the same ESP32 boards as well as the same flash tool. Ideas?

By the way, I am not the programmer, I do not have access to the source code. I only have the bin file.

Thank you

body:
My fault. I hadn't wired the final product exactly as the designer had. Once the wiring was correct the issue was resolved. Just needed a physical troubleshooting as the software troubleshooting wasn't the issue.

Funny thing is, there are only two wires on the entire project and I had gotten them wrong.

So I think the lesson here is, check your physical configuration as well as the software/firmware.

Thank you all for your help.


message:
50% duty cycle PWM signal with calculated frequency

```
#include <PWM.h>
int led = 9;
void setup()
{
  InitTimersSafe();
  Serial.begin(115200);
  Serial.println();
  variable_freq();
  pinMode(A0,INPUT);
}
void variable_freq()
{
   while(true)
 {
   a=analogRead(A0);
   float p = (a/1024)*5;
   int Vi = p/0.143;
   float Vo = 12;
   float Po=100;
   float n=1, ni=0.9, Ntr=1, Vf=0.7, Rf=0.018, rc=0.025, Mvs=0.9;
   float Rl=(Vo*Vo)/Po;
   float fo = 70000;
   float Mv = Vo/Vi;
   float Qo=6;
   float pi = 3.14159;
   float g ;
   g= (1+(2*(Vf/Vo))+((Rf*pi*pi)/4*Rl)+(rc/Rl)*(((pi*pi)/8)-1));
   float Ri=((8*Rl*n*n)/(Ntr*pi*pi))*g;
   float Mvr, MVR, h;
   Mvr=(pi*Ntr)/(2*n*sqrt(2)*g);
   MVR=Mv/(Mvs*Mvr);
   h=(sqrt((pow((ni/MVR), 2))-1))/Qo;
   float f_sw;
   f_sw = ((fo*h)/2) + (sqrt(pow(fo*h,2) + 4*pow(fo,2)))/2;

   SetPinFrequency(led,f_sw);

   float T = 0.5;

   pwmWriteHR(led,T*65536);
 }
}
```
I am working on a project where I have to find a required frequency from a varying DC input voltage. I am using Arduino Nano to produce a PWM signal of this required freqeuncy.

From the code, once the frequency *f_sw* is calculated, I have used the *setPinFrequency* function to set the frequency of pin D9 to *f_sw*. I want a PWM signal of duty cycle 50% with f_sw as the frequency.

Does pwmWriteHR(led,T*65536) accomplish this? As per [this website][1], pwmWrite()'s 2nd argument is the duty cycle. Given that pwmWriteHR() is just the higher resolution version of pwmWrite(), will this output the signal as per my requirements?

I cannot test this on a board yet, so I simulated it in Proteus, but the frequency of the signal I obtained there does not match, although the duty cycle was 50%.

  [1]: https://rambutan.readthedocs.io/projects/librambutan/en/latest/lang/api/pwmwrite.html

body:
Let's look at what's possible using the Atmega328P (which is on the Nano).

The timers are really just counters, with the input to the counter being the system clock, possibly after being divided down by a prescaler.

Timers 0 and 2 are 8-bit timers which means they can count to 256 before wrapping around. Timer 1 is a 16-bit timer which means it can count to 65536 before wrapping. The inputs to the timers are zero-relative, so the actual counter limits are 255 (0xFF) and 65535 (0xFFFF).

Your desired frequency of 76441 means the period is 1/76441 seconds, namely 13.082 µs.

With no prescaler, the period of the system clock is 1/16000000, namely 0.0625 µs.

Divide 13.082 by 0.0625 and you get 209.312 which means 209 counts are going to roughly get you the frequency you want.

However then we have to divide by 2 because each time the counter counts up we toggle the output, and it takes two toggles to do one period (one up, one down).

So we need to set up a timer of 209/2 which is 104.5. Since we can't count up to half a count we actually count up to 104. The code to do that, without needing any libraries, is:

---

## Example code

<!-- language: c++ -->

    void setup()
      {
      pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

      unsigned long Hz = 76441;

      // it takes two toggles for one "cycle"
      unsigned long ocr = (F_CPU / Hz / 2) - 1;

      // stop timer
      TCCR1A = 0;
      TCCR1B = 0;
      // reset counter
      TCNT1H = 0;
      TCNT1L = 0;

      // what to count up to
      OCR1AH = highByte (ocr);
      OCR1AL = lowByte (ocr);

      TCCR1A = bit (COM1A0);              // toggle output pin
      TCCR1B = bit (WGM12) | bit (CS10);  // start timer, CTC mode
      }  // end of setup

    void loop() { }

The results on pin 9 were measured as 76.805 kHz which is slightly out, partly because of the fact that the resolution is in increments of 62.5 ns, and partly because the Nano has resonator\* rather than a crystal, so its clock might not be exactly 16 MHz.

\* I'm not sure about that.

---

## Duty cycle

In this particular example we have a 50% duty cycle because each time the timer reaches its count it toggles the output. Thus it does it symmetrically. That is, the on portion will be the same length as the off portion.

There are other timer modes which can be used for PWM generation where the duty cycle is not 50%. See the datasheet for more information.

---

## Prescaler

The prescalers (not used in this particular example) are used to extend the length of time that a timer can count for.

Possible prescalers are 1, 8, 32, 64, 128, 256, and 1024. Prescalers of 32 and 128 are only available on timer 2.

So, for example, if you use a prescaler of 8 then each "tick" of the timer will be 8 * 62.5 ns, so it can count for 8 times as long before it overflows. However each count will only have a resolution of 500 ns rather than 62.5 ns, so you can get a less precise time measurement.

Choosing prescalers is a compromise between resolution and the available time period you can time for.

---

See [my page about timers](http://gammon.com.au/timers) for more discussion about the Atmega328P timers.

---

## List of possible frequencies

From my page above I reproduce this list which shows what frequency and period you get for various timer counts, and prescalers.

      n  -- Prescale 1   --  -- Prescale 8   --  -- Prescale 64  --  -- Prescale 256 --  -- Prescale 1024--
         Freq (Hz) Per (µs)  Freq (Hz) Per (µs)  Freq (Hz) Per (µs)  Freq (Hz) Per (µs)  Freq (Hz) Per (µs)
      1: 8,000,000*   0.125  1,000,000    1.000    125,000    8.000     31,250   32.000      7,813  128.000
      2: 5,333,333    0.188    666,667    1.500     83,333   12.000     20,833   48.000      5,208  192.000
      3: 4,000,000    0.250    500,000    2.000     62,500   16.000     15,625   64.000      3,906  256.000
      4: 3,200,000    0.313    400,000    2.500     50,000   20.000     12,500   80.000      3,125  320.000
      5: 2,666,667    0.375    333,333    3.000     41,667   24.000     10,417   96.000      2,604  384.000
      6: 2,285,714    0.438    285,714    3.500     35,714   28.000      8,929  112.000      2,232  448.000
      7: 2,000,000    0.500    250,000    4.000     31,250   32.000      7,813  128.000      1,953  512.000
      8: 1,777,778    0.563    222,222    4.500     27,778   36.000      6,944  144.000      1,736  576.000
      9: 1,600,000    0.625    200,000    5.000     25,000   40.000      6,250  160.000      1,563  640.000
     10: 1,454,545    0.688    181,818    5.500     22,727   44.000      5,682  176.000      1,420  704.000
     11: 1,333,333    0.750    166,667    6.000     20,833   48.000      5,208  192.000      1,302  768.000
     12: 1,230,769    0.813    153,846    6.500     19,231   52.000      4,808  208.000      1,202  832.000
     13: 1,142,857    0.875    142,857    7.000     17,857   56.000      4,464  224.000      1,116  896.000
     14: 1,066,667    0.937    133,333    7.500     16,667   60.000      4,167  240.000      1,042  960.000
     15: 1,000,000    1.000    125,000    8.000     15,625   64.000      3,906  256.000        977 1024.000
     16:   941,176    1.063    117,647    8.500     14,706   68.000      3,676  272.000        919 1088.000
     17:   888,889    1.125    111,111    9.000     13,889   72.000      3,472  288.000        868 1152.000
     18:   842,105    1.187    105,263    9.500     13,158   76.000      3,289  304.000        822 1216.000
     19:   800,000    1.250    100,000   10.000     12,500   80.000      3,125  320.000        781 1280.000
     20:   761,905    1.313     95,238   10.500     11,905   84.000      2,976  336.000        744 1344.000
     21:   727,273    1.375     90,909   11.000     11,364   88.000      2,841  352.000        710 1408.000
     22:   695,652    1.438     86,957   11.500     10,870   92.000      2,717  368.000        679 1472.000
     23:   666,667    1.500     83,333   12.000     10,417   96.000      2,604  384.000        651 1536.000
     24:   640,000    1.562     80,000   12.500     10,000  100.000      2,500  400.000        625 1600.000
     25:   615,385    1.625     76,923   13.000      9,615  104.000      2,404  416.000        601 1664.000
     26:   592,593    1.688     74,074   13.500      9,259  108.000      2,315  432.000        579 1728.000
     27:   571,429    1.750     71,429   14.000      8,929  112.000      2,232  448.000        558 1792.000
     28:   551,724    1.813     68,966   14.500      8,621  116.000      2,155  464.000        539 1856.000
     29:   533,333    1.875     66,667   15.000      8,333  120.000      2,083  480.000        521 1920.000
     30:   516,129    1.938     64,516   15.500      8,065  124.000      2,016  496.000        504 1984.000
     31:   500,000    2.000     62,500   16.000      7,813  128.000      1,953  512.000        488 2048.000
     32:   484,848    2.062     60,606   16.500      7,576  132.000      1,894  528.000        473 2112.000
     33:   470,588    2.125     58,824   17.000      7,353  136.000      1,838  544.000        460 2176.000
     34:   457,143    2.188     57,143   17.500      7,143  140.000      1,786  560.000        446 2240.000
     35:   444,444    2.250     55,556   18.000      6,944  144.000      1,736  576.000        434 2304.000
     36:   432,432    2.313     54,054   18.500      6,757  148.000      1,689  592.000        422 2368.000
     37:   421,053    2.375     52,632   19.000      6,579  152.000      1,645  608.000        411 2432.000
     38:   410,256    2.438     51,282   19.500      6,410  156.000      1,603  624.000        401 2496.000
     39:   400,000    2.500     50,000   20.000      6,250  160.000      1,563  640.000        391 2560.000
     40:   390,244    2.563     48,780   20.500      6,098  164.000      1,524  656.000        381 2624.000
     41:   380,952    2.625     47,619   21.000      5,952  168.000      1,488  672.000        372 2688.000
     42:   372,093    2.687     46,512   21.500      5,814  172.000      1,453  688.000        363 2752.000
     43:   363,636    2.750     45,455   22.000      5,682  176.000      1,420  704.000        355 2816.000
     44:   355,556    2.812     44,444   22.500      5,556  180.000      1,389  720.000        347 2880.000
     45:   347,826    2.875     43,478   23.000      5,435  184.000      1,359  736.000        340 2944.000
     46:   340,426    2.938     42,553   23.500      5,319  188.000      1,330  752.000        332 3008.000
     47:   333,333    3.000     41,667   24.000      5,208  192.000      1,302  768.000        326 3072.000
     48:   326,531    3.063     40,816   24.500      5,102  196.000      1,276  784.000        319 3136.000
     49:   320,000    3.125     40,000   25.000      5,000  200.000      1,250  800.000        313 3200.000
     50:   313,725    3.188     39,216   25.500      4,902  204.000      1,225  816.000        306 3264.000
     51:   307,692    3.250     38,462   26.000      4,808  208.000      1,202  832.000        300 3328.000
     52:   301,887    3.313     37,736   26.500      4,717  212.000      1,179  848.000        295 3392.000
     53:   296,296    3.375     37,037   27.000      4,630  216.000      1,157  864.000        289 3456.000
     54:   290,909    3.437     36,364   27.500      4,545  220.000      1,136  880.000        284 3520.000
     55:   285,714    3.500     35,714   28.000      4,464  224.000      1,116  896.000        279 3584.000
     56:   280,702    3.562     35,088   28.500      4,386  228.000      1,096  912.000        274 3648.000
     57:   275,862    3.625     34,483   29.000      4,310  232.000      1,078  928.000        269 3712.000
     58:   271,186    3.688     33,898   29.500      4,237  236.000      1,059  944.000        265 3776.000
     59:   266,667    3.750     33,333   30.000      4,167  240.000      1,042  960.000        260 3840.000
     60:   262,295    3.813     32,787   30.500      4,098  244.000      1,025  976.000        256 3904.000
     61:   258,065    3.875     32,258   31.000      4,032  248.000      1,008  992.000        252 3968.000
     62:   253,968    3.938     31,746   31.500      3,968  252.000        992 1008.000        248 4032.000
     63:   250,000    4.000     31,250   32.000      3,906  256.000        977 1024.000        244 4096.000
     64:   246,154    4.063     30,769   32.500      3,846  260.000        962 1040.000        240 4160.000
     65:   242,424    4.125     30,303   33.000      3,788  264.000        947 1056.000        237 4224.000
     66:   238,806    4.188     29,851   33.500      3,731  268.000        933 1072.000        233 4288.000
     67:   235,294    4.250     29,412   34.000      3,676  272.000        919 1088.000        230 4352.000
     68:   231,884    4.313     28,986   34.500      3,623  276.000        906 1104.000        226 4416.000
     69:   228,571    4.375     28,571   35.000      3,571  280.000        893 1120.000        223 4480.000
     70:   225,352    4.437     28,169   35.500      3,521  284.000        880 1136.000        220 4544.000
     71:   222,222    4.500     27,778   36.000      3,472  288.000        868 1152.000        217 4608.000
     72:   219,178    4.563     27,397   36.500      3,425  292.000        856 1168.000        214 4672.000
     73:   216,216    4.625     27,027   37.000      3,378  296.000        845 1184.000        211 4736.000
     74:   213,333    4.688     26,667   37.500      3,333  300.000        833 1200.000        208 4800.000
     75:   210,526    4.750     26,316   38.000      3,289  304.000        822 1216.000        206 4864.000
     76:   207,792    4.813     25,974   38.500      3,247  308.000        812 1232.000        203 4928.000
     77:   205,128    4.875     25,641   39.000      3,205  312.000        801 1248.000        200 4992.000
     78:   202,532    4.938     25,316   39.500      3,165  316.000        791 1264.000        198 5056.000
     79:   200,000    5.000     25,000   40.000      3,125  320.000        781 1280.000        195 5120.000
     80:   197,531    5.062     24,691   40.500      3,086  324.000        772 1296.000        193 5184.000
     81:   195,122    5.125     24,390   41.000      3,049  328.000        762 1312.000        191 5248.000
     82:   192,771    5.188     24,096   41.500      3,012  332.000        753 1328.000        188 5312.000
     83:   190,476    5.250     23,810   42.000      2,976  336.000        744 1344.000        186 5376.000
     84:   188,235    5.312     23,529   42.500      2,941  340.000        735 1360.000        184 5440.000
     85:   186,047    5.375     23,256   43.000      2,907  344.000        727 1376.000        182 5504.000
     86:   183,908    5.438     22,989   43.500      2,874  348.000        718 1392.000        180 5568.000
     87:   181,818    5.500     22,727   44.000      2,841  352.000        710 1408.000        178 5632.000
     88:   179,775    5.563     22,472   44.500      2,809  356.000        702 1424.000        176 5696.000
     89:   177,778    5.625     22,222   45.000      2,778  360.000        694 1440.000        174 5760.000
     90:   175,824    5.687     21,978   45.500      2,747  364.000        687 1456.000        172 5824.000
     91:   173,913    5.750     21,739   46.000      2,717  368.000        679 1472.000        170 5888.000
     92:   172,043    5.813     21,505   46.500      2,688  372.000        672 1488.000        168 5952.000
     93:   170,213    5.875     21,277   47.000      2,660  376.000        665 1504.000        166 6016.000
     94:   168,421    5.937     21,053   47.500      2,632  380.000        658 1520.000        164 6080.000
     95:   166,667    6.000     20,833   48.000      2,604  384.000        651 1536.000        163 6144.000
     96:   164,948    6.063     20,619   48.500      2,577  388.000        644 1552.000        161 6208.000
     97:   163,265    6.125     20,408   49.000      2,551  392.000        638 1568.000        159 6272.000
     98:   161,616    6.188     20,202   49.500      2,525  396.000        631 1584.000        158 6336.000
     99:   160,000    6.250     20,000   50.000      2,500  400.000        625 1600.000        156 6400.000
    100:   158,416    6.313     19,802   50.500      2,475  404.000        619 1616.000        155 6464.000
    101:   156,863    6.375     19,608   51.000      2,451  408.000        613 1632.000        153 6528.000
    102:   155,340    6.438     19,417   51.500      2,427  412.000        607 1648.000        152 6592.000
    103:   153,846    6.500     19,231   52.000      2,404  416.000        601 1664.000        150 6656.000
    104:   152,381    6.562     19,048   52.500      2,381  420.000        595 1680.000        149 6720.000
    105:   150,943    6.625     18,868   53.000      2,358  424.000        590 1696.000        147 6784.000
    106:   149,533    6.688     18,692   53.500      2,336  428.000        584 1712.000        146 6848.000
    107:   148,148    6.750     18,519   54.000      2,315  432.000        579 1728.000        145 6912.000
    108:   146,789    6.813     18,349   54.500      2,294  436.000        573 1744.000        143 6976.000
    109:   145,455    6.875     18,182   55.000      2,273  440.000        568 1760.000        142 7040.000
    110:   144,144    6.938     18,018   55.500      2,252  444.000        563 1776.000        141 7104.000
    111:   142,857    7.000     17,857   56.000      2,232  448.000        558 1792.000        140 7168.000
    112:   141,593    7.063     17,699   56.500      2,212  452.000        553 1808.000        138 7232.000
    113:   140,351    7.125     17,544   57.000      2,193  456.000        548 1824.000        137 7296.000
    114:   139,130    7.187     17,391   57.500      2,174  460.000        543 1840.000        136 7360.000
    115:   137,931    7.250     17,241   58.000      2,155  464.000        539 1856.000        135 7424.000
    116:   136,752    7.313     17,094   58.500      2,137  468.000        534 1872.000        134 7488.000
    117:   135,593    7.375     16,949   59.000      2,119  472.000        530 1888.000        132 7552.000
    118:   134,454    7.437     16,807   59.500      2,101  476.000        525 1904.000        131 7616.000
    119:   133,333    7.500     16,667   60.000      2,083  480.000        521 1920.000        130 7680.000
    120:   132,231    7.563     16,529   60.500      2,066  484.000        517 1936.000        129 7744.000
    121:   131,148    7.625     16,393   61.000      2,049  488.000        512 1952.000        128 7808.000
    122:   130,081    7.687     16,260   61.500      2,033  492.000        508 1968.000        127 7872.000
    123:   129,032    7.750     16,129   62.000      2,016  496.000        504 1984.000        126 7936.000
    124:   128,000    7.813     16,000   62.500      2,000  500.000        500 2000.000        125 8000.000
    125:   126,984    7.875     15,873   63.000      1,984  504.000        496 2016.000        124 8064.000
    126:   125,984    7.938     15,748   63.500      1,969  508.000        492 2032.000        123 8128.000
    127:   125,000    8.000     15,625   64.000      1,953  512.000        488 2048.000        122 8192.000
    128:   124,031    8.063     15,504   64.500      1,938  516.000        484 2064.000        121 8256.000
    129:   123,077    8.125     15,385   65.000      1,923  520.000        481 2080.000        120 8320.000
    130:   122,137    8.188     15,267   65.500      1,908  524.000        477 2096.000        119 8384.000
    131:   121,212    8.250     15,152   66.000      1,894  528.000        473 2112.000        118 8448.000
    132:   120,301    8.313     15,038   66.500      1,880  532.000        470 2128.000        117 8512.000
    133:   119,403    8.375     14,925   67.000      1,866  536.000        466 2144.000        117 8576.000
    134:   118,519    8.438     14,815   67.500      1,852  540.000        463 2160.000        116 8640.000
    135:   117,647    8.500     14,706   68.000      1,838  544.000        460 2176.000        115 8704.000
    136:   116,788    8.563     14,599   68.500      1,825  548.000        456 2192.000        114 8768.000
    137:   115,942    8.625     14,493   69.000      1,812  552.000        453 2208.000        113 8832.000
    138:   115,108    8.688     14,388   69.500      1,799  556.000        450 2224.000        112 8896.000
    139:   114,286    8.750     14,286   70.000      1,786  560.000        446 2240.000        112 8960.000
    140:   113,475    8.812     14,184   70.500      1,773  564.000        443 2256.000        111 9024.000
    141:   112,676    8.875     14,085   71.000      1,761  568.000        440 2272.000        110 9088.000
    142:   111,888    8.938     13,986   71.500      1,748  572.000        437 2288.000        109 9152.000
    143:   111,111    9.000     13,889   72.000      1,736  576.000        434 2304.000        109 9216.000
    144:   110,345    9.063     13,793   72.500      1,724  580.000        431 2320.000        108 9280.000
    145:   109,589    9.125     13,699   73.000      1,712  584.000        428 2336.000        107 9344.000
    146:   108,844    9.188     13,605   73.500      1,701  588.000        425 2352.000        106 9408.000
    147:   108,108    9.250     13,514   74.000      1,689  592.000        422 2368.000        106 9472.000
    148:   107,383    9.313     13,423   74.500      1,678  596.000        419 2384.000        105 9536.000
    149:   106,667    9.375     13,333   75.000      1,667  600.000        417 2400.000        104 9600.000
    150:   105,960    9.437     13,245   75.500      1,656  604.000        414 2416.000        103 9664.000
    151:   105,263    9.500     13,158   76.000      1,645  608.000        411 2432.000        103 9728.000
    152:   104,575    9.563     13,072   76.500      1,634  612.000        408 2448.000        102 9792.000
    153:   103,896    9.625     12,987   77.000      1,623  616.000        406 2464.000        101 9856.000
    154:   103,226    9.688     12,903   77.500      1,613  620.000        403 2480.000        101 9920.000
    155:   102,564    9.750     12,821   78.000      1,603  624.000        401 2496.000        100 9984.000
    156:   101,911    9.813     12,739   78.500      1,592  628.000        398 2512.000        100 10048.000
    157:   101,266    9.875     12,658   79.000      1,582  632.000        396 2528.000         99 10112.000
    158:   100,629    9.938     12,579   79.500      1,572  636.000        393 2544.000         98 10176.000
    159:   100,000   10.000     12,500   80.000      1,563  640.000        391 2560.000         98 10240.000
    160:    99,379   10.062     12,422   80.500      1,553  644.000        388 2576.000         97 10304.000
    161:    98,765   10.125     12,346   81.000      1,543  648.000        386 2592.000         96 10368.000
    162:    98,160   10.188     12,270   81.500      1,534  652.000        383 2608.000         96 10432.000
    163:    97,561   10.250     12,195   82.000      1,524  656.000        381 2624.000         95 10496.000
    164:    96,970   10.313     12,121   82.500      1,515  660.000        379 2640.000         95 10560.000
    165:    96,386   10.375     12,048   83.000      1,506  664.000        377 2656.000         94 10624.000
    166:    95,808   10.438     11,976   83.500      1,497  668.000        374 2672.000         94 10688.000
    167:    95,238   10.500     11,905   84.000      1,488  672.000        372 2688.000         93 10752.000
    168:    94,675   10.563     11,834   84.500      1,479  676.000        370 2704.000         92 10816.000
    169:    94,118   10.625     11,765   85.000      1,471  680.000        368 2720.000         92 10880.000
    170:    93,567   10.687     11,696   85.500      1,462  684.000        365 2736.000         91 10944.000
    171:    93,023   10.750     11,628   86.000      1,453  688.000        363 2752.000         91 11008.000
    172:    92,486   10.813     11,561   86.500      1,445  692.000        361 2768.000         90 11072.000
    173:    91,954   10.875     11,494   87.000      1,437  696.000        359 2784.000         90 11136.000
    174:    91,429   10.938     11,429   87.500      1,429  700.000        357 2800.000         89 11200.000
    175:    90,909   11.000     11,364   88.000      1,420  704.000        355 2816.000         89 11264.000
    176:    90,395   11.063     11,299   88.500      1,412  708.000        353 2832.000         88 11328.000
    177:    89,888   11.125     11,236   89.000      1,404  712.000        351 2848.000         88 11392.000
    178:    89,385   11.188     11,173   89.500      1,397  716.000        349 2864.000         87 11456.000
    179:    88,889   11.250     11,111   90.000      1,389  720.000        347 2880.000         87 11520.000
    180:    88,398   11.312     11,050   90.500      1,381  724.000        345 2896.000         86 11584.000
    181:    87,912   11.375     10,989   91.000      1,374  728.000        343 2912.000         86 11648.000
    182:    87,432   11.438     10,929   91.500      1,366  732.000        342 2928.000         85 11712.000
    183:    86,957   11.500     10,870   92.000      1,359  736.000        340 2944.000         85 11776.000
    184:    86,486   11.563     10,811   92.500      1,351  740.000        338 2960.000         84 11840.000
    185:    86,022   11.625     10,753   93.000      1,344  744.000        336 2976.000         84 11904.000
    186:    85,561   11.688     10,695   93.500      1,337  748.000        334 2992.000         84 11968.000
    187:    85,106   11.750     10,638   94.000      1,330  752.000        332 3008.000         83 12032.000
    188:    84,656   11.813     10,582   94.500      1,323  756.000        331 3024.000         83 12096.000
    189:    84,211   11.875     10,526   95.000      1,316  760.000        329 3040.000         82 12160.000
    190:    83,770   11.937     10,471   95.500      1,309  764.000        327 3056.000         82 12224.000
    191:    83,333   12.000     10,417   96.000      1,302  768.000        326 3072.000         81 12288.000
    192:    82,902   12.063     10,363   96.500      1,295  772.000        324 3088.000         81 12352.000
    193:    82,474   12.125     10,309   97.000      1,289  776.000        322 3104.000         81 12416.000
    194:    82,051   12.188     10,256   97.500      1,282  780.000        321 3120.000         80 12480.000
    195:    81,633   12.250     10,204   98.000      1,276  784.000        319 3136.000         80 12544.000
    196:    81,218   12.313     10,152   98.500      1,269  788.000        317 3152.000         79 12608.000
    197:    80,808   12.375     10,101   99.000      1,263  792.000        316 3168.000         79 12672.000
    198:    80,402   12.437     10,050   99.500      1,256  796.000        314 3184.000         79 12736.000
    199:    80,000   12.500     10,000  100.000      1,250  800.000        313 3200.000         78 12800.000
    200:    79,602   12.562      9,950  100.500      1,244  804.000        311 3216.000         78 12864.000
    201:    79,208   12.625      9,901  101.000      1,238  808.000        309 3232.000         77 12928.000
    202:    78,818   12.688      9,852  101.500      1,232  812.000        308 3248.000         77 12992.000
    203:    78,431   12.750      9,804  102.000      1,225  816.000        306 3264.000         77 13056.000
    204:    78,049   12.813      9,756  102.500      1,220  820.000        305 3280.000         76 13120.000
    205:    77,670   12.875      9,709  103.000      1,214  824.000        303 3296.000         76 13184.000
    206:    77,295   12.938      9,662  103.500      1,208  828.000        302 3312.000         75 13248.000
    207:    76,923   13.000      9,615  104.000      1,202  832.000        300 3328.000         75 13312.000
    208:    76,555   13.062      9,569  104.500      1,196  836.000        299 3344.000         75 13376.000
    209:    76,190   13.125      9,524  105.000      1,190  840.000        298 3360.000         74 13440.000
    210:    75,829   13.187      9,479  105.500      1,185  844.000        296 3376.000         74 13504.000
    211:    75,472   13.250      9,434  106.000      1,179  848.000        295 3392.000         74 13568.000
    212:    75,117   13.313      9,390  106.500      1,174  852.000        293 3408.000         73 13632.000
    213:    74,766   13.375      9,346  107.000      1,168  856.000        292 3424.000         73 13696.000
    214:    74,419   13.438      9,302  107.500      1,163  860.000        291 3440.000         73 13760.000
    215:    74,074   13.500      9,259  108.000      1,157  864.000        289 3456.000         72 13824.000
    216:    73,733   13.563      9,217  108.500      1,152  868.000        288 3472.000         72 13888.000
    217:    73,394   13.625      9,174  109.000      1,147  872.000        287 3488.000         72 13952.000
    218:    73,059   13.687      9,132  109.500      1,142  876.000        285 3504.000         71 14016.000
    219:    72,727   13.750      9,091  110.000      1,136  880.000        284 3520.000         71 14080.000
    220:    72,398   13.812      9,050  110.500      1,131  884.000        283 3536.000         71 14144.000

\* = may not work reliably, testing shows.

Space restraints preclude including the entire list, see the page mentioned above for a few more rows.


message:
Problem with using PubSubClient, the "callback" function doesn't seem to work correctly

I have a program that communicate between a esp8266 and a atmega328 using Serial, the esp8266 will connect to a MQTT server running on local network, and publish/subscribe to some topics. In the callback function for the subscribing, it will send an instruction to atmega chip to toggle the LED (pin 13). I am using XC4411 board which is an integrated 2-in-1 board with both esp and atmega.

The code looks like this:
On esp side:
```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "credentials.h" // this is where I define the wifi ssid, psw, mqtt username/psw etc.
#include <Arduino.h>

#define SERIAL_BAUD 115200 //make sure this is the same in atmega code, serial communication with atmega chip
#define ESP8266_LED 1

WiFiClient espWifiClient;
PubSubClient espMQTTClient(espWifiClient);
const char* test_topic = "/test/msg01";
void reconnect();
void callback(char *topic, uint8_t *payload, unsigned int length);

void setup_wifi() {
    delay(10);
    WiFi.begin(MY_SSID, MY_WIFIPSW);
    while (WiFi.status() != WL_CONNECTED) delay(500);
}

void setup_mqtt() {
    espMQTTClient.setServer(MY_MQTT_SERVER_ADDRESS, MY_MQTT_SERVER_PORT);
    reconnect();
    espMQTTClient.subscribe(test_topic);
    espMQTTClient.setCallback(callback);

}

void reconnect() {
    while(! espMQTTClient.connected()) {
        if (espMQTTClient.connect(MY_MQTT_CLIENT_ID, MY_MQTT_USER, MY_MQTT_PSW)) {
            espMQTTClient.subscribe(test_topic);
        }
        else delay(500);
    }
}

void callback(char *topic, uint8_t *payload, unsigned int length) {

    digitalWrite(ESP8266_LED, !digitalRead(ESP8266_LED));
    Serial.println("[toggle]");

    // espMQTTClient.publish("/test/esp8266", topic, length);
    espMQTTClient.publish("/test/esp8266", payload, length);

    if (strcmp(topic, test_topic) == 0) {
        if (length >= 0 && (char) payload[0] == '1') {
            espMQTTClient.publish("/test/esp8266", "get payload 1");
        } else if (length >= 0 && (char) payload[0] == '0') {
            espMQTTClient.publish("/test/esp8266", "get payload 0");
        } else {
            espMQTTClient.publish("/test/esp8266", "unknown payload for topic /test/msg01");
        }

    }
}

void setup() {
    Serial.begin(SERIAL_BAUD);
    setup_wifi();
    setup_mqtt();
    pinMode(ESP8266_LED, OUTPUT);
}

String data_from_arduino = "";

void loop() {
    if (! espMQTTClient.connected()) reconnect();
    espMQTTClient.loop();
    while (Serial.available()) {
        char x = Serial.read();
        if (x == '\r')
   continue;
        data_from_arduino += x;
    }
    if (data_from_arduino != "") {
        espMQTTClient.publish("/test/arduino", data_from_arduino.c_str());
        data_from_arduino = "";
    }
    // espMQTTClient.publish("/test/esp8266", "hello from esp"); // this line works fine, so there is no connection problem
}
```

On atmega side:

```
#include <Arduino.h>

#define SERIAL_BAUD 115200

#define LED_PIN 13

String receivedCommand = "";
bool dataIn = false;

void setup()
{

 Serial.begin(SERIAL_BAUD); //same as ESP baud
 pinMode(LED_PIN, OUTPUT);
}

String msg_from_esp8266 = "";
bool start_receiving_msg = false;

void loop()
{
 while (Serial.available())
 {
  char c = Serial.read();

  if (c == '[')
  {
            start_receiving_msg = true;
            msg_from_esp8266 = "";
        } else if (start_receiving_msg && c != ']') {
            msg_from_esp8266 += c;
        } else if (start_receiving_msg && c == ']') {
            start_receiving_msg = false;
            if (msg_from_esp8266 == "toggle") {
                digitalWrite(LED_PIN, !digitalRead(LED_PIN));
                Serial.println("arduino toggle led");
            }
        }

 }
 delay(10);
}
```

Basically when you publish anything to topic /test/msg01 manually, it will try to toggle the esp8266's built in led. then esp8266 will publish a message to /test/esp8266 with the exact payload you publish to /test/msg01. Also, esp8266 will also send a serial message "[toggle]" to atmega. On the atmega side, it will check if it receives the "[toggle]" and toggle its built in LED, then it will send a message through serial. on the esp side, in the loop, it will receive that message from atmega and publish it to topic /test/arduino. This program is to test the communication between other mqtt client devices and the esp8266, as well as (communication between other mqtt client devices) and the atmega through esp8266 via serial.
The code in if (strcmp(topic, test_topic) == 0) is just some other additional test code.

Generally, you should expect the behaviour like this: once you publish any message to topic /test/msg01, you will see the same message being relayed to topic /test/esp8266. both esp8266 and atmega will toggle their LED on and off. And the message "arduino toggle led" will be published to topic /test/arduino.

However, neither LED toggles. And there is no message from /test/arduino. in topic /test/esp8266 I saw some garbage text instead of my original message.

I have already troubleshooted the connection, the board configuration and checked if the lED is broken. They are all good, and I am pretty sure that the problem is to do within the "callback" function.

Here are some screenshot with the mqtt message:

What I have published to /test/msg01:
[![enter image description here][1]][1]

What I get from /test/esp8266
[![enter image description here][2]][2]
[![enter image description here][3]][3]

And, there is no problem with the message in /test/msg01 as I was also subscribing to the topic and get the same message as I published.
[![enter image description here][4]][4]
[![enter image description here][5]][5]

I didn't receive any message from topic "/test/arduino", so seems like the Serial message didn't get to atmega.

And again no problem with XC4411 board configuration as I turn the button 1, 2 on after I done flashing the two chips, and the code compiled and was uploaded to both chip successfully.

Looks like the callback function just corrupted my message, and also just somehow skipped and ignored the line that sends the toggle message to arduino and the line that toggle esp8266's LED.

I am very new to these topic discussed in the question in general, so maybe there are some mechanism that I am not aware of. Thank you the answers in advance.

  [1]: https://i.stack.imgur.com/Hwk3x.png
  [2]: https://i.stack.imgur.com/sm1rn.png
  [3]: https://i.stack.imgur.com/I9CZG.png
  [4]: https://i.stack.imgur.com/eP3ok.png
  [5]: https://i.stack.imgur.com/lIjs4.png

body:
From the [PubSubClient][1] library documentation:

  [1]: https://pubsubclient.knolleary.net/api#callback

> Internally, the client uses the same buffer for both inbound and outbound messages. After the callback function returns, or if a call to either publish or subscribe is made from within the callback function, the topic and payload values passed to the function will be overwritten


message:
Atmega 328pu on breadboard. What to choose in order to upload code with ftdi converter

When I program atmega328 PU on breadboard,vwhat programmer do I have to use and what arduino board type I have to choose? I am trying this with ftdi converter I have already done the connections and it's okay but there's an error when I'm trying to upload the code either with instant upload either with the programmer. Everything can help is acceptable and thanks in advance for your support.

body:
There are quite a few questions here about breadboard computers. Try searching this site for "breadboard". I also have [a page about making a breadboard Arduino](http://gammon.com.au/breadboard) which might help.

Normally I would set the Arduino type to Uno if the breadboard computer has a 16 MHz oscillator or crystal on it. If you are running at 8 MHz (possibly with the internal oscillator) I would set it to Lilypad.

If the chip doesn't have a bootloader on it then you need to install that first. I have [a page about installing a bootloader](http://gammon.com.au/forum/?id=11635) which might help.

To install the bootloader you need to use an SPI interface as described on the above page. That requires running 6 wires from an existing (working) Arduino to your breadboard.

>  it's okay but there's an error when I'm trying to upload the code

It's OK? But there's an error? What error message?