text:
Real time programming with real time module
If you install a real time clock like DS3231 Real Time Clock Module RTC Sensor High Precision, can you program digital output (such as turning 12VDC valves on) based on day of week and time?
I mean like turning digital output 5 on Friday at 7am for 10 minutes, for example.

Yes you can.  You do have to take into account power fails and reboot procedures.

@RohitGupta Please do not answer in comments. Make an answer. Thank you.

Is this a battery powered project where the solution has to be low power ?

you can program the state of a digital output based on almost any event you can think of, providing that you have a way to detect the event


text:
Pin Change Interrupt Flag timing on 1284P
I want to ask about pin change interrupts on a 1284P chip using MightyCore.  I have a question about the timing of multiple interrupts on one port.  Specifically, if I am servicing a PCINT vector and another pin in the port changes while I am in the ISR, will it generate another interrupt immediately following the one I am servicing?
When I read the datasheet I see:

Bit 2 – PCIF2: Pin Change Interrupt Flag 2 When a logic change on any
PCINT[23:16] pin triggers an interrupt request, PCIF2 will be set. If
the I-bit in SREG and the PCIE2 bit in PCICR are set, the MCU will
jump to the corresponding Interrupt Vector. The flag is cleared when
the interrupt routine is executed. Alternatively, the flag can be
cleared by writing '1' to it.

When it says that the flag is cleared when the interrupt routine is executed, does that mean when it enters or exits the ISR?  If it is at the end, can I clear the flag in the first line of the ISR and allow another pin change to set it again even if it happens before I exit the ISR?

When it is entered. The wording is slightly vague but I think "when the interrupt routine is executed" means the commencement of execution. Otherwise multiple pin-change interrupts could be easily missed, depending on how long you took inside the ISR.
I suggest writing a simple test that saves somewhere what the flag is, upon entering the ISR, and check it is cleared already.

I wrote this test for the Uno (which is the same basic architecture):
volatile bool firstTime = true;
volatile byte PCIFR_copy = 0;

ISR (PCINT0_vect)
 {
 // handle pin change interrupt for D8 to D13 here

 if (!firstTime)
   return;

 firstTime = false;
 PCIFR_copy = PCIFR;
 }  // end of PCINT0_vect

void setup ()
  {
  pinMode (9, INPUT_PULLUP);
  Serial.begin (115200);

  // pin change interrupt (for D9)
  PCMSK0 |= bit (PCINT1);  // want pin 9
  PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13
  }  // end of setup

void loop ()
  {
  Serial.print ("First time is ");
  Serial.print ((int) firstTime);
  Serial.print (", Flag is ");
  Serial.println ((int) PCIFR_copy);
  delay (1000);
  }  // end of loop

The PCIFR flag was always zero, even after triggering the pin-change interrupt, which shows that it was cleared upon entering the ISR.

will it generate another interrupt immediately following the one I am servicing?

So, based on the above, the answer is yes it will. Upon leaving the ISR one more instruction will be executed and then the next interrupt will be serviced (assuming a higher-priority interrupt doesn't get in first).

Another way of looking at it is that the pin change will always set that flag. Between instructions the processor would check that flag (and the flags for the other interrupts) and for the highest priority interrupt, if that flag is set, then it would clear that flag and then commencing processing that interrupt. That is really the only logical way it could work.

Also, it makes more sense from the design of the processor to clear the flag upon entering the ISR. Apart from the problem that interrupts could be missed if it didn't, when it enters the ISR the processor "knows" which interrupt it is servicing, because it would have checked the PCIFx flag, it would have checked the PCIEx flag (to see if the interrupt should be executed) and it would have then changed the program counter to the appropriate address for that interrupt, after pushing the current program counter onto the stack. This would be the logical time to clear that flag while all this information is in the processor's "head" so to speak.
At the end of the ISR the code simply executes a RTI (Return from Interrupt) instruction which doesn't have associated with it which interrupt it is returning from. Thus it would be hard to clear the flag at that point.

Thanks for the quick and thorough (and tested) response.

source: Stack Exchange

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

sort: votes


text:
Blackpill stm32F411 doesn't enter boot mode anymore
I cannot enter boot mode with my BlackPill F411 board anymore. It's currently running one my sketch successfully uploaded few weeks ago but now, I don't know what's happen.
I've read this post which unfortunately doesn't help me.
Blue led doesn't blink, CubeProgrammer 2.14 doesn't detect any DFU mode and Arduino says
      -------------------------------------------------------------------
                   STM32CubeProgrammer v2.14.0
      -------------------------------------------------------------------

Error: Target device not found
Establishing connection with the device failed
Failed uploading: uploading error: exit status 1

I try to upload via USB here is my setting:

Get_PnpDevice says in PowerShell: "BLACKPILL_F401CC CDC in FS Mode".
Isn't it strange? So do you have any idea please?
I use STM32 MCU based boards 2.6.0, IDE 2.1.1. don't know if it occured after some release.

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


text:
Functions downgraded in the I2S library using an ESP32
I am following the instruction to setup a microphone with an esp32 with arduino cli.
Here is the tutorial

https://dronebotworkshop.com/esp32-i2s/#Resources
https://www.youtube.com/watch?v=m-MPBjScNRk&t=915s

As pointed out in the video (timestamp 14:30 to 15:05), it seems that some functions of the I2S library were downgraded. And, indeed, when I compile the code, I get the following error message:
/Users/me/Documents/cs/microcontrollers/ESP32/microphone/microphone.ino: In function 'void i2s_install()':
/Users/me/Documents/cs/microcontrollers/ESP32/microphone/microphone.ino:33:47: error: 'I2S_COMM_FORMAT_STAND_I2S' was not declared in this scope
     .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),
                                               ^
Used platform Version Path
esp32:esp32   1.0.6   /Users/me/Library/Arduino15/packages/esp32/hardware/esp32/1.0.6

Error during build: exit status 1

Here is the code:
/*
  ESP32 I2S Microphone Sample
  esp32-i2s-mic-sample.ino
  Sample sound from I2S microphone, display on Serial Plotter
  Requires INMP441 I2S microphone

  DroneBot Workshop 2022
  https://dronebotworkshop.com
*/

// Include I2S driver
#include <driver/i2s.h>

// Connections to INMP441 I2S microphone
#define I2S_WS 25
#define I2S_SD 33
#define I2S_SCK 32

// Use I2S Processor 0
#define I2S_PORT I2S_NUM_0

// Define input buffer length
#define bufferLen 64
int16_t sBuffer[bufferLen];

void i2s_install() {
  // Set up I2S Processor configuration
  const i2s_config_t i2s_config = {
    .mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = 44100,
    .bits_per_sample = i2s_bits_per_sample_t(16),
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),
    .intr_alloc_flags = 0,
    .dma_buf_count = 8,
    .dma_buf_len = bufferLen,
    .use_apll = false
  };

  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
}

void i2s_setpin() {
  // Set I2S pin configuration
  const i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = -1,
    .data_in_num = I2S_SD
  };

  i2s_set_pin(I2S_PORT, &pin_config);
}

void setup() {

  // Set up Serial Monitor
  Serial.begin(115200);
  Serial.println(" ");

  delay(1000);

  // Set up I2S
  i2s_install();
  i2s_setpin();
  i2s_start(I2S_PORT);

  delay(500);
}

void loop() {

  // False print statements to "lock range" on serial plotter display
  // Change rangelimit value to adjust "sensitivity"
  int rangelimit = 3000;
  Serial.print(rangelimit * -1);
  Serial.print(" ");
  Serial.print(rangelimit);
  Serial.print(" ");

  // Get I2S data and place in data buffer
  size_t bytesIn = 0;
  esp_err_t result = i2s_read(I2S_PORT, &sBuffer, bufferLen, &bytesIn, portMAX_DELAY);

  if (result == ESP_OK)
  {
    // Read I2S data buffer
    int16_t samples_read = bytesIn / 8;
    if (samples_read > 0) {
      float mean = 0;
      for (int16_t i = 0; i < samples_read; ++i) {
        mean += (sBuffer[i]);
      }

      // Average the data reading
      mean /= samples_read;

      // Print to serial plotter
      Serial.println(mean);
    }
  }
}

I also tried to install the I2S library with:
arduino-cli lib install I2S

but got the following error message:
Error installing I2S: Library 'I2S' not found

How can I solve the problem?
EDIT 1
After the comments I tried to Upgrade the ESP32 package. For this I went to Tools -> Boards -> Board Manager, typed ESP32 and got the following window:

It seems to me that I cannot upgrade beyond version 1.0.6 (under Arduino IDE 1.8.19)
What am I doing wrong?
EDIT 2
Ok I followed the installation instruction on the espressif website and it worked
https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html

It is not that the library has been downgraded, the message shows that you had very old version of ESP32-Arduino package installed (1.0.6), the current version is 2.0.8.. Goto Tools -> Boards -> Board Manager to upgrade your ESP32 package. You don't need to manually install driver/i2s.h as it is part of the esp-idf as the foundation of Arduino ESP32 Core.

Many thanks for your comment @hcheung. I tried to Upgrade the ESP32 package. For this I went to Tools -> Boards -> Board Manager, typed ESP32 and got the window displayed in the edited question at the end. It seems to me that I cannot upgrade beyond version 1.0.6 (under Arduino IDE 1.8.19). What am I doing wrong?

Ok I followed the installation instruction on the espressif website and it worked https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html


text:
How to flash plcc 32 chip with arduino
The specific model is the W39V080FA and I'm quite a noob when it comes to flashing.
I've already prepared the circuit to divide the voltage and use a proper 3.3V.
I have an plcc to dip adapter, but I really don't know how to wire each pin, really need some tips. Thanks.

you have to determine which signals are required to write data to the chip ... then you have to write a program that generates those signals ... determining the required signals is in no way related to the Arduino ... your question would be related to the arduino only when you know which signals to generate, but have problems generating those signals with the arduino

it sounds like a lot of work, but thankfully there's a great project called Flashrom that get rid of those assignments, and their official docs point that this chip is supported. My barrier is building the circuit (assigning the pins to Arduino). Also, thanks for your response

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". Then come back and [edit] your question, adding the link to the mentioned project. Also add what specifically stops you from assigning pins. You don't want us to guess, do you?


text:
PlatformIO and const PROGMEM
I'm using the DuinoWitchery LCD library (https://github.com/duinoWitchery/hd44780) in a PlatformIO Arduino project with CLion.
The following code works if I stick it in main.cpp:
// near top of class...
const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
};

hd44780_I2Cexp lcd(0x27);

// ... snip ...

void setup() {
    for (int x=0; x<8; x++)
       lcd.createChar((uint8_t)x, decimalDigit[x]);
    // ...snip...
}

... but if I move the code into another class, like:
Renderer.h
class Renderer : BaseRenderer {
public:
    virtual void renderTo(hd44780* lcd) override;
    // ... snip ...
private:
const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
    };
}

Renderer.cpp
void Renderer::renderTo(hd44780lcd* lcd) {
    for (int x=0; x<8; x++)
       lcd->createChar((uint8_t)x, decimalDigit[x]);
    // ...snip...
}

... the custom characters end up with garbage data.
I think I might be breaking some esoteric rule that governs where you're allowed to put a const PROGMEM uint8_t[], and causing the array declared in Renderer.h to end up in SRAM. But I'm not sure how to confirm it OR fix it.

note: the for/next loop to create the chars is just for the sake of illustration & to demonstrate that something that works in main.setup() fails in Renderer.renderTo(). In real life, the sequence of characters getting rendered to the LCD owns one of the 8 custom characters & redefines it as necessary to be the decimal point and tenths value.

Does it help if you make the data member static const?

I'm pretty sure the first works only because it's in the RAM anyway because createChar doesn't support PROGMEM.

I think the DuinoWitchery LCD library specifically does. I literally copied the code that worked in main.setup() from the library's example code .

Confirmation: hd44780::createChar(uint8_t location, const uint8_t* charmap) ABSOLUTELY treats charmap as a pointer to PROGMEM. I took advantage of CLion's ability to find the source for a method, and edited it to stick a bunch of Serial.print() statements in createChar to see what's happening. The values it's fetching via pgm_read_byte() are definitely NOT the values in my array. So, it looks like my theory that decimalDigit[10][8] is ending up in SRAM is probably correct. I still have no idea why, or how to fix it, though :-(

I also just verified that the decimalDigit[][] array in Renderer.h is DEFINITELY ending up in SRAM (by temporarily hacking createChar() to forcibly treat it like a pointer to SRAM instead of a pointer to flash). So... NOW, the big question is, what do I have to do to get Renderer.h's array to end up in PROGMEM instead of SRAM?

Take the table out of the class.  Keep it in progmem.  Give the class a reference or a pointer to it.

Ok, I haven't noticed link to the library and found wrong one. You've defined it as const member of the class, so in theory you can change it in the constructors initializer list which means it's "runtime code" and therefore ends in the RAM

The PROGMEM qualifier can only be applied to statically-allocated
constant data. When you move the decimalDigit array inside the class,
it becomes a data member, i.e. you have one copy of the array per
instance... in RAM. In this case, PROGMEM does not work. My compiler
says:
warning: ‘__progmem__’ attribute ignored [-Wattributes]

If you want to keep the array inside the class, it must be given the
static qualifier. It then becomes statically-allocated class data (not
instance data):
// Renderer.h:
class Renderer : BaseRenderer {
public:
    virtual void renderTo(hd44780* lcd) override;
    // ... snip ...
private:
    static const PROGMEM uint8_t decimalDigit[10][8];
};

// Renderer.cpp:
const PROGMEM uint8_t Renderer::decimalDigit[10][8] = {
    {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
    {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
    // ... snip ...
};

Of course, putting the array within the class is not an obligation. If
it is going to be private anyway, the outside world (the files that
include Renderer.h) does not need to know about its existence.

OK, I ended up blindly stumbling over the solution, even though at this moment I have no idea why it actually works.
I moved the const PROGMEM uint8_t decimalDigit[10][8] = {...} declaration from Renderer.h to the almost-top of Renderer.cpp, so it sits between #include "Renderer.h" and constructor:
#include "Renderer.h"

const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
};

Renderer::Renderer(int col, int row, int customCharNumber) : BaseRenderer(col, row) {
    assignCustomChar(customCharNumber);
}

For now, I just have to chalk it up as 'black magic', because some subsequent experiments have forced me to question and doubt everything I ever thought I understood about how #include directives work.

That's not black magic.  You just took it out of the class definition.  If the class needs it as a member, then pass in a pointer or reference.  As it is written now, the decimalDigit array is no longer a part of the class.  It is existing at global scope.

It's nothing to do with black magic or #includes. An array of constants is, by definition, not going to change. Therefore there is no point in including it inside a class, unless marked as static, for scoping purposes.


text:
MD5 of File doesnot match data in flash Error with ESP32 S3
I am getting the fatal error MD5 of file not match data in flash. Below is the output of upload.
[1/5] cmd.exe /C "cd /D D:\Users\INOMETRICS\espressif\workspace\blink\build\esp-idf\esptool_py && python D:/Espressif/frameworks/esp-idf-v4.4/components/partition_table/check_sizes.py --offset 0x8000 partition --type app D:/Users/INOMETRICS/espressif/workspace/blink/build/partition_table/partition-table.bin D:/Users/INOMETRICS/espressif/workspace/blink/build/blink.bin"
blink.bin binary size 0x31340 bytes. Smallest app partition is 0x100000 bytes. 0xcecc0 bytes (81%) free.
[2/5] Performing build step for 'bootloader'
[1/1] cmd.exe /C "cd /D D:\Users\INOMETRICS\espressif\workspace\blink\build\bootloader\esp-idf\esptool_py && python D:/Espressif/frameworks/esp-idf-v4.4/components/partition_table/check_sizes.py --offset 0x8000 bootloader 0x0 D:/Users/INOMETRICS/espressif/workspace/blink/build/bootloader/bootloader.bin"
Bootloader binary size 0x5180 bytes. 0x2e80 bytes (36%) free.
[2/3] cmd.exe /C "cd /D D:\Espressif\frameworks\esp-idf-v4.4\components\esptool_py && D:\Espressif\tools\cmake\3.20.3\bin\cmake.exe -D IDF_PATH="D:/Espressif/frameworks/esp-idf-v4.4" -D SERIAL_TOOL="python D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/esptool/esptool.py --chip esp32s3" -D SERIAL_TOOL_ARGS="--before=default_reset --after=hard_reset write_flash @flash_args" -D WORKING_DIRECTORY="D:/Users/INOMETRICS/espressif/workspace/blink/build" -P D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/run_serial_tool.cmake"
esptool.py esp32s3 -p COM8 -b 460800 --before=default_reset --after=hard_reset write_flash --flash_mode dio --flash_freq 80m --flash_size 2MB 0x0 bootloader/bootloader.bin 0x10000 blink.bin 0x8000 partition_table/partition-table.bin
esptool.py v3.2-dev
Serial port COM8
Connecting...
Chip is ESP32-S3
Features: WiFi, BLE
Crystal is 40MHz
MAC: 70:04:1d:be:ab:74
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Flash will be erased from 0x00000000 to 0x00005fff...
Flash will be erased from 0x00010000 to 0x00041fff...
Flash will be erased from 0x00008000 to 0x00008fff...
Compressed 20864 bytes to 13002...
Writing at 0x00000000... (100 %)
Wrote 20864 bytes (13002 compressed) at 0x00000000 in 0.1 seconds (effective 1284.4 kbit/s)...
File  md5: 1d4bc050825217f8434a2cfd167894cd
Flash md5: 1b32e380d00eb036ce18a632dedbe04d
MD5 of 0xFF is b145c0e952abec491d69c8c5f8ac47c4

A fatal error occurred: MD5 of file does not match data in flash!
CMake Error at run_serial_tool.cmake:56 (message):
  python
  D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/esptool/esptool.py
  --chip esp32s3 failed

I am getting the same error while uploading with esp-idf and Arduino ide or platformio.
How could i solve the issue.
Regards

Yes, I have managed to get it working now, the issue encountered was with the strapping pins. Specifically, Pin 45 of ESP32S3 is responsible for configuring VDD_SPI_FLASH. To ensure it operates at 3.3V, the pin should be connected to the ground. Otherwise, it will function at 1.8V, which might cause problems with the Flash functionality.
Fortunately, this can also be resolved by burning some EFUSES using the espefuse.py tool, which comes along with esptool.py. All you need to do is run the command: espefuse.py set_flash_voltage <voltage> (where voltage can be either 3.3V or 1.8V or OFF). For more details, you can visit: link to the official documentation.


text:
ERROR: return reinterpret_cast<T>(pgm_read_ptr(p));
I need to update DHT sensor data to the webserver in JSON format using ESP8266. This is my code.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#include <ArduinoJson.h>

const char* ssid = "YOUR_SSID";
const char* password = "YOUR PASSWORD";
const int dhtPin = D4;
DHT dht(dhtPin, DHT11);
ESP8266WebServer server(80);

void handleRoot() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  if (isnan(temperature) || isnan(humidity)) {
     server.send(500, "text/plain", "Failed to read from DHT sensor");
    return;
  }

  StaticJsonDocument<200> jsonDoc;
  jsonDoc["temperature"] = temperature;
  jsonDoc["humidity"] = humidity;

  String jsonString;
  serializeJson(jsonDoc, jsonString);

  server.send(200, "application/json", jsonString);
}

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

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");
  dht.begin();
  server.on("/", handleRoot);
  server.begin();
  Serial.println("Server started");
}

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

But I got error like,
In file included from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/static_array.hpp:11:0,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Numbers/FloatTraits.hpp:14,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Numbers/FloatParts.hpp:8,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/TextFormatter.hpp:11,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/JsonSerializer.hpp:7,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/ConverterImpl.hpp:7,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:37,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,
                 from C:\Users\Kuralmozhi.R\Downloads\ID_2\ID_2.ino:5:
c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/pgmspace_generic.hpp: In instantiation of 'typename ArduinoJson6193_F1::enable_if<ArduinoJson6193_F1::is_pointer<T>::value, T>::type ArduinoJson6193_F1::pgm_read(const void*) [with T = const __FlashStringHelper*; typename ArduinoJson6193_F1::enable_if<ArduinoJson6193_F1::is_pointer<T>::value, T>::type = const __FlashStringHelper*]':
c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Deserialization/DeserializationError.hpp:85:12:   required from here
c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/pgmspace_generic.hpp:15:45: error: 'const void*' is not a pointer-to-object type
   return reinterpret_cast<T>(pgm_read_ptr(p));
                                             ^

exit status 1

Compilation error: exit status 1

I don't know how to solve this error. Please suggest me some ideas!

I tried to update ESP8266. But now it shows like this,
Variables and constants in RAM (global, static), used 28984 / 80192 bytes (36%)
║   SEGMENT  BYTES    DESCRIPTION
╠══ DATA     1504     initialized variables
╠══ RODATA   1376     constants
╚══ BSS      26104    zeroed variables
Instruction RAM (IRAM_ATTR, ICACHE_RAM_ATTR), used 60439 / 65536 bytes (92%)
║   SEGMENT  BYTES    DESCRIPTION
╠══ ICACHE   32768    reserved space for flash instruction cache
╚══ IRAM     27671    code in IRAM
Code in flash (default, ICACHE_FLASH_ATTR), used 273120 / 1048576 bytes (26%)
║   SEGMENT  BYTES    DESCRIPTION
╚══ IROM     273120   code in flash

Please copy and paste the actual error, including the line number, not something "like" the error. Edit your question to do this.

Sounds like this problem.

I can't understand this problem. Can you explain briefly?

What version of the Arduino IDE are you using?

The page linked by Fahad suggested: I suggest you upgrade or reinstall the ESP8266 core for Arduino. If that's still not working, you can disable support for PROGMEM until we figure what's wrong (see ARDUINOJSON_ENABLE_PROGMEM).

What is your issue with the output after the update? In my eyes this looks like a successful build.

With the info from the link Fahad provided in the comments, I can only offer a guess: Your ESP8266 board definitions are outdated and the old version of the ESP8266 board definitions contains a bug.
There is an outdated URL to the ESP8266 board definition JSON floating around on the web. I guess you found that one. The URL still works, but is not updated anymore. Please check the version of your ESP8266 board definitions: Open the Board Manager (Tools -> Board -> Board Manager), search for ESP8266 and verify that the version is at least 3.1.2 (current version as of this writing; I don't know the lowest version where this bug is fixed).
If the Board Manager does not offer to update to version 3.1.2 (or later), you may need to provide the current URL to the board definitions in File -> Preferences -> Tab "Settings" -> Additional Boards Manager URLs. Remove the old ESP8266 URL, but don't remove URLs for other boards. Then try to update using the Board Manager again:
https://arduino.esp8266.com/stable/package_esp8266com_index.json

This works! Thank you so much orithena!!


text:
Encoder giving value between steps
I'm trying to interface an encoder and a 1602 i2c display. My encoder seems to be giving an output between steps.
I have tried to make my code as simple as possible and am outputting whether the encoder rotated clockwise or counter clockwise to serial. When I rotate the knob one physical step clockwise, '++' (separated by a new line) outputs to the serial monitor when I am expecting just '+'.  The same occurs when rotating counter clockwise, except with '--' instead of '++'.
Parts:

ESP32 Dev Board
Rotary Encoder

Code:
#define enc1 32
#define enc2 33
#define button 25
#define led 2;

int oldPos1;
int newPos1;
int newPos2;

void setup() {
  pinMode(enc1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(enc1),encRead,CHANGE);
  pinMode(enc2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(enc2),encRead,CHANGE);
  Serial.begin(115200);

  oldPos1 = digitalRead(enc1);
}

void encRead(){
  newPos1 = digitalRead(enc1);
  newPos2 = digitalRead(enc2);
  if(oldPos1 != newPos1){
    if (newPos1 == newPos2){
      Serial.println("+");
    }
    else{
      Serial.println("-");
    }
  }
  oldPos1 = newPos1;
}

void loop() {
  delay(10);
}

remove the enc2 attachInterrupt

This is the kind of thing that can happen when you buy cheap parts that
come with no documentation whatsoever: you don't know how they are
supposed to work! Many rotary encoders have two detents per pulse: if
you rotate them by a single detent, you get a single transition on each
pin. If using such an encoder, you would indeed expect a single + or
- printed per detent. But what about the encoder you bought? You can't
tell, since there is no documentation!
Quite fortunately, a helpful individual left a useful review on the
product page you linked to. It can serve as an ersatz of datasheet:

Each movement of the spindle from one detent to the next results in
the encoder1 and encoder2 pins going through multiple transitions, not
a single one (as you might expect).
Assuming that you have tied the encoder pins to (say) 5V with a
resistor, a rotation between detents, will produce a set of encoder
transitions. For example: 11 10 00 01 11 (clockwise) or 11 01 00 10 11
(anti-clockwise).

This explains the behavior you are experiencing.
Side note: as jsotola writes in a comment, you should
remove the enc2 attachInterrupt(). As your interrupt handler
explicitly ignores transitions in enc2 (it does nothing unless enc1
changed), there is no point in interrupting the processor for those
ignored transitions.

Unfortunately you did not provide a link to the data sheet of the encoder.
One physical step at the knob can generate changes on both pins. And since you have assigned the interrupt service routine to both pins, it is called two times for each physical step.
Another possible reason is "bouncing" of the mechanical contacts in this encoder. That means, that multiple pulses are generated on the change between open and closed. Therefore, change or edge interrupts are only a correct solution, if you take bouncing into account.
To investigate the issue, you can insert port pin toggles to your interrupt service routine. For example, set a pin on entry and reset it on exit. Then connect an oscilloscope or logic analyzer and compare the input signals and this output.
Oh, and it is never a good idea to put serial output in an interrupt service routine. Depending on the amount of sent data and the chosen baudrate, this output will block the routine for several milliseconds. During this time, the same interrupt is not serviced, and can be skipped in case of multiple triggers.


text:
DS18B20 oneWire analog vs digital
I just discovered that the Dallas DS18B20 can be read from either digital or analog pins. I never thought analog was an option until I stumbled across an article searching for another issue.
So now I'm wondering, if I have a dozen DS18B20's on about 20 feet of wire with a 4.7k resistor, what would be the better option for reading? Digital or Analog?

the Analog on an Arduino Uno means those pins are analog-capable (not all the GPIO pins are analog-capable), meaning that they can be configured to be an analog input instead of just as digital input/output. 2)DS18B20 is a digital sensor communicating using 1-wire protocol, it is a bus, meaning multiple DB18B20 can share the same bus.

To use multiple DS18B20 devices on the same bus
1/ First get the address of each DS18B20 device by attaching it alone to the Arduino, and calling the discoverOneWireDevices(); function. Write down the address. This is a set of 8 hexadecimal digits, eg 0x28, 0x13, 0x97, 0x9A, 0x0A, 0x00, 0x00, 0x6A
2/ Hard-code the address of each device, e.g. #define TEMP_SENSOR1 {0x28, 0x13, 0x97, 0x9A, 0x0A, 0x00, 0x00, 0x6A} before the call to the setup, and define the corresponding device address: DeviceAddress tempSensor1 = TEMP_SENSOR1;
3/ each time you launch a command to a DS18B20, specify to which you are speaking, eg temperature1 = sensors.getTempC(tempSensor1);

Analog is not an option as the 1-wire is a digital communication bus, however using an analog pin is on many processors to do this is possible. This is achieved on many of the processors because the analog pin can be configured and used for digital I/O.  Arduinos such as the UNO can accomplish this because of the processor they use. Note not all microprocessors are designed use an analog pin for digital I/O.
There is an application note by AMD called "1-Wire Search Algorithm", https://www.analog.com/en/app-notes/1wire-search-algorithm.html. By using this process you can read all of the sensors independently without knowledge of there addresses. Using this method will not guarantee which sensor you are reading but the sequence will repeat and you can simply replace a sensor but the order will probably change. This allows you to change sensors etc when there are not many sensors involved. Here are some links to better explain this.
https://docs.arduino.cc/learn/communication/one-wire
https://www.arduino.cc/reference/en/libraries/onewire/


text:
Whether my board analog pins shorted? I see same input on all
I am puzzled. I just connected 3.3 V input to the Analog pin A5 of the Arduino UNO. On the script, I am reading all the input pins. Surprizingly, all the pins are giving voltage as that of A5 pin. This made me think whether all of them shorted?
code:
int a0_analogPin = A0;
float a0_val = 0;
int a1_analogPin = A1;
float a1_val = 0;
int a2_analogPin = A2;
float a2_val = 0;
int a3_analogPin = A3;
float a3_val = 0;
int a4_analogPin = A4;
float a4_val = 0;
int a5_analogPin = A5;
float a5_val = 0;

void setup() {
  Serial.begin(9600);           //  setup serial
  pinMode(a0_analogPin,INPUT);
  pinMode(a1_analogPin,INPUT);
  pinMode(a2_analogPin,INPUT);
  pinMode(a3_analogPin,INPUT);
  pinMode(a4_analogPin,INPUT);
  pinMode(a5_analogPin,INPUT);
  Serial.println("A0_val,A1_val,A2_val,A3_val,A4_val,A5_val");
}

void loop() {
  a0_val = analogRead(a0_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a0_val);          // debug value
  Serial.print(",");
  a1_val = analogRead(a1_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a1_val);
  Serial.print(",");
  a2_val = analogRead(a2_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a2_val);
  Serial.print(",");
  a3_val = analogRead(a3_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a3_val);
  Serial.print(",");
  a4_val = analogRead(a4_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a4_val);
  Serial.print(",");
  a5_val = analogRead(a5_analogPin)*5.0/1023.0;  // read the input pin
  Serial.println(a5_val);
}

Board:

Serial Monitor:

you set all analog pins as digital inputs

@jsotola, analogRead configures the pin for ADC. Mainland, unconnected pins act like an antenna

@Juraj The problem is solved after I connected remaining to the ground. Thanks

Most of your analog pins are not connected to anything. In electrical engineering, that's called "floating". It means they have no reference to anything and thus their value can be anything.
Basically their value is determined by static electricity. Moving your hands near the pins or moving them away may be enough to change the value you read.
It could be that your "oscilloscope view" actually shows that nicely. One pin gets the voltage immediately (value 6) and through static electricity, the other pins slowly take that value as well (value 1, value 2, ...). Probably the steepest curve of those is closest to the pin that is high and the most shallow curve is furthest away. Your observations may vary depending on humidity and temperature, since that makes static electricity spread faster or slower.
Solution: don't let your pins float. Connect them to a defined value, e.g. ground if you want them to have a predictable value.

You are seeing crosstalk between the analog input channels. In the
datasheet of the microcontroller you can see the analog
input circuitry. See the capacitor labeled “CS/H”? This is
the “sample and hold” capacitor. Its job is to hold the voltage being
read while the ADC performs the conversion. When you measure channel A5,
you are charging this capacitor to 3.3 V. Then, when you switch to
a floating input, the capacitor has no path to discharge, and you end
up measuring the same voltage.
Actually, you do not measure exactly the same voltage. The reason is
that each input pin has a parasitic capacitance. When you switch from A5
to A0, the charge in CS/H splits between this capacitor and
the stray capacitance of the pin A0. Then, you switch to A1 and the
remaining charge is split between CS/H and the stray
capacitance of A1, and so on. Eventually, when you come back to A5, you
charge again CS/H to the full 3.3 V and the cycle starts
again. The net effect is that you are progressively moving charges
between the successive pins. This is why the curves look like
exponential relaxations, where each successive pin charges more slowly
than the preceding one.
The solution, as already written in other answers, is to avoid leaving
the pin floating. The datasheet recommends making sure the connected
source has an impedance no larger than 10 kΩ.


text:
Startg the Arduino2 with the boards parameters
when the Arduino_2 starts the board is not selected.
Is it possible to run a program with such parameters (for example)?: "C:\Program Files\Arduino IDE\Arduino IDE.exe" --board arduino:avr:uno --С:\Users\scetch.ino

It's not something the Arduino IDE 2.x currently supports. However, the IDE should remember the selected board between IDE stop/start once selected. File > New Sketch should inherit the board selection from the currently opened sketch window. Please elaborate on why you find this feature helpful besides saving two clicks after the sketch opens. It can be implemented if there is a good reason.


text:
How to Connect Two CQRobot Ocean Non-Contact Water/Liquid Level Sensors (CQRSENYW001) to Arduino UNO REV3 (A000066)?
I am a complete beginner trying my hand at a home automation project.
Part of my setup includes using an Arduino UNO REV3 (A000066), and connecting two CQRobot Ocean Non-Contact Water/Liquid Level Sensors (CQRSENYW001).
There is great documentation for the sensor:
http://www.cqrobot.wiki/index.php/Non-Contact_Water/Liquid_Level_Sensor_SKU:_CQRSENYW001
And setting up one sensor is a breeze (see setup in image below):

Red Wire to 5V
Black Wire to GND
Green Wire (Output) to 7

Since there is only one 5V on the Arduino (and since the project could expand), it sounds like I need to use a breadboard to allow for expansion.
I used the following video to connect the Arduino to the breadboard for power:
https://www.youtube.com/watch?v=Ia7gkgSor78
Now to connect the two sensors, do I just need to put the Black and Red Dupont Wires from the sensors anywhere in the - and + columns on the breadboard and connect the green wires back to the Arduino for the output in 6 and 7?
In other words, does the setup look correct below?

I have noticed that doing this seems to work for the most part (there is power) for the sensor, but I just want to make sure I am doing this right. Thanks!

if it works correctly, then you are doing it right

See my answer to your post in the arduino forum.

My answer to this question is there. I am curious why are you using the same question on two forums.


text:
Programming barebones ATMega328 with external programmer and no bootloader
I have created a circuit with a barebones ATMega328.
I also have an external programmer (Sparkfun's Pocket AVR Programmer)...
Now I want to program a particular sketch... When uploading a sketch, do i also have to flash the bootloader beforehand?
Or is it possible to upload the sketch directly to the microcontroller without a bootloader?

The Pocket AVR Programmer is just a standard ISP programmer, meaning it uses the ISP protocol built into the hardware of the microcontroller to write data to flash and EEPROM. That is also the way, that the bootloader got onto the microcontroller in the first place.
The bootloader of the Arduino on the other hand is a small program to communicate over Serial (or USB depending on the Arduino board) and then write the data to flash and EEPROM.
So: No, you don't need the bootloader, if you want to use the ISP programmer. Select your programmer in the corresponding menu of the Arduino IDE to use it.
Though keep in mind, that you won't be able to upload a new sketch via Serial/USB without the bootloader. You can always use the ISP programmer to again write the bootloader to the microcontroller.


text:
ESP32 trouble with running ledcWrite inside of ISR
ESP32-S2 (Wemos/Lolin S2 mini)
Arduino 2.1.1 on Windows 11
Hello,
Thank you for taking the time to read this post and for any assistance you can provide. I consider myself a newbie when it comes to the more advanced aspects of Arduino, such as hardware functions and 32-bit MCUs. I've spent the last three days working on this code segment from a much larger project, and have searched extensively online to accomplish a seemingly simple task. I hope I'm not wasting anyone's time by asking a question that may have been answered elsewhere in an LMGTFY.
My goal is to output two LED PWM channels using hardware timers to control the frequency and duty cycle of the strobing LEDs. Here are the specific requirements:

The LEDs need to be power-controlled (I've been using the ledc() function)
The LEDs should be able to be strobed at specific intervals within the range of 0 to 1kHz. I'm using hardware timers so blocking functions such as non-DMA SPI updates of the display does not interfere with the strobe.
The duty cycle of the strobe needs to be adjustable as a float percentage ranging from 0.01 to 99.99% uptime per cycle.

Unfortunately, I've encountered an issue where I can either (unreliably) time the strobe and duty cycle or (somewhat more reliably) control the PWM power modulation, but not both simultaneously. I've tried various combinations of timer bindings, ledc channels, timing libraries, ISR handling, and rewriting the code from scratch multiple times.
I apologize for the messy state of the code, as it has undergone numerous modifications, and I'm fried at looking at the code. I would greatly appreciate any assistance or pointers you can provide to help resolve this issue.
Thank you once again for your help!
#include <esp32-hal-timer.h>

// Pin assignments
#define LED_660    17
#define LED_850    16

// Intensity control variables (percentage)
int pwr_850 = 0;
int pwr_660 = 0;

// Strobe control variables
float led_hz = 1.0;   // Strobe cycles per second
float led_duty = 50.0;    // Duty cycle percentage

// Timing variables
volatile unsigned long on_time;
volatile unsigned long off_time;

hw_timer_t *timer_on = NULL;
hw_timer_t *timer_off = NULL;

bool leds_on = false;  // Flag to track the state of LEDs

void IRAM_ATTR onTimer() {
  ledcWrite(2, 254);
  ledcWrite(3, 254);
  timerAlarmDisable(timer_off);
  timerAlarmWrite(timer_on, on_time, true);
  timerAlarmEnable(timer_on);
}

void IRAM_ATTR offTimer() {
  ledcWrite(2, 0);
  ledcWrite(3, 0);
  timerAlarmDisable(timer_on);
  timerAlarmWrite(timer_off, off_time, true);
  timerAlarmEnable(timer_off);
}

void startLEDs() {
  ledcSetup(2, 4000, 8);  // 4 kHz PWM, 8-bit resolution
  ledcSetup(3, 4000, 8);  // 4 kHz PWM, 8-bit resolution
  ledcAttachPin(LED_660, 2);
  ledcAttachPin(LED_850, 3);
  if (led_hz == 0) {
    ledcWrite(2, (pwr_660 / 100.0) * 255);
    ledcWrite(3, (pwr_850 / 100.0) * 255);
    leds_on = true;
  }
  else if (!leds_on && led_hz > 0.0) {
    // Calculate on/off times based on strobe parameters
    unsigned long cycle_time = 1000000.0 / led_hz;  // Convert Hz to microseconds
    off_time = ((cycle_time * led_duty) / 100);
    on_time = (cycle_time - off_time);

    // Update timer alarms
    timerAlarmWrite(timer_on, on_time, true);
    timerAlarmWrite(timer_off, off_time, true);

    // Enable timers
    timerAlarmEnable(timer_on);
    timerAlarmEnable(timer_off);  // Enable this at the same time as timerOn
    leds_on = true;
  }
}

void stopLEDs() {
  if (leds_on) {
    ledcWrite(1, 0);
    ledcWrite(0, 0);
    timerAlarmDisable(timer_on);
    timerAlarmDisable(timer_off);
    leds_on = false;
  }
}

void setup() {
  pinMode(LED_660, OUTPUT);
  pinMode(LED_850, OUTPUT);
  pinMode(15, OUTPUT);

  // Create timers
  timer_on = timerBegin(0, 80, true);  // Timer 0, prescaler 80 (1MHz)
  timer_off = timerBegin(1, 80, true);  // Timer 1, prescaler 80 (1MHz)

  // Attach interrupts
  timerAttachInterrupt(timer_on, &onTimer, true);
  timerAttachInterrupt(timer_off, &offTimer, true);
}

void loop() {
  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 1);
  led_hz = 1;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();

  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 0);
  led_hz = 2;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();

  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 1);
  led_hz = 5;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();

  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 0);
  led_hz = 10;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();
}


text:
NodeMcu V3 & BMe280 -> Temperature, Humidity, Pressure: value nan
I've just started playing around with a NodeMcu V3 and a BME280 sensor.

wiring
VCC -> 3.3V
GND -> GND
SCL -> D1 (GPIO5)
SDA -> D2 (GPIO4)

I've tried this sketch /  I2C scanner: it finds the BME280 at 0x76
#include <Wire.h>

// Set I2C bus to use: Wire, Wire1, etc.
#define WIRE Wire

void setup() {
  WIRE.begin();

  Serial.begin(9600);
  while (!Serial)
     delay(10);
  Serial.println("\nI2C Scanner");
}

void loop() {
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    WIRE.beginTransmission(address);
    error = WIRE.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

Then I've tried library BMx280I2C into this sketch:
#include <Wire.h>
#include <BMx280I2C.h>

BMx280I2C bmx280(0x76);

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

  // Setup BMx280
  Wire.begin();
  bmx280.begin();
  bmx280.resetToDefaults();
  bmx280.writeOversamplingPressure(BMx280I2C::OSRS_P_x16);
  bmx280.writeOversamplingTemperature(BMx280I2C::OSRS_T_x16);
  bmx280.writeOversamplingHumidity(BMx280I2C::OSRS_H_x16);

}

void loop() {

  // T,P,H measurements
  bmx280.measure();

  do{
    delay(100);
    Serial.println("No value, yet!");
  } while (!bmx280.hasValue());

  Serial.print("Pressure ");
  Serial.println(bmx280.getPressure());

  Serial.print("Temperature ");
  Serial.println(bmx280.getTemperature());

  Serial.print("Humidity ");
  Serial.println(bmx280.getHumidity());

  delay(1000);

}

the output is always and only:

-> No value, yet!
-> Pressure nan
-> Temperature nan
-> Humidity nan

Why? How can I understand the origin of the problem?Thanks!

Did you run the BMx280_I2C example sketch? Did it function correctly>

For ESP8266, you need to call Wire.begin(D2, D1); or Wire.begin(4, 5); instead of just Wire.begin().

@hcheung set  Wire.begin(D2,D1); but same behaviour

The begin() method on BMx280I2C  returns an indication of whether it succeeds or not. You should check it. Also CSB should be connected to VCC to force the I2C interface.

@StarCat same result
21:31:30.943 -> Pressure: nan
21:31:30.943 -> Pressure (64 bit): nan
21:31:30.977 -> Temperature: nan
21:31:30.977 -> Humidity: nan

With this libary https://github.com/Erriez/ErriezBMX280 (example in the same page) I obtain values! But are always the same... For example always Temperature: -142.46

Do you check for errors when you use that library? The code you posted doesn't.

Solved with Adafruit library
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme;

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

  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
}

void loop() {
  Serial.print("Temperature = ");
  Serial.print(bme.readTemperature());
  Serial.println(" *C");

  Serial.print("Humidity = ");
  Serial.print(bme.readHumidity());
  Serial.println(" %");

  Serial.print("Pressure = ");
  Serial.print(bme.readPressure() / 100.0F);
  Serial.println(" hPa");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.println();

  delay(2000);
}


text:
How EEMEM maps the variables? (avr/eeprom.h)
I can store and restore my data with avr/eeprom.h if I don't change the sketch.

I have a sketch that stores the data. After power cycle of the device the data are fine.
If I change the sketch with Serial.print statements (I want to re-read the data on-screen) the sketch seeks the data in wrong addresses of EEPROM, although I can verify with another sketch that the data are fine.

More detailed: I store around 50 bytes, but I verified the location for only the 4 bytes variable. I can see that this variable is at the start of the EEPROM (address: 0). But the second sketch seeks the data on address 30. Not even close.
To my understanding avr/eeprom.h is more easy to use since you don't need to police the location of data. But it seems that if change (what?) in your sketch it seeks the data on other locations although on eeprom are fine.
In other words, it's like if I change the firmware (not the EEMEM variables / definitions!), that firmware seeks the data on different places.
I understood something wrong?
In my situation is better to use the arduino EEPROM.h with static location of EEPROM addresses?
Fun fact. Google Bard seems it got it completely wrong:

What are the differences of avr/eeprom.h and EEPROM.h from arduino?

(Google Bard Answer)

The avr/eeprom.h and EEPROM.h libraries in Arduino are both used to access the EEPROM memory on AVR microcontrollers. However, there are some key differences between the two libraries.
avr/eeprom.h is a lower-level library that provides direct access to the EEPROM registers. This means that it can be used to access any location in the EEPROM, but it also requires more code and can be more error-prone.
EEPROM.h is a higher-level library that provides a more user-friendly interface to the EEPROM. It only allows you to access addresses that are within the range of the EEPROM, but it is easier to use and less error-prone.
In general, avr/eeprom.h should only be used if you need to access specific locations in the EEPROM that are not within the range of EEPROM.h. Otherwise, EEPROM.h is the preferred library to use.

Edit: avr-objdump of eeprom section

Prints on Sketch
Without prints
Prints both on Library and Sketch

00810000 <eeprom_lw_dev_nonce>:
00810000 <eeprom_lw_f_nwk_s_int_key>:
00810000 <eeprom_lw_dev_addr>:

00810002 <eeprom_lw_f_nwk_s_int_key>:
00810010 <eeprom_lw_s_nwk_s_int_key>:
00810004 <eeprom_lw_dev_nonce>:

00810012 <eeprom_lw_s_nwk_s_int_key>:
00810020 <eeprom_lw_has_joined>:
00810006 <eeprom_lw_f_nwk_s_int_key>:

00810022 <eeprom_lw_join_nonce>:
00810021 <eeprom_lw_dev_nonce>:
00810016 <eeprom_lw_s_nwk_s_int_key>:

00810026 <eeprom_lw_has_joined>:
00810023 <eeprom_lw_join_nonce>:
00810026 <eeprom_lw_nwk_s_enc_key>:

00810027 <eeprom_lw_tx_frame_counter>:
00810027 <eeprom_lw_tx_frame_counter>:
00810036 <eeprom_lw_app_s_key>:

00810029 <eeprom_lw_rx_frame_counter>:
00810029 <eeprom_lw_nwk_s_enc_key>:
00810046 <eeprom_lw_has_joined>:

0081002b <eeprom_lw_nwk_s_enc_key>:
00810039 <eeprom_lw_rx_frame_counter>:
00810047 <eeprom_lw_rx_frame_counter>:

0081003b <eeprom_lw_app_s_key>:
0081003b <eeprom_lw_app_s_key>:
00810049 <eeprom_lw_tx_frame_counter>:

0081004b <eeprom_lw_dev_addr>:
0081004b <eeprom_lw_dev_addr>:
0081004b <eeprom_lw_rx2_data_rate>:

0081004f <eeprom_lw_rx2_data_rate>:
0081004f <eeprom_lw_rx1_delay>:
0081004c <eeprom_lw_rx1_data_rate_offset>:

00810050 <eeprom_lw_rx1_data_rate_offset>:
00810050 <eeprom_lw_rx2_data_rate>:
0081004d <eeprom_lw_join_nonce>:

00810051 <eeprom_lw_rx1_delay>:
00810051 <eeprom_lw_rx1_data_rate_offset>:
00810051 <eeprom_lw_rx1_delay>:

Image kept for historical reasons.
1st window: Serial.print(s) only in sketch.
2nd window: without Serial.print(s)
3rd window: Serial.print(s) both on sketch and library.

Do you have EEMEM variables in more than one compilation unit?

All EEMEM variables are in a arduino library. I don't redefine them / change order. But maybe the commands to read / or write the EEMEM variables change order! I will edit my question with avr-objdump of variables. With every compile it changes the placement.

By “in a arduino library” you mean in a library's header file or in a library's C++ file(s)?

The arduino library has both .h and .cpp files. EEMEM variables are only in .cpp file of library. In my sketch I don't have EEMEM variables. I have updated the question with comparison of EEMEM addresses with different compile "options". In my sketch I don't change the events. I just add Serial.print statements for debugging. Even if I define print statements, the EEMEM variables change place.

please do not post any text as a picture ... copy the text and paste it into the post ... format it as code

I tried. I wrote before the image that it was difficult to populate the table for easy comparison.

So you put the burden to us visitors, repeated for each single visitor, instead investing your time as the questioner just once. :-}

In my computer the table can't fit, but since it's important to at least two people, I made the edit.

I managed to reproduce your issue with the simple sketch below:
#include <avr/eeprom.h>

EEMEM uint8_t int8_ee;
EEMEM uint16_t int16_ee;
EEMEM uint32_t int32_ee;
EEMEM char str_ee[40];

void show(const char *name, void *address)
{
    Serial.print(name);
    Serial.print(": ");
    Serial.println((uint16_t) address);
}

void setup() {
    Serial.begin(9600);
    show("int8_ee", &int8_ee);
#ifdef SWAP_PRINTING_VARS
    show("int32_ee", &int32_ee);
    show("int16_ee", &int16_ee);
#else
    show("int16_ee", &int16_ee);
    show("int32_ee", &int32_ee);
#endif
    show("str_ee", str_ee);
}

void loop(){}

As is, it prints:
int8_ee: 46
int16_ee: 44
int32_ee: 40
str_ee: 0

If I #define SWAP_PRINTING_VARS, it prints instead:
int8_ee: 46
int32_ee: 42
int16_ee: 40
str_ee: 0

I have no proper answer to your question. Although one may try to unveil
the linker's reasoning, I believe it is safer to just assume that the
way these variables are allocated is unpredictable, and unstable between
subsequent versions of the program.
For your specific issue, I suggest you allocate only one variable to
EEMEM: put everything you need in a single struct, and allocate that
as a whole. I am quite confident it will always end at address zero.
This should be robust against changes in the program provided that, if
you ever add extra fields to that struct, you add them at the end.

Thank you for your effort to DEBUG this. If I understood correctly the variables change location according to reading instead of storing, or both.

@krg: I guess it could depend on the order in which they are referenced in the code. But then, again, I would rather avoid second-guessing the linker and treat the locations as unspecified.

I wouldn't rely on the compiler necessarily allocating variables at any particular memory address, especially after what you posted. You can make a little include file that simplifies reading from/writing to EEPROM, as below:
#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

Then you can do something like this:
int someData;  // declare a local variable

...

EEPROM_readAnything (0, someData);  // read into it, from address zero in EEPROM

...

someData++;
EEPROM_writeAnything (0, someData);  // write it back out, to address zero

The library above uses templates to manage any size data, so you can write or write ints, arrays, etc. One possibility would be to make a struct and read/write the whole thing every time. That way you don't need to keep track of offsets (the whole struct could be written to address 0).

Here's an example of doing that, using offsetof to manage the offsets of individual fields inside your overall struct, the thing that is stored in the EEPROM.
#include <EEPROMAnything.h>

const long MAGIC_ID = 'Nick';

// information in EEPROM
typedef struct {
    unsigned long magic;   // to see if we initialised EEPROM
    unsigned long counter;
    char myName [30];
}  myInformation;

void setup() {
  Serial.begin (115200);
  Serial.println ("Starting ...");

  // see if EEPROM initialised

  unsigned long magicTest;
  EEPROM_readAnything (offsetof (myInformation, magic), magicTest);

  if (magicTest != MAGIC_ID)
    {
    Serial.println ("Initialising EEPROM");
    myInformation initStuff;
    initStuff.magic = MAGIC_ID;
    initStuff.counter = 0;
    strcpy (initStuff.myName, "Nick Gammon");
    EEPROM_writeAnything (0, initStuff); // write whole struct
    } // end of if not initialised

  // find counter
  unsigned long myCounter;
  EEPROM_readAnything (offsetof (myInformation, counter), myCounter);
  Serial.print ("Counter is ");
  Serial.println (myCounter);

  // find name
  char hisName [sizeof (myInformation().myName)];
  EEPROM_readAnything (offsetof (myInformation, myName), hisName);
  Serial.print ("Name is ");
  Serial.println (hisName);

  // add to counter
  myCounter++;

  // write counter back
  EEPROM_writeAnything (offsetof (myInformation, counter), myCounter); // write whole struct

  Serial.println ("Done.");

} // end of setup

void loop()
{
  // whatever
}   // end of loop

Note that your template functions EEPROM_{read,write}Anything() are provided by the standard Arduino EEPROM library since core 1.6.21. They are called EEPROM.get() and EEPROM.put().

Oh, wow! That saves keying in my library. :)


text:
Push button issues
I have been using https://wokwi.com/ to learn Arduino and I am having a problem that seems to be happening no matter what I do. I am trying to set up a push button and an LED. The end goal here is to set it up so that when I tap the push button down and release it that the LED blinks like a turn signal in a car. When I push it down and release it again, the LED should stop blinking. I have tried tons of different code, even using code copied and pasted directly from Arduino's website. What ends up happening is that the button is unreliable. Sometimes the button will click, other times it won't register. It is very bizarre behavior. I read about the bouncing effect but any code I put in to ignore bouncing doesn't seem to have any effect on the system. Why are push buttons so unreliable? I know in real life they aren't because I am able to type this using presumably push buttons on my keyboard. What am I doing wrong??
Here is an example. The push button is totally unpredictable. Why is it behaving like this?

int state = 0;

void setup()
{
  pinMode(9, OUTPUT);
  pinMode(6, INPUT);
}

void loop()
{
  if (digitalRead(6)) {
    state = !state;
  }
  digitalWrite(9, state);
}

the problem is on line 20

I am counting 15 lines

no other guess was possible without seeing the code

you have a logic error in your code ... the code is similar to if it's dark outside, then flip the light switch ... you'd be turning the lights on and off all night long, and the light stands a chance to be left on all day

    state = !state;
  }``` Is that correct?

think about it ... if the button is pressed, then state changes ... this happens 50,000 times per second, once at each iteration of loop()... state will flip back and forth until you release the button

you need to "remember" the state of the button between iterations of loop() ... only if the button state changes, then update the state of the LED

You've got the button wired wrong.  Your resistor is inline with the signal going to the pin.  It should be going from the pin to 5V.  The button should be wired directly to the pin and ground.  Or you can use INPUT_PULLUP in pinMode instead of INPUT and eliminate the resistor entirely.
Your code should test for the button pin being LOW, not HIGH.  When you press the button it will read LOW.  When unpressed it will read HIGH.  This is the normal way that buttons are wired up.
Also note that your loop() function will repeat thousands of times per second.  As long as you still have your finger on the button it will keep cycling the state.  That means that every time you press the button, the state gets cycled a few tens of thousands of times and there's no real way of knowing which state it will be on when you finally get your finger off the button.
You should look at the "State Change Example" in the Arduino IDE.  It shows how to keep track of the previous state of the button so you can react once to each press.

Do you know what I can Google to find that State Change Example? Having trouble finding it. Thanks for the explanation

I think Delta_G means this one: https://docs.arduino.cc/built-in-examples/digital/StateChangeDetection

@wgm, open the Arduino IDE.  Go to the File menu.  File->Examples->Digital.  State Change Detection will be towards the middle.  If you google "Arduino State Change Example" you will be flooded with information and tutorials.  Surely one of them is your speed.

Do you know what I can Google to find that State Change Example - see my website: http://gammon.com.au/switches  - it also talks about transitions


text:
How does actually arduino measure voltage?
I am not interested into the AnalogRead() part, but rather on how he converts 5 or 2 V into a number between 0 and 1023. How does it practically do it to convert the voltage level into a number or into bits to then send to the processor? Thanks in advance

https://en.wikipedia.org/wiki/Analog-to-digital_converter

The ATmega328P features a 10-bit successive approximation ADC. The ADC is connected to an 8-channel Analog Multiplexer.

First, an input is selected from the multiplexer on the left. This allows any of 8 input channels to be active at one time (but only one). These are: A0 to A5 on the Uno (some boards also have A6 and A7). There are also additional input channels (not shown) which also allows the selection of:

The internal temperature sensor
Ground
Bandgap reference voltage

The input channel (multiplexer output) is connected to a "sample and hold" capacitor, as shown. Once an analog conversion starts the switch is opened after 1.5 ADC cycles (12 µs with the default prescaler of 128) so that the capacitor retains its current reading (ie. it holds it) so that the input voltage can now change without affecting the result. This would be useful for fast-changing signals, as the whole conversion can take 104 µs (depending on the prescaler).
To work out the voltage the logic applies the analog reference voltage (ARef) divided down by a DAC (digital-to-analog converter) under the control of the ADC logic. The output of the DAC is sent to the comparator which determines if the input voltage is higher or lower than the reference voltage, at its current divided state. For example, the high-order bit would be set or cleared by setting the DAC to divide the reference voltage by 2 (ie. 2.5V if ARef is 5V). If the input is higher than 2.5V then the high-order bit in the result is set. This takes one ADC cycle (8 µs at the default prescaler of 128 with a 16 MHz processor clock).
To get the next result bit the DAC would be set to the next step (ie. 0.25 of ARef or 0.75 of ARef depending on whether the first bit was set or not) and another comparison done. This process is repeated for all 10 bits.

The Arduino Uno is powered by an ATmega328P microcontroller. According
to the datasheet:

The ATmega48A/PA/88A/PA/168A/PA/328/P features a 10-bit successive
approximation ADC.

On the next page, you can see the following schematic, where I have
highlighted the most essential parts of the converter. You can see the
DAC, the comparator, and the SAR data register.

If you want to get into the details of how this works, see the Wikipedia
article on Successive-approximation ADC. You may notice the
schematic at the top of that Wikipedia page is somewhat similar to the
one above.


text:
DS3231 not keeping time when Arduino is turned off
I am trying to make an LED clock using an DS3231 to keep track of time, but for some reason, it's not keeping time when the Arduino is turned off.
I tried to disconnect the clock from a power source for 5 minutes, and when I powered it back on, the clock picks up the time it was displaying before powering off. I thought the battery I was using at first ran out, and so I replaced it with a new one, but the issue persists. Then I read that it could be that I am using the non-rechargeable one, and to fix this, I removed some resistors and diodes to turn off the charging function, but that also didn't fix the issue. At this point, I'm not sure if this is more on hardware or software issue that the clock is not keeping count of time when Arduino is turned off. It could be that the module I bought was the cheap knockoff, which doesn't function like it should, so I ordered a better one.
I'll the provide the snippet of codes I used:
#include <RTClib.h>
#include <Wire.h>

RTC_3231 rtc;

int hoursNow;
int minutesNow;
int secondsNow;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
//  rtc.adjust(DateTime(2023, 6, 31, 14, 21, 0));
}

void loop() {
  DateTime now = rtc.now();
  hoursNow = now.hour();
  minutesNow = now.minute();
  secondsNow = now.second();
  Serial.print(hoursNow);
  Serial.print(":");
  Serial.print(minutesNow);
  Serial.print(":");
  Serial.print(secondsNow);
  delay(1000);
}

Maybe I'm missing something in the code that is causing it not to do what I want it to do, but I've looked online, and most were pretty similar to the code I have.

rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

You have this line in setup that sets the date and time to the date and time that the code was compiled.  That's fine to set it once, but that time never changes.  It's the time that it was when you compiled the code.  So every time it runs, you are setting the time back to this.  The RTC keeps the time running while the Arduino is off, but as soon as it's turned on your code sets it back to what it was before.
If you remove that line, then things will work the way you want.  You might need to load a sketch once with a line like this to set the time, run it once, then load a new sketch without that line.  Or include a routine in your code to allow a user to set the time.

How would that work? Should I use a conditional statement? I've tried commenting out that particular line just as you suggested, and sure enough, the rtc is keeping real time. However, without that line, it won't update the time to match my current time.

I said it in my answer.  Load a sketch that allows you to set the time.  Run it ONCE.  Now the time is set.  Then load a NEW sketch that doesn't set the time and the RTC will still have the right time that was set by the sketch before.


text:
Arduino IDE 2.1.1 Mac M2 - Fails to upload, No drive to deploy, Raspberry Pico
I'm using Arduino IDE 2.1.1 on a Mac M2 and it's failing to upload, No drive to deploy, I have tried 3 different Mac's, and multiple Picos & USB cables.
Summary of what I've done:

Loaded Example Blink application
Selected board Raspberry Pico W from Raspberry Pi Pico Arduino core 3.3.2
Port selection initially UF2 which shows connected and successfully uploads, then shows as /dev/cu.usbmodem1101

The first time I do the above the blink application works but any further uploads to /dev/cu.usbmodem1101 fail, with the following output:
Resetting /dev/cu.usbmodem1101
Converting to uf2, output size: 660992, start address: 0x2000
Scanning for RP2040 devices
No drive to deploy.
Failed uploading: uploading error: exit status 1

I have only two ports available for upload

/dev/cu.Bluetooth-Incoming-Port
/dev/cu.usbmodem1101

It feels as if I'm either consistently missing some key configuration details or there's technical issues with Arduino IDE or the Pico's

I am not sure if you have the same problem, but I am positive the Arduino-Pico core has some issues in the platform definition regarding the pluggable discovery, and the monitor does not work. See arduino/arduino-ide#2100 (comment) for more details. You can start a discussion and ask the platform maintainers. I hope this helps.


text:
Updating the firmware of Arduino Mega2560
I wanted to connect my Arduino board to MATLAB although it recognized the Arduino board, I kept receiving the error that said:
"Internal error: The initialization of the server code is incorrect."
I got the recommendation of updating my Arduino board's firmware;
So I connected my board to my pc and opened Arduino IDE; It said that the Arduino Mega or Mega 2560 on com6 is connected.
I even uploaded the blink example to my board to make sure that it was connected and fully functioning. Which it was.
But in the above bar in Arduino IDE, "Tools" menu, when I select the "WIFI101/ Firmware Updater" It says that no supported board connected.
What should I do now?
P.S:
I'm currently using Arduino IDE version 2.1.1 and MATLAB 2023a on Windows 11.
I'm sorry, I'm really new to this and would appreciate your help.

Do you have the WIFI101 shield on the Mega?  How are you wanting to use Wifi with the Mega?

I just want to update it's firmware
I don't know how...

The firmware you are trying to use is for the WiFi-101 shield.  It's not for an Arduino Mega.  The WiFi shield might go on a Mega, but this firmware does not.  Do you have that shield?  Or do you just have a Mega?

No I just have a Mega. As I have explained above, it gets detected in MATLAB but I can not fully connect it to MATLAB via its commands. So I got recommended to update my board. This is the link explained my MATLAB problem as well: https://www.mathworks.com/matlabcentral/answers/contributors/29688717-ava/questions/?s_tid=ans_lp_my_ques

OK, I think I understand your confusion from the other thread.  The WiFi101 Firware updater is for updating firmware on a WiFi101 shield.  It has nothing to do with the Arduino Mega.  In order to communicate with matlab you will need some code running on the Mega.  You need to find that sketch and load it on the board.  That will load like a normal sketch.  It will not involve anything that actually says the word "firmware".

Start here: https://www.mathworks.com/help/supportpkg/arduinoio/setup-and-configuration.html
Then here.  This shows how to upload the firmware to the arduino: https://www.mathworks.com/help/supportpkg/arduinoio/ug/configure-setup-for-arduino-hardware.html

https://www.mathworks.com/help/supportpkg/arduinoio/ug/configure-setup-for-arduino-hardware.html
This link has the instructions for connecting the Arduino board.  Look right at the first where it talks about the USB connection. Step 2 where you click program is the step where you are loading the server firmware onto the Mega.  That's the bit it sounds like you're missing.


text:
Can arduino be used in industrial projects?
I'm developing an industrial project and my programming knowledge is limited to arduino.
I'm planning to use either Atmega328 or STM32F103C8T6 chip in my pcb and to program it using arduino IDE. My plan is just to use Arduino IDE to create sketches and programming the chip after burning arduino bootloader.
Is this concept viable for industrial environments? Are there any problems/challenges using this method?

You don't talk about Arduino hardware. Your concern is the Arduino IDE.
Which is a lawyer's licensing topic. Might depend on the libraries you plan to use. And whether you want to hide the fact you're using (selling ?) open source software.

I don't think there are any major problems with your proposal. The chips themselves will have documented limitations (specifications) that you would need to be aware of. I think you would find that most manufacturers of washing machines, toasters, TVs etc. do not also manufacture processor chips, so they too would be relying on commercially-available chips such as the ones you mentioned.
This brings us to the IDE. It is basically a "wrapper" around a C++ compiler which is available for anyone to use in any project. The Arduino libraries themselves may have licensing you would need to be aware of, the same as if you used a library not associated with the Arduino.
See this page: Licensing for products based on Arduino:

Note:

You can freely use Arduino hardware and software for your personal purposes, or within your company or organization, with no restrictions. The rules described in this document apply only when you distribute products based on Arduino to third parties or you make them public in any form.
If you comply with the open-source licenses of Arduino, you can distribute your software/hardware products for free or commercially. This document provides a summary of such rules for your convenience and does not waive the need to get professional legal advice.

I am not a  lawyer, and if you are worried about the legal aspects I suggest you get legal advice. However I doubt that a small-scale project would warrant anyone getting their lawyers involved. For one thing, it would be hard to prove that the 0s and 1s on your chip were produced using the Arduino IDE, or any of its libraries.

The chips should work fine, however it depends on how things are assembled, what parts are used, ambient temperature, cooling and electronic protection. For reference here is what I use:
Hobby: 0°C to 50°C
Commercial: 0 ° to 70 °C.
Industrial: −40 ° to 85 °C.
Military: −55 ° to 125 °C.
Automotive: -40°C to 175°C, location dependent.
Without a complete set of specifications, schematic, and component information I cannot give you a yes or no answer.
At this point you should realize it will not be a slam dunk simple project.

Industrial environments can be hostile to electronics that aren't "hardened" against the potential hazards. There is no one answer to this without knowing the specific environment. Will it be controlling heavy electrical machinery (even if not switching the power). You'll need to know more about the intended environment to know whether and how you can harden your electronics to it.
But if nothing else, Arduino is terrific for prototyping things that, once the concept is proven, might then have to be re-built to a higher standard for production use.

If the project is also going to have a commercial aspect to it you may also want to look at some of the licensing models applicable to Arduino projects.


text:
text section exceeds available space in board for esp32 + bluetooth + wifi + httpclient
I trying to learn how to write arduino code for an ESP32 WROOM 32.  I want my esp32 to make an http request to a RESTFUL API i've set up. Thus, my esp32 will need wifi access. I was planning to use Bluetooth to tell my esp32 what wifi connection details to use and the specific address of the RESTFUL API end point.  I read some documenation online and people suggested that I would need BluetoothSerial.h for bluetooth connection, <WiFi.h> for wifi connection and <HTTPClient.h> for make HTTP requests.
But the moment I include all 3 packages and initialize a few variables and try to compile, my Arduino IDE gives me the following error:
text section exceeds available space in boardSketch uses 1428393 bytes (108%) of program storage space. Maximum is 1310720 bytes.

Global variables use 55740 bytes (17%) of dynamic memory, leaving 271940 bytes for local variables. Maximum is 327680 bytes.
Sketch too big; see https://support.arduino.cc/hc/en-us/articles/360013825179 for tips on reducing it.
Error compiling for board ESP32-WROOM-DA Module.

This is the code that caused the error:
#include "BluetoothSerial.h"
#include <WiFi.h>
#include <HTTPClient.h>

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
const char* ssid = "";
const char* pass = "";
String apiUrl = "";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA); //Optional
  WiFi.begin(ssid, pass);

  while(WiFi.status() != WL_CONNECTED){
      delay(100);
  }
  SerialBT.begin("ESP32test"); //Bluetooth device name
}

void loop() {
  delay(20);
}

As you can see, I haven't even begun any real coding and I already get an error that suggest my ESP32 doesn't have necessary resources.
Did I do something wrong?  What else should I consider?

UPDATES
@jsotola
When I comment out the lines BluetoothSerial SerialBT; and SerialBT.begin("ESP32test");, then the program compiles and I see this message:
Wrote 726112 bytes (464336 compressed) at 0x00010000 in 7.0 seconds (effective 828.6 kbit/s)...
Hash of data verified.

So does that mean just those two lines of bluetooth related code takes up about 700kb?
@hcheung - If I change the Tools > Partition Scheme from Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) to 8MB with spiffs (3MB APP/1.5MB SPIFFS), then Arduino IDE compiles and writes the code to my ESP32.  However, when I try to use my Android phones Serial Bluetooth app to try to connect to the ESP32, I get the error Connection failed: read failed, socket might closed or timeout, read ret:-1.  So it seems the partition scheme affects bluetooth functionality.
I also tried changing the Tools > Flash Size from 4MB to 8MB.  And I get the same behaviour - 4MB doesn't compile.  But 8MB does compile.  But after it compiles my phone can't connect via bluetooth.
And just to be sure, the following code below from File > Examples > BluetoothSerial > SerialtoSerialBT only works with Flash Size 4MB and Default Partition Scheme of Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}

what is the program size if you remove all of the bluetooth program lines?

From Arduino IDE, click on menu "Tools -> Partition Scheme" to configure your board with larger flash memory size.

thanks @jsotola i updated my question with details to your question.  Seems like bluetooth lines use up half the memory/flash size?

thanks @hcheung, i updated my question with details to your suggestion. Seems like changing partition scheme or the flash size lets the program compile, but it disrupts the bluetooth connection

choose other options than 8MB unless you know for sure that your ESP32 came with 8MB flash memory. Changing the partition scheme has nothing to do with Bluetooth functionality.


text:
Using Soft UART - how include library
I want to use the soft serial communication example.

But when I compile it, it sais:
/home/xxx/Arduino/SoftwareSerialExample/aa/aa.ino:28:28: schwerwiegender Fehler: SoftwareSerial.h: Datei oder Verzeichnis nicht gefunden
Kompilierung beendet.
exit status 1
Fehler beim Kompilieren für das Board Arduino Uno.

What is going there?
I  have a directory also with AFSoftSerial.h at /Arduino/libraries/AFSoftSerial/AFSoftSerial

the library should be here /home/xxx/.arduino15/packages/arduino/hardware/avr/1.8.6/libraries/SoftwareSerial

Check to make sure you have the line:
#include <SoftwareSerial.h>

... at the top of your Sketch.
Also, compare your code with that found on the Arduino Software Serial Library web page here.
Finally, make sure your Arduino Application and all your Arduino Libraries are up to date.

I have a directory also with AFSoftSerial.h at /Arduino/libraries/AFSoftSerial/AFSoftSerial

The code is looking for the "SoftwareSerial" library and that is the library you need include and call, not "AFSoftSerial". Or, if you intend to use AFSoftSerial, then change your code to say that instead.

Download Arduino SoftwareSerial library, extract it and put it into your libraries folder. Libraries folder is in your project folder. If you haven't changed project folder in Preferences, it will be in C:\Users\your_username\Documents\Arduino. Be careful that there are not two SoftwareSerial folders.
Then try to upload your code again.

just no. the Arduino SoftwareSerial library is bundled with the AVR boards package

But the compiler said "No such file or directory". Which means that the library is not installed anywhere.

which means something went wrong with the boards package installation and just putting random SoftwareSerial library into the libraries folder will not fix it


text:
Problem with reading MIFARE 13.5Mhz with MFRC522 lib
I'm trying to read the UID of MIFARE 13.5Mhz cards with MFRC522 lib and I have defined the following function for it.
void getUID() {
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
  Serial.println("Scanned PICC's UID:");
  tag = "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
   {
    tag.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    tag.concat(String(mfrc522.uid.uidByte[i], HEX));
   }
  tag.toUpperCase();
  Serial.println(tag);
  mfrc522.PICC_HaltA(); // Stop reading
}
}

this function works perfectly fine in void loop() but when I call it in the following web request my esp8266 crashes.
controlserver.on("/searchuid", HTTP_POST, [](AsyncWebServerRequest *request){

    transmit = request->arg("idcode");
    if (request->hasArg("configmodule")) {
    File file = SPIFFS.open("/inputString.txt", "r");
    if (!file) {
    Serial.println("Failed to open file");
    return;
    }
    getID();
    delay(500);
    Serial.println(tag);
    String content = file.readString();
    if (content.indexOf(tag) >= 0) {
    Serial.println("Found search string");
  } else {
    Serial.println("Did not find search string");
  }

    }
  });

and I cannot understand why, any help will be appreciated.

Under "Important Things To Remember" in the ESPAsyncWebServer README:

You can not use yield or delay or any function that uses them inside
the callbacks

Your code calls delay() in the callback, and calls functions that you cannot know do not call delay() or yield().
You need to rewrite your code to follow the instructions in the web server's documentation.


text:
Teensy 4.1 Synchronized PWM - ADC sampling
I'm looking to drive a high side driver at PWM frequency of 200Hz on a Teensy 4.1 with variable duty. The high side driver current sense pin is connected to an analogue pin on the Teensy. I want to sample an analogue reading only when the PWM output is low (HSD is on). I'll also likely need to read the analogue input with some delay after the PWM output has gone low (approximately 200uS).
How can I achieve this and guarantee synchronisation?


text:
Using SPI on Pi Pico, Arduino IDE
Beginner with the Pi Pico here, but I studied electronics engineering and am reasonably hardware literate. I've used mbed online for a project prior to covid.
I want to use SPI to connect to a display using the ILI9488, (480 x 320 TFT panel), however, I cannot see how or where I would define SPI pins, and my understanding is that using SPI.h would default to Arduino pinouts - the uno etc being pin incompatible with the pi pico.
Do I need to trudge through the SPI.h file to try to work out how I set the pins manually? Or am I barking up the wrong tree?
I am using macOS, Arduino IDE 2.1.1 and have no issues connecting to the pico W. Please ask for any other clarification, I can provide a schematic of my design if it makes things easier. Love the pico but am finding it hard to use with C/C++.
Thanks,
KL

the pins are defined in the variants file for the selected board so the SPI library has the pins specific for the board

Depend on which Arduino Core you installed. The variants definition of Arduino Core describe the pin assignments for each board. There are two Arduino Core for Pico, the board variants definitions for the one by Earle Philhower can be found here, another one based on mbed by Arduino is here.

You can read the actual SPI pins with the following sketch
    void setup() {
      Serial.begin(115200);
    }

    void loop() {
      Serial.print("MOSI: ");
      Serial.println(MOSI);
      Serial.print("MISO: ");
      Serial.println(MISO);
      Serial.print(" SCK: ");
      Serial.println(SCK);
      Serial.print("  SS: ");
      Serial.println(SS);
      Serial.println();
      delay(5000);
    }

As Juraj wrote, they are defined in the board files.
I have no experience with your ILI9488 display and the corresponding library. Many libraries allow you to use software defined pins. I would not recommend that, especially for a display with 480 x 320 pixels. You really need the speed of the hardware SPI.


text:
ArduinoJson library: how much space to allocate for serialized buffer?
I am using the fantastic ArduinoJson library for working with JSON data on my ESP8266. I have been facing issues with random software wdt resets and have been investigating memory leaks wherever I can. I want to trim down my use of Strings and DynamicJsonDocuments as much as possible. So I thought of using automatic variables: char buffers: char[N] and StatitcJsonDocuments instead.
I am using the ArduinoJson assitant service to help me figure out how many bytes I should reserve. The following is one response payload, I am expecting to receive:
// char input[MAX_INPUT_LENGTH];

StaticJsonDocument<128> doc;

DeserializationError error = deserializeJson(doc, input, MAX_INPUT_LENGTH);

if (error) {
  Serial.print(F("deserializeJson() failed: "));
  Serial.println(error.f_str());
  return;
}

int statusCode = doc["statusCode"]; // 200
bool needUpdate = doc["needUpdate"]; // true
const char* message = doc["message"]; // "update required"

JsonObject data = doc["data"];
const char* data_deviceId = data["deviceId"]; // "DLD00005"
const char* data_user_fw_version = data["user_fw_version"]; // "0.0.0"
const char* data_new_fw_version = data["new_fw_version"]; // "0.0.5"

As you can see I am using a char [N] type as the input, which is in fact being copied using strncpy() from the https.getString().c_str() from the response of a previous https.POST() request. My issue is that I do not know how much memory I should reserve for the char[N] array, ie what should be the value of N? The reasons I ask is that I am getting a deserialization() failed: IncompleteInput error, which I'm pretty sure is because the char[N] buffer is not large enough. So my question is if the StaticJsonDocument object is 128 bytes, then how big should I make the char[N] buffer (is there any relation between the sizes)? Or should I just go with an arbitrarily large value like char[512] which I want to avoid to avoid stack overflows?
StaticJsonDocument<128> payload;
char payloadSerial[???];
...
int status = https.POST(payloadSerial);
strncpy(payloadSerial, https.getString().c_str(), sizeof(payloadSerial));
DeserializationError error = deserializeJson(payload, payloadSerial, sizeof(payloadSerial));
if (error) {
    Monitor.print(F("DeserializeJson() failed: "));
    Monitor.println(error.f_str());
}

You're asking about code that looks like this:
StaticJsonDocument<128> payload;
char payloadSerial[???];
...
int status = https.POST(payloadSerial);
strncpy(payloadSerial, https.getString().c_str(), sizeof(payloadSerial));
DeserializationError error = deserializeJson(payload, payloadSerial, sizeof(payloadSerial));

The documentation for deserializeJson() shows that it can accept a String directly:
DeserializationError deserializeJson(JsonDocument& doc, const String& input);

So there's no need to copy https.getString().c_str() into payloadSerial. You can just pass the String that https.getString() returns:
StaticJsonDocument<128> payload;

int status = https.POST(request_body);

DeserializationError error = deserializeJson(payload, https.getString());

You were using the same character array here for both the body of the request that you passed to POST() and for deserializing the JSON response. While this is okay, for clarity I changed the POST call to use something else as the character array is completely unnecessary for processing the response.
Even if deserializeJson() didn't accept a String type as an argument, you still wouldn't need to copy the response into a buffer. You could just pass https.getString().c_str():
StaticJsonDocument<128> payload;

int status = https.POST(request_body);

DeserializationError error = deserializeJson(payload, https.getString().c_str());

You really should check the value of status. It indicates whether the POST succeeded or not. If it failed, you should report that and the reason for the failure, and not attempt to process the returned payload as there is no returned payload.


text:
Need help with ATtiny85 code
I am looking for help with ATtiny85 coding. The project I am working on is using an Arduino Nano and I want to switch to an ATtiny85.
The code below works with the Nano but not with the ATtiny85. I am relatively new to Arduinos and have done a few projects with success but this is my first time using an ATtiny.
I will try to explain. When the code is running on a Nano

It is checking for a number between 1 and 32 in the EEPROM at address 0.
If the number is outside either value it will generate a random number between 18 and 32.
I then check to see if the value at address 0 in the EEPROM is less than or equal to 0, if not it will decrement that value and store the new value in address 0.
Once the value is at 0 or less a separate value is generated for a time delay.
Once that time delay has occurred pin 7 outputs power for 1 second and stops.
Once that has occurred a new random number is generated and stored in address 0.
To decrement the value the Nano is powered off and on again and the check is made.

I have tested this code with a Nano multiple times and with pin 7 connected to an led it turns on and off, resets and begins again. When I load this code onto an ATtiny85 and run the same test the led will not turn on, also I get an error with the Serial.begin(9600) and anything else starting with Serial, so I comment them out and it compiles and uploads just fine. I have the Spark Fun AVR programmer and was able to get the ATtiny to blink an led using a simple led blink sketch but that's as far as I got. I need some help.
    #include <EEPROM.h>  // Include the EEPROM library

    void setup() {
      Serial.begin(9600);          // Initialize the serial communication
      pinMode(7, OUTPUT);          // Use digital pin 7 as output
      randomSeed(analogRead(0));   // Seed the random number generator with a random value
      int value = EEPROM.read(0);  // Read the value stored in EEPROM address 0

      if (value <= -1 || value > 32) {  // If the value is not between 1 and 32
        int new_Value = random(18, 32);  // Generate a new random number between 18 and 32
        EEPROM.write(0, new_Value);    // Store the new value in EEPROM address 0
        Serial.println("Generated a new random number: " + String(new_Value));
      }

      else if (value <= 0) {     // Check if the random value is less than or equal to 0
        value--;                 // If no then decrement the value
        EEPROM.write(0, value);  // Write the new value to EEPROM address 0
        Serial.println("Random number from EEPROM: " + String(value));
      }

      else {
        int time_delay = random(1, 25);  // Generate random number for time delay
        Serial.println("Generated Time Delay: " + String(time_delay));

        delay(1000 * time_delay);

        digitalWrite(7, HIGH);
        delay(1000);
        digitalWrite(7, LOW);

        int new_Value = random(18, 32);  // Generate new random day value
        EEPROM.write(0, new_Value);    // Write new value to EEPROM address 0
        Serial.println("Generated a new random number: " + String(new_Value));
      }
    }
    void loop() {
    }

Sketch used for LED blink
    void setup() {
      pinMode(0, OUTPUT);
    }

    void loop() {
      digitalWrite(0, HIGH);
      delay(5000);
      digitalWrite(0, LOW);
      delay(5000);

does not work is not a useful description of a program behavior ... what exactly happens when you run the program?

was able to get the ATtiny to blink an led ...look at your blink LED code and compare to this code

Have a look at this answer: https://arduino.stackexchange.com/a/47616/37523

@VE7JRO, I will give that a try, thank you.

if the blink program works, then why did you not use the same pin for your program?

When you put this code on the nano you use pin 7.  When you put it on the ATtiny85 what pin number do you use?

if (value <= -1 || value > 32) - I don't see how a single byte, which will range between 0 and 255 could ever be less than 0.

@NickGammon value is of type (signed) int so it can be less than 0

@SBF EEPROM.read() returns uint8_t which is unsigned. I realise value can hold negative numbers, but since its value is put there by EEPROM.read() it won't, in this particular case, ever be negative.


text:
Timer interrupt setup for one second is too slow (~ 4 seconds)
I am trying to use the timer interrupt on an Arduion Uno.
Here is a imple example code for displaying a progressive digit on a lcd display, which is updated with timer interupt every second:
#include <LCD_I2C.h>

LCD_I2C lcd(0x27);
volatile bool timerFlag = false; // Timer-Flag (timer-Interrupt)
int displayWidth = 16; // display width
int digit = 0; // current digit

void setup() {
  lcd.begin();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = (1 << CS12) | (1 << CS10); // set Prescaler to 1024
  TCNT1 = 0;
  OCR1A = 15624; // should be 1 second with a prescaler of 102
  TIMSK1 |= (1 << OCIE1A); // Enable timer interrupt
  interrupts();
}

ISR(TIMER1_COMPA_vect) {
  timerFlag = true;
}

void loop() {
  static int position = 0;
  char displayString[17]; // +1 null termination

  if (timerFlag) {
    lcd.clear(); // clear display

    // update digit and progress
    digit = (digit + 1) % 10;
    position = (position + 1) % (displayWidth + 1);
    memset(displayString, ' ', displayWidth);
    displayString[displayWidth] = '\0'; add null termination
    displayString[position] = '0' + digit; // Character for the current digit

    // Show updated progress on the display
    lcd.setCursor(0, 1);
    lcd.print(displayString);

    timerFlag = false;
  }
}

The values for setting up he inteupt timer 1 for 1 second is arround everywhere.
BUt the updates generated by this code is clearly much slower than 1 second, it's more about 4 seconds.
So i did a comparison with a delay based version of the same example:
#include <LCD_I2C.h>

LCD_I2C lcd(0x27);
int displayWidth = 16; // display width

void setup() {
  lcd.begin();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");
}

void loop() {
  for (int digit = 0; digit < 10; digit++) {
    char displayString[17]; // +1 null termination
    int position = digit % (displayWidth + 1);

    // Update progression
    memset(displayString, ' ', displayWidth);
    displayString[displayWidth] = '\0'; // add null termination
    displayString[position] = '0' + digit; // Character for the current digit

    // Show updated progress on the display
    lcd.clear(); // Clear display
    lcd.setCursor(0, 1);
    lcd.print(displayString);

    delay(1000);
  }
}

This one works as expected and updates every second.
So what is wrong with my interrupt settings?

There is a flag in TCCR1A/B called WGM12 which sets the wave generation mode (WGM) to Clear Timer on Compare Match (CTC).
This causes the timer to count up to the value in OCR1A and then automatically reset to 0.
This flag was forgotten, so the interrupt simply ignores the setting OCR1A = 15624; and counts through to 65535, which corresponds to the observed factor of about 4.
Therefore the setting line for TCCR1B must be changed to
TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10);
// Set CTC mode and set Prescaler to 1024

Now the interrupt is triggered correctly every second.

"This still got me some time to find out what it means and what i needed to do, so:" I'm pleased that it was a useful learning exercise for you and your description looks good. Much more valuable than receiving a ready made and complete solution.

It is ignoring this OCR1A = 15624; and simply rolling over at 65535 instead., hence the error factor of 4. You have to set the wave generation mode as CTC in registers TCCR1A/B.

Thank you for the answer.
Unfortunately, I won't be able to try it out until after the weekend.
I will see if it works (but I am pretty confident)

This still got me some time to find out what it means and what i needed to do, so:
The ctc mode means "Clear Timer on Compare Match" and is controled by the WGM12 flag in the TCCR1A/B register. As I'm using the TCCR1b, the line gets:
  TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10);