text:
Arduino Temperature Sensor
We are doing a project and we need to build a thermo sensor and read the voltage and the temperature but we also have to have the temperature correspond to LEDs that will give a blue for cold green for mild and red for hot we are using a DS18b20 thermo sensor.
How should we write the code or where could we find code that would work for this purpose?
We both have a very surface level understanding of code at the moment, however our time constraints have made learning it difficult.

Please show us the code you've written so far.

What is the reason for your time constraint? Is this a school project? Is it for CS? What resources do you have for the class? Do you understand how to set up the hardware, and just need help with the software? What's your background?

This forum isn't great for detailed solutions to vague problems. If you don't have much experience with programming, you'll have a lot to figure out. It will take you a while (realistically probably a couple of weeks if you work at it every day, and have a knack for it, assuming you're starting from scratch.)
The first step is to define your problem. It sounds like you want to build a project that uses colored LEDs to indicate the measured temperature in different ranges.
So lets say you want:
Temp <10°C light Blue LED
Temp 10°C - 30°C light green LED
temp >30°C light red LED.

Break the problem into bite-sized pieces and solve them one at a time.
Pick an Arduino model. Install the IDE. Run a sketch that will blink the built-in LED. Then do a google search on "Arduino Blink without delay" and rewrite your blink code to not use the delay() function. Forget the delay() function exists and never use it again, since it will usually get in the way of what you need to do.
Then figure out how to wire separate LEDs (including current limiting resistors) to 3 separate pins. Make your code blink all 3 LEDs at the same time by toggling the appropriate pins' output states.
Modify your app to blink first one LED, the 2nd, and then the third. Now get tricky and modify your app to blink the first LED on and off once a second, the next LED once every 1/3 of a second, and the fourth LED to blink once every 1/4 second, all at the same time. (That will force you to really understand how to do timing without delay.)
Now look up a sample project that uses your temp sensor. (Try this one I found, for example) Run that and get it to send the temp to your serial port once every few seconds. (again not using delay().)
Now write a loop that reads the temp sensor, decides which range the temp is in, and lights the appropriate LED based on those ranges. Note that you may only be able to read the temp every 2 seconds or so (the DHT22 and DHT11 temp sensors I've used have that limitation.)


text:
Will bootloader communicate via TX0 / RX0
I'm fairly new to Arduino programming but have a good deal of experience with  low-level programming early processors, having originally cut my teeth on Z80, 8088, etc. I'm looking at developing a sizeable project using a Mega 2560. The project includes quite a lot of off-board logic, leds, and an RPi. Thus I don't want to overload the 2560 voltage regulator and really want to use common rail 5v power with a switch-mode supply. However, I also need debugging / console access, so this gives me the immediate problem of direct 5v driving whilst the board is being driven with 5v from the USB port, which is a no - no. The solution appeared to be fairly simple - use a CH340 - based USB to serial converter and connect it to RX0, TX0 and Reset (DTR output connected via a blocking capacitor) but with its 5v output disconnected. With this setup, the Arduino communicates quite happily with the IDE-based serial monitor (the sketch was downloaded via the on-board usb port), but on trying to download a new sketch via this route, AVRDude fails with a timeout. At the commencement of the download the processor is being reset, but the bootloader doesn't appear to hansdshake with AVRDude (properly). Is this a known feature or have I missed something?

the bootloader listens on RX0/TX0. the on-board USB chip is connected to this pins

Problem solved. The standalone CH340-based converter for whatever reason isn't man-enough to reliably pull down the RX0 line when connected to the Mega 2560 (also with a CH340 converter on board). I've seen suggestions posted in various places that this can be a problem with respect to DTR (though I don't have a problem with it). My solution is to insert a 7417 open-collector non-inverting buffer between the output of the stand-alone converter and the RX0 input on the 2560 board. I've not been able to find a schematic for the Mega 2560 board to determine its pull-up resistor size but imagine it must be relatively small. Thanks to those who made suggestions.

source: Stack Exchange

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

sort: votes


text:
RTC DS3231 Not resetting time on power loss
I'm completely removing power from a DS3231 RTC module and my call to rtc.lostPower() is never hit when I reconnect everything. I'm also removing the battery, I left it overnight and it remembers the time just before I disconnected everything, but doesn't register a power loss. I'm using this with a D1 mini.
void setup() {
  // put your setup code here, to run once:
  Serial.begin(baud);

  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC.");
    while (1); // while true
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, resetting time.");
    ConnectWiFi();
    GetNtpTime();
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    Serial.println("Time set after power loss");
  }
}

please add a link to the module datasheet and to the DS3231 datasheet

@jsotola: Here is the datasheet of the DS3231. The lostPower() method returns the “Oscillator Stop Flag” from the status register (c.f. datasheet, p. 14).

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


text:
ESP-01 Deep Sleep not waking up properly
I have a temperature/humidity project using an ESP-01 and DHT11.  I want to be able to put t into deep sleep to preserve battery life.  I have soldered a wire from GPIO16 to RST.
#include <SimpleTimer.h>  //https://github.com/jfturcot/SimpleTimer
#include <ESP8266WiFi.h>
#include <PubSubClient.h>  //https://github.com/knolleary/pubsubclient
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>  //https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA
#include "DHT.h"

//USER CONFIGURED SECTION START//
#define DHTPIN 2     // what digital pin we're connected to

const char* ssid = "mySSID";
const char* password = "password";
const char* mqtt_server = "mqttserverip";
const int mqtt_port = 1883;
const char *mqtt_user = "usser";
const char *mqtt_pass = "pass";
const char *mqtt_client_name = "DryerMCU"; // Client connections can't have the same connection name
//USER CONFIGURED SECTION END//

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);
SimpleTimer timer;

bool boot = true;
int status = WL_IDLE_STATUS;

//Functions
void setup_wifi()
{
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void getTemperature()
{
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");

  char temperature[50];
  char humidity[50];

   // Update temperature and humidity
  String temp_str = String(f);
  temp_str.toCharArray(temperature, temp_str.length() + 1);
  client.publish("dryer/temperature", temperature);

  String hum_str = String(h);
  hum_str.toCharArray(humidity, hum_str.length() + 1);
  client.publish("dryer/humidity", humidity);

}

void setup() {
  Serial.begin(38400);
  delay(2000);
  Serial.println("Booting");

  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  getTemperature();

  Serial.println("Going to sleep");
  ESP.deepSleep(10000000,RF_DEFAULT);
}

void loop() {

}

When I start it up it takes one measurement, goes to sleep and then wakes up, but nothing happens once it wakes up.  Serial output:
Booting

Connecting to SSID
  ......
WiFi connected
IP address:
mqttip
Humidity: 51.00 %   Temperature: 20.00 *C 68.00 *F  Heat index: 19.39 *C 66.90 *F
Going to sleep

ets Jan  8 2013,rst cause:5, boot mode:(3,7)

ets_main.c

I added a Serial.println("woke up"); right after ESP.DeepSleep and it never prints that line.  Also, I was under the impression that the setup() method gets called again when it wakes up as if it had just been reset

That did not help.  It still doesn't do anything after the ESP.DeepSleep

reduce your code to minimum ... example code is here at "basic deep sleep" ... https://www.losant.com/blog/making-the-esp8266-low-powered-with-deep-sleep   .... i was very wrong about putting code in loop() ... looks like the esp resets when it wakes up

I tried the very basic version from your link and still get the same result.  It appears to sleep, but nothing runs after it wakes up.  What else could it be?

please post a picture that shows the wire you soldered onto the circuit

Did the same project.  Used ESP-Now instead of normal WIFI protocol and 3 ESP8266 ESP-01 boards (1 for the sensor and 2 to make a ESP-Now to WIFI bridge).  I abandon the DHT11 as I had one fail in a very hard to get to location & switched to the Si7021.  The remote ESP-01 which goes to sleep needed to be modified in order for the onboard timer to wake it up.  Has been running outside for over 2 months now.  Should really push this code back to github.  Add a comment if you want to try this route instead of normal WIFI.

I'd try putting Serial.flush();  before the deepsleep.

In the question the OP said:

I have soldered a wire from GPIO16 to RST.

But, I'm going to post an answer for the people who find this question and need the ESP-01 modification instructions in order to wake an ESP-01 module up from deep-sleep:
The ESP8266 mounted on an ESP-01 board will not wake up from deep-sleep because the ESP8266 wake up signal is not connected to the reset pin of the ESP8266 on an ESP-01 board.  You need to add this connection which can be difficult for most people.  You can see the modification in this picture:

...which comes from this instructables posting.
If this is too difficult, consider using a different ESP8266 board which brings these ESP8266 pins to board edge connectors.

I guess you have a race condition between automatic connection to WiFi by the Espressif SDK and your WiFi.begin(). You have two options how to solve it.
1. option: Don't use WiFi.begin in this sketch. Use an utility sketch to set the SSID and password and the SDK remembers it persistent on flash. Then it is able to connect fast to WiFi specially on reset, because it has the WiFi channel number in RTC memory which is not cleared at reset (only on power down).
2. option: turn of remembering of the SSID and password and the automatic connection at start. Then the esp8266 will connect to the WiFi only with your WiFi.begin call. The commands are WiFi.persistent(false) and WiFi.setAutoConnect(false).
You can turn of the SoftAP too. At default it starts automatically. The command is WiFi.softAPdisconnect()

I don't think the issue has to do with WiFi at all.  I have completely stripped down the code to just have it go into Deep Sleep and I get the same behavior.

@Brian, try setAutoConnect(false). the automatic connection starts before the sketch


text:
Nodemcu powering with 5.2v and 2A?
I bought a this voltage regulator . DC-DC 5v 8A voltage regulator. ıts supported 8-35V input voltage . And i want to use this with 12v power supply.
But i searched on the internet . Nodemcu max amp is 800mA. This device can provide 2A per usb output if i will plug the nodemcu with usb cable this what happen ? Does it burn ? How can i drop the amps ?  i want to use other 3 usb output with other devices sensors and screen .

the 8 A is the maximum current that can be supplied before the power supply shuts down, or the output voltage starts to drop .... it does not mean that 8 amps will be pushed through any load  ... the amount of current that 5 V can push through a load is dependent on the load resistance

@jsotola i understand thanks for your answer :)

Generally, we specify DC power supplies as constant voltage sources.  In order to do this, power supplies deliver more or less current as demanded by the load in an attempt to keep the voltage constant regardless of the load.
When a constant voltage DC power supply specifies a maximum current, it is saying the power supply can only maintain the specified voltage while the current demand is less than the specified maximum current.
To be clear, unless you need a constant current power supply, a power supply should be picked based on the required constant voltage.  And the capacity of that power supply, usually measured in Amps, should exceed the maximum combined current demand of all connected devices (loads).

usb output is 5.2V which is its ok . But now I have a prototype for my project . i plug nodemcu to pc usb port and its provide 500mAh and its ok . but i want to connect 5v 2A usb port . I dont have too much electrical knowledge  . I have difficulty about that. I just wonder nodemcu and other devices does it burn or not ?

USB ports are regulated to be 5 volts or very close to 5 volts.  You don't regulate both voltage and current.  It is one or the other.  Older USB ports are obliged to supply up to 500mA.  Newer USB ports can supply more.  But you only need to match voltages when talking about constant voltage power supplies.  You do not match the current values.  You only need to make sure you draw less current then the constant voltage power supply is rated for.

For example, it is fine if you plug in a USB keyboard which expects 5 volts and draws only 15mA.  As even the oldest USB computer ports supply 5 volts and have at least 500mA to offer.  See, 5 volts == 5 volts and 15mA is < 500mA.  So this should work fine.

Ok. I understand now. more clear in my mind. Thank you for explanation and fast reply :)

It will not burn.  The nodeMCU will only "pull" the amount of current (amps) it needs.

Thanks man .  I'm saying hypothetically. We will connect 5v 10A supply for nodemcu and nodemcu still pulls as much as it needs right ?

Yes, it will only pull as much as it needs no matter how many amps the supply is capable of.

Ok man thanks for your answer :)


text:
Arduino UNO not showing up in USB devices on Ubuntu 18.04
I have an Arduino UNO (clone, not original) that was working fine until a couple of days ago. Now, it does not show up when I connect it to my laptop.
Things that I've troubleshouted:

USB cable is fine (tried with another Arduino).
USB ports are fine (tried with another Arduino).
Followed all the fixes and checks listed
here
and everything is successful.
I can upload sketches trough ICSP using a working Arduino.
I've tailed syslog while connecting and disconnecting the failing
Arduino and nothing shows up (it does when using the "good one").
I've tried on a Windows 10 machine and it doesn't show up.

What else can I try?

CH340 USB chip on it?

@Majenko Atmega16U2

Unusual. Maybe it's not a real one or its a factory reject. Probably dead. Continue using ICSP or use a USB UART dongle with it

Wondering if you bricked it similiar to my issue. @Majenko helped me as well :). Link to that answer located here: https://arduino.stackexchange.com/questions/66239/windows-10-does-not-recognize-arduino-leonardo

@static_cast I see that your problem was solved by reuploading the bootloader. I've already try that and it didn't work :(

I can't comment yet but have you updated your board manger for UNO on unbunto?
tools > Board > Board Manger > Search UNO
Kind of dumb to have to do that but it happen to me before and this was the solution I did.

It's already at the most recent version.


text:
Routing Arduino Mega output to either one of two serial ports
I have an Arduino Mega controller that normally communicates via Bluetooth (HC08 Bluetooth module) to an Android device. In case there is a problem on the Android side I wish to have a fallback ability to communicate via the USB serial port. The choice of serial port is determined by a hardware switch that the Arduino can read. Currently I have:
HardwareSerial & Terminal = Serial;
HardwareSerial & BTPort = Serial1;

Is there a way to route an output to either BTPort or to terminal, dependent on the state of the switch? Ideally I would like to do something like this:
HardwareSerial & OutputPort
if(switch_is_on)
  OutputPort = Terminal;
else
  OutputPort = BTPort;

Obviously the above code does not work. I have no idea of how to proceed.

Like you, I would use a global variable e.g. switch_is_on and I would write a method printSerial( ... ) containing a if else statement that uses the Serial object for the swich_is_on == true case and Serial1 for the else case. I would use this method instead of the Serial/Serial1 print methods. Also, to me it is not obvious whay your try should not work. What's the problem (besides the missing semicolon of cause ;-))?

Thank you, Peter, for your comment. Yes, it solves the problem, but not in the most efficient way. It would be most efficient if one could just re-assign a (pointer to?) a serial port and directly use the println for the re-assigned port. Your suggestion is a very useful work-around, though.

As I said, I don't know any reason, why you can't assign Serial or Serial1 to a variable of type HardwareSerial &<name> like HardwareSerial &activeSerial = Serial1; If you declare activeSerial as a global variable, you can access it from everywhere. I just don't know why it is obvious that this shouldn't work. At least for me it should. If you only want to use pointer, use HardwareSerial *activeSerial = &Serial and activeSerial->print....

But, I would prefer the printMethod because it is the most effective way. What happens if you change the switching flag while the program is running? If you have a predefined activeSerial variable nothing happens. The method would use the other Serial intead. You see the idea?

FYI: https://forum.arduino.cc/index.php?topic=358740.0

@PeterPaulKiefer, reference must be assigned at definition

I have:  HardwareSerial *Myserial;  Myserial = Serial1;  This gives an error: Myserial does not name a type.

Only initialization is allowed at global scope, e.g. HardwareSerial *hs = &Serial1;. Or do the assignment in a function.

@Juraj Thank you for pointing that out, I did not explain it clearly. References ( &) must be declared and  initialized together, so they can not be used to compute alternative references later on. But pointer have no such restrictions. Willem, I'm sorry that I did not mentioned that. I simply did not think so far. ;-)

Problem solved. Thank you everyone that responded.

I can think of three distinct ways (and one that is similar to another) of doing what you want.
But first a note on polymorphism.  The HardwareSerial class is itself a child of the Stream class. It's this Stream class that provides all the read/write functionality (it, itself, is a child of the Print class which provides all the print(...) functions).
If all you want to do is print then you should be working with the Print class. if you want to do both reading and writing then the Stream class is what you want. You should only use HardwareSerial if you need to use the Serial-specific functions like .begin(baud).
So with that in mind you could:
1. Assign a pointer
Print *printer;

void setup() {
    Serial.begin(115200);
    Serial1.begin(115200);
    printer = &Serial;
}

void loop() {
    printer = &Serial;
    printer->println(millis());
    delay(100);
    printer = &Serial1;
    printer->println(millis());
    delay(100);
}

This is by far the most efficient method from a purely machine perspective.
Note the use of -> instead of . when calling a function on a pointer.
2a. Use a wrapper function
uint8_t stream = 0;

void printit(const char *text) {
    switch (stream) {
        case 0:
            Serial.print(text);
            break;
        case 1:
            Serial1.print(text);
            break;
    }
}

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

void loop() {
    stream = 0;
    printit("Hello on stream 0\r\n");
    stream = 1;
    printit("Hello on stream 1\r\n");
}

This is less efficient and limits what you can print unless you write lots of overloaded functions.
2b. Use a macro
This is like 2a but uses a macro instead of a function:
#define printit(T) if (stream == 0) Serial.print(T) else Serial1.print(T)

This keeps the standard overloading of the print function but has lots of IF statements littered through your code. A fraction more efficient than 2a since it's all inline. Harder for a human to understand though.
3. Create a wrapper class
This is the rolls-royce method. Everything becomes encapsulated in your own object. Pointers are used to keep it efficient.
class Printer : public Print {
    private:
        Print *stream;
        Print *stream0;
        Print *stream1;
    public:
        Printer(Print &s0, Print &s1) : stream0(&s0), stream1(&s1) {
            stream = &s0;
        }
        size_t write(uint8_t c) {
            return stream->write(c);
        }
        void setStream(uint8_t sno) {
            switch (sno) {
                case 0: stream = stream0; break;
                case 1: stream = stream1; break;
            }
        }
};

Printer printer(Serial, Serial1);

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

void loop() {
    printer.setStream(0);
    printer.println(millis());
    delay(100);
    printer.setStream(1);
    printer.prinln(millis());
    delay(100);
}

With this method the new class could be put into a library and used across your projects.
You also get all the functions you'd normally get with the Serial object when printing (for reading change Print to Stream and implement all the pure virtual functions you need for that class).
And a footnote for all those that say "Why use pointers? Why not references?" I say: I hate references. Pointers are far more obvious what they are. References you can't tell apart from distinct variables. With a pointer you know it's a pointer. References are the spawn of the devil.

This is a complete explanation that clears up the problem. Thank you for your time.


text:
How to upload code to atmega32u4?
I recently created a pcb with the atmega32u4 to use it as a development board. The controller is connected to a micro usb port. Should I install the arduino bootloader instead of the deafult one? Or keep the default boot loader and find another way of flashing hex files? But bottom line what is the process to flash a hex file to the atmega32u4 via usb?

do you want to upload Arduino sketches from Arduino IDE? why do you think there is some bootloader on the 32u4?

I'm pretty sure the 32u4 comes preloaded with a bootloader and yes I would like to use the Arduino IDE. @Juraj

Pull /HWB high and reset the chip - you're now in DFU mode. Use a DFU programmer to upload your code over USB.

@Majenko  As I read it you pull HWBE LOW during RESET not hight.  See page 341 @ https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf

Maybe. I've never done it.

There are four ordering codes for the 32U4.  Three of them come with the DFU bootloader on it; one doesn't.  They also come with and without external oscillator fusing which may be relevant as well depending on how the board is designed and which programming method is used.  You should probably mention which ordering code you have and maybe more about the board.

Installing the Arduino bootloader would make it easier to upload you sketch from the Arduino IDE.
Installing the Arduino bootloader via DFU is probably the easiest method. Alternatively use ISP, but you'd need a programmer for that, or use a separate Arduino board with the ArduinoAsISP sketch running on it.


text:
ESP32 SD writes but doesn't append
I've got a microSD module adapter from the far east, and so far so good, and although it can create files using writeFile, it does not append messages. It returns true, i.e: message appended successfully but when you read the file on the computer or when ESP32 reads on reboot, it's blank.
This is how I call the function:
char* sdFileName = "/v.ea";
if (appendFile(SD, sdFileName, "Heyy")) {
//success
} else {
//failed
}

This is the modified, appendFile function:
bool appendFile(fs::FS &fs, const char * path, const char * message) {
  bool appendSuccess = false;
  if (DEBUG == 1) {
    Serial.print("Appending to the file: ");
    Serial.println(path);
  }
  File file = fs.open(path, FILE_APPEND);
  if (!file) {
    appendSuccess = false;
    if (DEBUG == 1) {
      Serial.println("Failed opening the file.");
    }
  }
  if (file.print(message)) {
    appendSuccess = true;
    if (DEBUG == 1) {
      Serial.println("Appended succesfully.");
    }
  } else {
    appendSuccess = false;
    if (DEBUG == 1) {
      Serial.println("Appending failed.");
    }
  }
  file.close();
  if (appendSuccess) {
    return true;
  } else {
    return false;
  }
}

I've even tried the writeFile function with file.seek(EOF) but no luck.
When calling appendFile for the first time, this appears:
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x17
Appending succesfully.

When the appendFile is called for the second time, this appears in serial monitor:
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x17
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x5
[W][sd_diskio.cpp:149] sdCommand(): token error [17] 0x5
[E][vfs_api.cpp:265] VFSFileImpl(): fopen(/sd/v.ea) failed
Appending failed.

I am using two SPI devices: MFRC522, and before calling SD's functions, I do a digitalWrite(SD_SS, LOW) to "enable" the SD functions till it completes its operations and returns back to HIGH to disable it.
The example in SD(esp32) works fine - writing, appending, deleting, renaming, etc. all work well.

Did you initialize SD with SD.begin()?  How do you handle the MFRC522? You have to disabled it, when the SD reader is active on the SPI bus. Where do you use writeFile? From the code I see, there's is nothing wrong, beside it is too complex. If there is a problem with the code, then you missed to show us the part where the problem is located. When you said the SD(esp32) works fine, do you mean example code for ESP32 where you don't use additional hardware?

@PeterPaulKiefer, yes, it is obvious, otherwise, even the writeFile would fail, and it'd report that SD mount failed first and foremost. Also yes, as I said, when I disable MFRC522, I enable SD, complete operations, then disable SD and enable MFRC522. The problem, as I suspect is in appendFile, as Serial monitor shows the [W] and [E], respectively. And also yes, SD(esp32) from File > Examples works well for all operations.

P.S.: I use writeFile if readFile returns false, that is, when the file does not exist, it invokes writeFile(SD, sdFileName, ""). Specifically, when fs.open(path) returns false, I instruct to create a new file by invoking writeFile.


text:
MFRC522 Communication Failure
I'm using TTGO ESP32 and I've got an MFRC522 from AliExpress.
I've soldered connector pins to the board itself (both for ESP32 and MFRC522) and I'm using jumper wires female-to-female to connect themselves.
However, using an example sketch (DumpInfo) from miguelbalboa's RFID library, it says communication failure and scanning 3 different key cards or the key fob doesn't output anything.
Firmware Version: 0xFF = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?

This is my current pinout scheme:
(MFRC - ESP32)
SDA (SS) -> 33
SCK -> 25
MISO -> 27
MOSI -> 26
RST -> 32

And, of course also GND to G and 3.3V to 3.3V.
I've also tried SDA and SCK to connect to 21 and 22, respectively but no luck.
Though I have a DS1307 RTC module and microSD card adapter module and connected accordingly and it's working fine, by using Dupont wires, with the same method.
A manufacturer's defect or still I'm making an error somewhere?
You can see TTGO's ESP32 pinout diagram and also a picture of MFRC522 here  wired using jumper wires. I may be using (again) the wrong pins. The red LED on the MFRC522 is stable, though.
Thank you in advance.

UPDATE!
The issue has been fixed, just after finding this stackoverflow answer by bat macumba. I'll leave the question here, in case someone stumbles into the same problem.


text:
ESP32 send UDP packets from both cores
Im using AsyncUDP in an ESP32 project, where I initialize AsyncUDP udpSender and call udpSender.write(sendbuffer, sendbuffer_size) from both cores, with different buffers on each core.
One core is continually collecting GY-91 (accel/gyro/magnet) sensor data many times a second and sending it via UDP multiple times a second (after every collection), and the other one is collecting some other data like temperature once a second, as well as responding to commands a server sends.
So I'm basically using one sender on both cores and wondering if this is "thread-safe", if that terminology even applies to this scenario.
Can this cause problems? Is there a specific way this should be done? Like using semaphores?

I don't know if it's thread safe or not. However I would be inclined to play it sage and use a queue and notifications.

Create a queue
Create a "sender" thread that waits for notification then sends anything in the queue through UDP
Create any number of "sensor" threads that place items into the queue then notify the sender thread.


text:
Which board has the highest max current via 3.3v pin?
Is there any arduino board which can deliver 600-800ma via 3.3v pin? Maybe the Arduino due or the nano 33 ble?

Uno Plus 3.3V 800mA https://www.waveshare.com/product/arduino-2/boards-kits/arduino/uno-plus.htm

Yes, that's what i am looking for. Unfortunately, the size of the board is not ideal for my application. The nano 33 ble would be great but i can not find any information about the max current of the 3.3v pin.

why do you mention Due then? it is huge

Yes, you are right. I mentioned it because it can probably deliver around 800ma. https://www.mouser.de/arduino-due/ But I am still hoping there is a smaller board.

yes it can. better source of information is the product page at Arduino. https://store.arduino.cc/arduino-due. but like on all 3.3 V boards the MCU is on this regulator too.

why not just switch the 3.3v input with a mosfet?

Sorry, i am not familiar with mosfets. But in this case I need an extra 3.3v power supply, right?

Your USB will output only 500mA or max to max 1A in some cases. Even if your board is rated for higher output you will be restricted by your source. First step is to increase your source. Secondly check which 3.3V regulator is present on which board and check the datasheet of the regulator to get information about it.
Either ways you can externally add a high current 3.3V regulator and connect it to your 3.3V pin on the arduino. As voltages are equal no current will flow between them.
But remember your source needs to output the higher current first


text:
How to connect MPU6050 with Arduino Uno without using A0-A5 pins?
Connecting MPU6050 with Arduino without using A0-A5 pins.

You could use a Software I2C library, like this one on github, which can be used on almost any pin of a board. But keep in mind, that doing such communication in software imposes some limits (for example the linked library can only be a master). Keeping it in hardware is often the better choice, depending on your requirements.

Thanks. I want to connect 5 flex sensors and MPU6050 to arduino uno and i don't know how to make the circuit and code it. Can you help me.

Have you tried to google the individual parts of your project? That should help you a lot. Depending on your flex sensor, they are either a resitive voltage divider by themselves (in which case they exactly behave like a potentiometer, where you can easily google tons of tutorials) or you need an additional resistor to build a voltage divider. For the MPU: With a quick google I haven't found a library for it, that can directly use Software I2C. Depending on how deep you wanna go: You can create your own library or modify an existing one for the MPU6050 to use SoftwareI2C.

Or you can change your plan: Using an external ADC board for measuring the flex sensors or using a different MPU board, which can for example use SPI (like the MPU6000). Think about how you want to build your project and how much time you wanna invest. You can always come to this site and as a specific question


text:
i want to make Node Mcu a bride for other devices but its self connected with home wifi not providing internet to others
i there!
i have Node Mcu which i want to connected with my home wifi
after it it made it own station mode then i want to make it access point for other
but now problem is that it is now in both mode mean (AP+Station ).
when i want to connect any other phone or Pc  it connected successfully
but not providing internet to other devices.
Question?

is problem in wifi configuration of acess point?
which ip,gate way and subnet mask i would assign to the access point?

I don't understand, how you have configured the Node MCU. Please provide a minimal working sketch, that shows your problem. Gateway and subnet mask have to match the corresponding values of your network, that you connect to. If the gateway isn't correctly set, you won't have internet connection, since the routing won't work

the NodeMcu is not a router. there are attempts to make a router application for esp8266, but not with Arduino

The NodeMCU under the Arduino framework cannot do what you want.  There are basically three methods for what you want:

Configure the IP stack to enable routing - not possible in Arduino, and also requires configuration of your upstream router to work.
Configure the IP stack to enable routing and Network Address Translation - not possible in Arduino, and I am not sure if the stack even supports NAT.
Write a sketch to act as a proxy server - only works for certain types of traffic (HTTP) and requires a lot of coding. May be possible, but not an easy task.

1) and 2) certainly can't be don in Arduino. There are rumours on the internet that it is possible to configure and compile your own lwIP stack version with routing enabled, but that is so far outside the scope of this website.
Option 3 is the more realistic, but certainly not something even I would consider doing. Creating a sketch that works like squid, for example, would be a mammoth task, and may even hit the limitations of the ESP8266.
It would be more beneficial to perhaps get an old wireless router that is supported by OpenWRT and learn how to hack that to act as you want.


text:
Control 4 Grove - RGB LED (WS2813 Mini) color and brightness
I have connected 4 Grove - RGB LED (WS2813 Mini) to D2,D3,D4,D5 on Grove Base Shield V2.0 for Arduino. How can I control the brightness and color of each LED? At the moment I only know to activated one.
Code:
#include "Adafruit_NeoPixel.h"
#define PIN            2
#define NUMPIXELS      1
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  pixels.setBrightness(125);
  pixels.begin();
}

void loop() {
    pixels.setPixelColor(1, pixels.Color(255,255,255));
    pixels.show();
}

Thanks

Here is one of the multiple ways possible to address the problem, Basically, use a for loop and iterate the first parameter setPixelColor function to address all the LEDs. Try experimenting here:
#include "Adafruit_NeoPixel.h"
#define PIN            2
#define NUMPIXELS      4
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  pixels.setBrightness(125);
  pixels.begin();
}

void loop()
{
  pixels.clear(); // Set all pixel colors to 'off'

  // The first NeoPixel in a strand is #0, second is 1, all the way up
  // to the count of pixels minus one.
  for (int i = 0; i < NUMPIXELS; i++) { // For each pixel...

    // pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
    // Here we're using a moderately bright green color:
    pixels.setPixelColor(i, pixels.Color(0, random(0,255), 0));

    pixels.show();   // Send the updated pixel colors to the hardware.

    delay(100); // Pause before next pass through loop
  }
}

here is quick view:

Since you are using NeoPixels, here is a list of simulated examples. you can play with the code and make your own projects online.

Thanks but the simulation is wrong as I have  4 Grove - RGB LED (WS2813 Mini) (https://www.seeedstudio.com/Grove-RGB-LED-WS2813-Mini-p-4269.html ) connected to D2,D3,D4,D5 and I wish to control each one of them separately.

@alirazi And why would you need 4 pins for that? As I see it the WS2813 is just like the standard Neopixels (WS2811 or 12 I think). You can daisy chain them. That way you only need one pin, but you can still control each LED individually.

@chrisl You are right, but I wish to avoid soldering and extra wires.

https://github.com/FastLED/FastLED/wiki/Multiple-Controller-Examples you have a few examples for controlling multiple addressable LEDs


text:
I2C Motor Driver (TB6612FNG) and DC fan error
I running the following code with Seeeduino Cortex M0, DC fan  and Grove - I2C Motor Driver (TB6612FNG) but I get error ,any idea why?
Code:
#include "Grove_Motor_Driver_TB6612FNG.h"
#include <Wire.h>

MotorDriver motor;

void setup()
{
    // join I2C bus (I2Cdev library doesn't do this automatically)
    Wire.begin();
    Serial.begin(9600);
    motor.init();
}

void loop()
{
    // drive 2 dc motors at speed=255, clockwise
    Serial.println("run at speed=255");
    motor.dcMotorRun(MOTOR_CHA, 255);
    delay(1000);

}

Errors:
c:\Users\alirazi\Desktop\libraries\Grove_-_Motor_Driver_TB6612FNG\I2Cdev.cpp: In static member function 'static int8_t I2Cdev::readBytes(uint8_t, uint8_t, uint8_t, uint8_t*, uint16_t)':
c:\Users\alirazi\Desktop\libraries\Grove_-_Motor_Driver_TB6612FNG\I2Cdev.cpp:276:62: error: 'BUFFER_LENGTH' was not declared in this scope
             for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
                                                              ^~~~~~~~~~~~~
c:\Users\alirazi\Desktop\libraries\Grove_-_Motor_Driver_TB6612FNG\I2Cdev.cpp:276:62: note: suggested alternative: 'REG_DSU_LENGTH'
             for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
                                                              ^~~~~~~~~~~~~
                                                              REG_DSU_LENGTH
c:\Users\alirazi\Desktop\libraries\Grove_-_Motor_Driver_TB6612FNG\I2Cdev.cpp: In static member function 'static int8_t I2Cdev::readWords(uint8_t, uint8_t, uint8_t, uint16_t*, uint16_t)':
c:\Users\alirazi\Desktop\libraries\Grove_-_Motor_Driver_TB6612FNG\I2Cdev.cpp:416:70: error: 'BUFFER_LENGTH' was not declared in this scope
             for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
                                                                      ^~~~~~~~~~~~~
c:\Users\alirazi\Desktop\libraries\Grove_-_Motor_Driver_TB6612FNG\I2Cdev.cpp:416:70: note: suggested alternative: 'REG_DSU_LENGTH'
             for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
                                                                      ^~~~~~~~~~~~~
                                                                      REG_DSU_LENGTH

exit status 1

Compilation error: exit status 1

it tells you why on the second line of the error message

This is the example from the Grove - I2C Motor Driver (TB6612FNG) library, any idea how to solve it?
adding #define BUFFER_LENGTH 132 dows not work


text:
"SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope
I recently switched computers and installed Arduino IDE, Added SAMD21 to the boards manager and installed drivers.
My sketch previously ran on my laptop with no problems.  Now when I try to compile for the SAMD21 Mini, I get a 'Serial1' was not declared in this scope error.
If I try to compile it for Mega, there are no problems.
I have tried sample code with Serial1 for SAMD21 and it compiled and uploaded with no problems.

The samd21g serial options are more configurable than for an AVR.  Much of this is left to the variant definition.  So which board do you have selected?

I selected "SparkFun SAMD21 Mini Breakout".  I got it working see below :)

Given that you're now liable to be the only person to answer the question, you may want to just edit the question and answer to make a good read for whomever comes across it in the future.  E.g. the question doesn't mention that you're not working in an .ino file.

Ahhhh, I figured it out.  I had to add #include "Arduino.h" to the .cpp file.


text:
25Q128 flash and garbage data over SPI
I have a logic analyzer coming in the mail, but thought I might ask for help here first.
I soldered the 25Q128 flash onto an adapter and wired it up to an Arduino UNO clone as you can see in the images below. I get nonsense data in the serial monitor. The 4 10k resistors are connected in parallel to GND and there are 4.7k resistors on the SCK, MISO, MOSI and CS lines. I am using the TestFlash sketch from the SPIMemory Arduino library by Marzogh. Could it be a bad soldering joint? Or am I missing something?
I used this as a guide also:
https://www.14core.com/wiring-the-winbond-w25qxx-spi-serial-flash-memory-with-microcontroller/
https://www.14core.com/wp-content/uploads/2017/09/windbond-spi-flash-memory-W25Q80BV-8bit-storage-wiring-guide.jpg
Here are some pictures and a diagram.
Setup
Breadboard
Closeup
Arduino
Fritzing diagram

That "guide" is bad. You don't want any resistors on MISO. Just connect it direct between the Arduino and the chip.

You will be better to buy one of these from aliExpress.

here's de pinout connections to an arduino:

Pin 1 - CS

Pin 2 - D0 (I/O1)

Pin 3 - VCC (I/O2)

Pin 4 - GND

Pin 5 - Di

Pin 6 - CLK

Pin 7 - VCC (I/O)

Pin 8 - VCC

this connection setup does not make use of the full data parallel async I/O, as you can see only I/O1 is connected to D0. This way has much slower data transfers.

what is "pin 1"? Uno TX pin?

CS = chip select

I ask what are the pins on the left. Uno pins? you use the TX pin as CS?

you can use any digital pin for CS


text:
Unexpected and incorrect HEX codes coming from IR remote, but only in second function..?
Hello:) I'm working on a lil project with some NeoPixels being controlled by an IR remote, and with there being multiple strips, I felt it would be best to first select the desired strip, and then the colour. The code is getting there, albiet with a few bugs. I've set the serial monitor up for debugging.
When a strip is selected (I call them 'shift buttons', like on a keyboard), the program and serial monitor detect it flawlessly, every time. However, when I press ONLY a colour button to test the input, a seemingly random, HEX code pops up on the serial monitor which changes with each press. This seems to cause the whole code not to function past selecting a strip.
Would anyone be able to give me a hand as to why this incorrect code might be popping up please? I've tested the function of the buttons on a IR remote testing script and the buttons correlate to the HEX displayed everytime so I know the physical route to the Arduino isn't flawed
TL:DR:
One function with IR information works flawlessly, other function using the same info returns random(?) HEX codes
Below is the code:
#include <IRremote.h> //include IR library
#include <Arduino.h>
#include <FastLED.h> //include LED library
#define NUM_LEDS1 18 //say how many leds is in row 1
#define NUM_LEDS2 17 //say how many leds is in row 2
#define NUM_LEDS3 20 //say how many leds is in row 3
const int RECV_PIN = 8; //say what pin IR sensor is plugged into
const int LEDPIN = 13;//say what pin blue STATUS led is plugged into

IRrecv irrecv(RECV_PIN);
decode_results results;
unsigned long key_value = 0;
int shiftbutton = 0;

CRGB leds1[NUM_LEDS1]; //link leds1 with how many leds are in it
CRGB leds2[NUM_LEDS2]; //link leds2 with how many leds are in it
CRGB leds3[NUM_LEDS3]; //link leds3 with how many leds are in it
size_t NumLeds[3] = { NUM_LEDS1, NUM_LEDS2, NUM_LEDS3 };
CRGB* strips[3] = { leds1, leds2, leds3 };

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

  irrecv.enableIRIn(); //Enables IR
  irrecv.blink13(true); //Flashes onboard LED when IR input detected
  pinMode(LEDPIN, OUTPUT); //set signal led as an ourput
  FastLED.addLeds<NEOPIXEL, 5>(leds1, NUM_LEDS1); //setup for row 1
  FastLED.addLeds<NEOPIXEL, 3>(leds2, NUM_LEDS2); //setup for row 2
  FastLED.addLeds<NEOPIXEL, 6>(leds3, NUM_LEDS3); //setup for row 3
}

void loop()
{
  readIR();
  ShiftButtons();
  LEDStrip();
}

void readIR()
{
  if (irrecv.decode(&results))
  {
    // debug
    Serial.println("processing received IR");
    // if not repeat key
    if (results.value != 0XFFFFFFFF)
    {
      key_value = results.value;

      // debug
      Serial.print("using new value ");
      Serial.println(key_value, HEX);
    }
    else
    {
      // nothing to do
      // key_value still contains the result of the previous read

      // debug
      Serial.print("using old value ");
      Serial.println(key_value, HEX);
    }
    irrecv.resume();
  }
}

void ShiftButtons()
{
  switch (key_value)
  {
    case 0xFF30CF:
      shiftbutton = 1;
      break;
    case 0xFFB04F:
      shiftbutton = 2;
      break;
    case 0xFF708F:
      shiftbutton = 3;
      break;
  }

  // debug
  Serial.print("shiftbutton set to ");
  Serial.println(shiftbutton);
}

void setStrip (size_t index, CRGB color)
{
  fill_solid(strips[index], NumLeds[index], color);
  FastLED.show();
}

void LEDStrip()
{
  if (shiftbutton == 0) return; // no strip selected

  // debug
  Serial.print("LEDStrip: using key value ");
  Serial.println(key_value, HEX);

  CRGB color = CRGB::Black;
  switch (key_value)
  {
    case 0xFF1AE5:
      color = CRGB::Red;
      // debug
      Serial.println("color set to red");
      break;
    case 0xFF9A65:
      color = CRGB::Green;
      // debug
      Serial.println("color set to green");
      break;
    case 0xFFA25D:
      color = CRGB::Blue;
      // debug
      Serial.println("color set to blue");
      break;
  }

  setStrip(shiftbutton - 1, color);
  shiftbutton = 0;  // reset the flag
}

Hopefully I’ve attached that code right!
Thanks

What are you getting in decode_type of the results?

do the LEDs shine onto the IR sensor?

19:44:59.050 -> LEDStrip: using key value FF30CF//meaning  (shift selected)
19:44:59.050 -> processing received IR//red pressed here
19:44:59.096 -> using new value 5A9FB1CA //picks up this or many other random codes
19:44:59.096 -> shiftbutton set to 0//resets shift select button even though successful colour hasn’t been selected

Also, no light shines directly into the sensor - it is working flawlessly when only the buttons to select strips are pressed, however when colours are introduced random numbers in the serial monitor start appearing instead of the set colour codes. Thanks

I would say, this code can not work at all. You read a value from the IR, then you check for "shiftbutton pressed" (1-3). In the next function you skip if no shiftbutton is pressed or you use the same key_value to select the color. But this is still the code for one of the shiftbuttons; not a color code.  So it would not match. Then the shifbutton is reset to 0. You allready have pressed the color key which might be in a queue. The loop starts from the beginning. Now (much too late) the color key is read. It does not match a shift button; shiftbutton stays with 0. And so on

But why the random values? Perhaps there is a unwanted shift when the bytes are tranfered induced by delayed reading. You could simply write a little test program. Use only the readIR method, but delete the else block (that would print too much output ;-) ). Then press the keys on the sender and see if the values are still random. Do you press the shift and color keys one after another or at the same time? (As a shift key would be suspected).


text:
Controlling lights by XBee S1+ ESP32 without bridge
I need some help with my ideas please, I have a smart home system and I am trying to control the Philips hue light but without the bridge.
I want to do that by XBee S1 + FURTHER ESP 32.
so, who did that or have any ideas about how that can possible.
Any links, Videos, tutorials will be greater.
thanks all.

do Phillips Hue lights use XBee modules for communication?

For Now, I am using the bridge but I want to control them XBee to turn it off/on. the system is not in my home I am working on it.  so what I want to do turn off the bridge and control the lights from the XBee ,    as I saw from the internet I can do that with the transport key of the light + XCTU software +xbee S1. but I am lost I don't know how to start.


text:
How to close/end a Wire.begin()?
I have an ESP32 cam, and I attached an i2c light sensor to it. I need to read the light level at startup, then I don't need the i2c connection again.
The problem is, the board uses 2 i2c connections I think (for the camera and such). So I use my custom pins for the sensor (15 and 16). It works well, I can read the light just fine, but then the camera fails because (I believe) the Wire.begin(15,16) changes the default pins and the camera gets confused.
So I would like to do something like Wire.end() to forget that I started the Wire.begin(). Any idea on how I can do that?
Here is the relevant code:
#define I2C_SDA 16
#define I2C_SCL 15
BH1750 lightMeter (0x23);
TwoWire I2Clightmeter= TwoWire(1);

void setup()
{
  I2Clightmeter.begin(I2C_SDA, I2C_SCL);
  lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,&I2Clightmeter);

  delay(1000);
  uint16_t lux = lightMeter.readLightLevel();

//rest of the code

Have you tried Wire.end()?

Yes, of course. But there is no such function.

Looks like that's something Arduino overlooked. It's something we (optionally) implemented in chipKIT...  There is a way though, but it's not too fun.

This is the esp32 header for wire: https://github.com/espressif/arduino-esp32/blob/master/libraries/Wire/src/Wire.h If there is a way, I'd like to know it, because I can't use the camera without it :/

I just tried to reproduce this, but since I don't have a BH1750, I just ran the solution #1 from the answer below without anything attached and it does not crash for me. So maybe the bug is not in the wire library but in the lightmeter library (as it may register some interrupts). Try dynamically allocating that one as well.

Thanks for the effort. The program doesn't require a physical board, or even actually using the library. Just starting a  I2Clightmeter.begin(I2C_SDA, I2C_SCL); is enough to crash when the camera is initialized. However, I found a solution: moving SDA on pin 14 seems to work.

There is a way of doing it that's ESP32 specific. However it means changing how you define your I2C object.
The ESP32 system is set up so that if the TwoWire instance is destructed the I2C bus is released. But you can't do that with the way you normally define the object. So instead you have to use dynamic allocation to control it:
TwoWire *I2Clightmeter;

void setup() {
    I2Clightmeter = new TwoWire(1);
    I2Clightmeter->begin(I2C_SDA, I2C_SCL);
    lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,I2Clightmeter);
    delay(1000);
    uint16_t lux = lightMeter.readLightLevel();
    delete I2Clightmeter;
    // rest of code
}

Another alternative is to keep the TwoWire object in a local scope so that it gets destroyed when you leave that scope - maybe with a special function for it:

uint16_t getLux() {
    TwoWire I2Clightmeter(1);
    I2Clightmeter.begin(I2C_SDA, I2C_SCL);
    lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,&I2Clightmeter);
    delay(1000);
    return lightMeter.readLightLevel();
}

void setup() {
    uint16_t lux = getLux();
    // rest of code
}

Thanks, but unfortunately it doesn't work. If I put the delete there, it just boot loops. If I don't put the delete, it gives me the message as it did before: [W][esp32-hal-i2c.c:905] i2c_isr_handler_default(): eject raw=0x2, int=0x200

Did you try the second option? Localise it?

I didn't try it, but I don't see how it would work, since most likely once the function is called in c (on the esp32 specific code) it will set something that persists there until the device is rebooted or some other magic thing happens to reset it. Btw, the camera code does NOT use wire() in my program. It is used by the libraries in the backend. The only i2c code in my program is reading the light sensor.

It's worth trying. Give it a go and report back.

Another option is just to use the other i2c channel, and maybe other pins too.

Trying the first channel was one of the first things I tried. Unfortunately, it still crashed.

I tried the scope version, and, unsurprisingly, it got stuck in a bootloop too...

Hmm... then I am out of ideas at the moment, sorry. Maybe raise it as an issue on the github repo - it really shouldn't cause it to crash.

Thanks for your effort, I appreciate it. I asked on the esp32.com forum, if I don't get an answer there too I will open an issue on github as well.

Btw, from looking at the code, deleting the object should release the i2c. Unfortunately, something else is going on :/ TwoWire::~TwoWire()
{
flush();
if(i2c) {
i2cRelease(i2c);
i2c=NULL;
}
}

Yes, that's where I got the idea of destroying the object from. Maybe the problem isn't with the I2C - maybe the problem is with the camera code. I know you probably don't get much control over that though as it's mostly embedded in the core.

Ok, I solved the problem. I moved SDA on pin 14, and now it works, for some reason :D I believe it's still a bug with esp-32 cam, but at least I got it to work.


text:
two adafruit neopixel loops
i'm making a device that's kind of based on Russian roulette.
I have 5 LED's  that are normally  white, and when you press the button one of the LED's is marked red.
After some tinkering I figured out how to do this with  the help of adafruit neopixel, but i also want to have a RGB strip with a rainbow effect running on the same arduino at the same time (or only just before the button is pressed).
The problem is that it interferes with the activation and running of my  Russian roulette.
I know you can't run two loops at a time, but is there some kind of way to solve this?
I will put my code below, thanks in advance!
#include <Adafruit_NeoPixel.h>

const int buttonPin = 2;

int buttonState = 0;

#define LED_PIN  6

#define LED_COUNT 5

#define LED_PIN2  7

#define LED_COUNT2 60

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2(LED_COUNT2, LED_PIN2, NEO_RGBW + NEO_KHZ800);

uint32_t wit = strip.Color(255, 255, 255);
uint32_t wit2 = strip2.Color(255, 255, 255);

void setup() {

  randomSeed(analogRead(0));
  strip.begin();
  strip.show();
  strip.setBrightness(255);
  strip2.begin();
  strip2.show();
  strip2.setBrightness(255);
  pinMode(buttonPin, INPUT);

}

void loop() {
    rainbow(10);
    shotknop();
}

void shotknop (){
  buttonState = digitalRead(buttonPin);
    strip.fill(wit, 0, LED_COUNT);
    strip.show();
    if (buttonState == HIGH) {
    theaterChase(strip.Color(255, 255, 255), 150);
    shot(strip.Color(0, 255, 0), 100, 5000, 0);
    }
    else{
      }
}

void shot (uint32_t color, int wait1, int wait2, int rng) {
    strip.clear();
    rng = random(LED_COUNT);
    for(int a=0; a<15; a++) {
      strip.setPixelColor(rng, color);
      strip.show();
      delay(wait1);
      strip.setPixelColor(rng, (0, 0, 0));
      strip.show();
      delay(wait1);
  }
    strip.setPixelColor(rng, color);
    strip.show();
    delay(wait2);
}
void colorWipe(uint32_t color, int wait) {
  for(int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
    strip.show();
    delay(wait);
  }
}
void theaterChase(uint32_t color, int wait) {
  for(int a=0; a<10; a++) {
    for(int b=0; b<3; b++) {
      strip.clear();

      for(int c=b; c<strip.numPixels(); c += 3) {
        strip.setPixelColor(c, color);
      }
      strip.show();
      delay(wait);
    }
  }
}
void rainbow(int wait) {
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip2.numPixels(); i++) {
      int pixelHue = firstPixelHue + (i * 65536L / strip2.numPixels());
      strip2.setPixelColor(i, strip2.gamma32(strip2.ColorHSV(pixelHue)));
    }
    strip2.show();
    delay(wait);
  }
}

You should ditch every call to delay() in your code and learn how to use a non-blocking coding style involvingthe millis() function, just like in the BlinkWithoutDelay example. That will enable you to not do busy waiting, bit do multitasking by very rapidly switching between the two tasks. There are tons of tutorials about that on the web. Please look at some of them. Then - if it isn't clear - you can always come back here. Have fun with your projekt :-)

Yep, ditch all delay(). Daisy chain 2 loops so you have 1 big loop. Write a drawing function update 2 loops at one time following global array that stores colour info of all each single LED on both loops. Setup a timer to call your drawing function every ~40ms. In main loop(), do the fancy stuff by modify the global array (screen buffer). Also check for buttons and  stuffs there in main loop. Since you separate your logic code (in main loop) and visual code (run by timer), you can do delay() in main loop.


text:
Running a robot with 2 front-facing sensors, but it's stuttering
Here's the run down: I have a small robot with four continuous servo motors and two ultrasonic sensors. It's run by and UNO board with a Sensor Shield V5 on top.
My goal is to program the front right and front left sensors to both be returning distances in inches, and have the robot turn in the direction with the most room when one of the sensors returns a distance less than some minimum.
I am very confident that the motors and sensors aren't the issue, as testing them by themselves shows no issues. However, when I run the below code the robot stutters, mainly just going backwards but stuttering forwards and occasionally turning for a second or two. Any ideas what's going on?
#include <Servo.h>

Servo FL;
Servo FR;
Servo BL;
Servo BR;

const int FRecho = 11;
const int FRtrig = 10;
const int FLecho = 9;
const int FLtrig = 8;

long durationFL;
long durationFR;
int distanceInchR = 24;
int distanceCmR;
int distanceInchL = 24;
int distanceCmL;

const int minDistanceInch = 18;
const int minDistanceCm;

enum movementStates {
 STILL,
 FORWARD,
 BACK,
 TURNFR,
 TURNFL,
 NOTHING
};

enum movementStates movement;

void setup() {

  FL.attach(4);
  FR.attach(5);
  BL.attach(6);
  BR.attach(7);

  pinMode(FRtrig, OUTPUT);
  pinMode(FRecho, INPUT);
 pinMode(FLtrig, OUTPUT);
  pinMode(FLecho, INPUT);

  movement = NOTHING;

  forward();

}

void loop() {

updateDistanceFL();
updateDistanceFR();

updateDirection();

}

void forward () {
  FL.write(180);
  FR.write(0);
  BL.write(180);
  BR.write(0);
  movement = FORWARD;
}

void turnFR () {
  FL.write(180);
  FR.write(180);
  BL.write(180);
  BR.write(180);
  movement = TURNFR;
}

void turnFL () {
  FL.write(0);
  FR.write(0);
  BL.write(0);
  BR.write(0);
  movement = TURNFL;
}

void backUp () {
  FL.write(0);
  FR.write(180);
  BL.write(0);
  BR.write(180);
  movement = BACK;
}

void still () {
  FL.write(90);
  FR.write(90);
  BL.write(90);
  BR.write(90);
  movement = STILL;
}

void updateDirection() {

  if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
    if (movement != BACK) {
      backUp();
    }
    else if (distanceInchR < minDistanceInch) {
     if (movement != TURNFL) {
      turnFL();
     }
    }
    else if (distanceInchL < minDistanceInch) {
     if (movement != TURNFR) {
      turnFR();
     }
    }
    else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch)
    if (movement != FORWARD) {
      forward();
    }
  }
    else {
      if (movement != STILL) {
        still();
      }
    }
}

void updateDistanceFR(){
digitalWrite(FRtrig, LOW);
delayMicroseconds(2);
digitalWrite(FRtrig, HIGH);
delayMicroseconds(10);
digitalWrite(FRtrig, LOW);
durationFR = pulseIn(FRecho, HIGH);
distanceCmR= durationFR*0.034/2;
distanceInchR = durationFR*0.0133/2;
  }

void updateDistanceFL(){
digitalWrite(FLtrig, LOW);
delayMicroseconds(2);
digitalWrite(FLtrig, HIGH);
delayMicroseconds(10);
digitalWrite(FLtrig, LOW);
durationFL = pulseIn(FLecho, HIGH);
distanceCmL= durationFL*0.034/2;
distanceInchL = durationFL*0.0133/2;
  }

the updateDirection() function contains a bunch of redundant logic tests ... it may not be doing what you expect it to do

Add a delay() in your loop(), your code is too busy checking and update the direction constantly without the time for the motor to move in any direction. Add a status variable to hold the current direction status, if the direction remain the same, there is no need to run updateDirection() again and again.

your updateDirection logic doesn't quite work the way you think it does.
after a bit of code formatting and comments it looks like this:
void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        } else if (distanceInchR < minDistanceInch) {
            //always entered if movement == BACK
            if (movement != TURNFL) {
                turnFL();
            }
        } else if (distanceInchL < minDistanceInch) {
            //never entered
            if (movement != TURNFR) {
                turnFR();
            }
        } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch)
            //never entered
            if (movement != FORWARD) {
                forward();
            }
        //endif distanceInchR < minDistanceInch && distanceInchL < minDistanceInch
    } else {
        // entered when distanceInchR > minDistanceInch || distanceInchL > minDistanceInch
        if (movement != STILL) {
            still();
        }
    }
}

it looks like you had a missing closing brace around the first condition. Causing the only movement functions that get called to be backUp, turnFL and still.
If we add the missing braces then it looks much better:
void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        }
    } else if (distanceInchR < minDistanceInch) {
        if (movement != TURNFL) {
            turnFL();
        }
    } else if (distanceInchL < minDistanceInch) {
        if (movement != TURNFR) {
            turnFR();
        }
    } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch) {
        if (movement != FORWARD) {
            forward();
        }
    } else {
        if (movement != STILL) {
            still();
        }
    }
}


text:
Voltage at AREF pin
I find difficulties to measure correctly the voltage at the AREF pin.
I would measure voltages with a resolution not exceeding 1 mV . nda voltage divider
In one of my trials, I was using a  9V battery and a voltage divider made with a 1k resistor and a 2k one.

The battery voltage was about 8890 mV and the reference voltage was about 2960 mV (confirmed by a multimeter).
I  connected the output of the divider to the AREF pin of an Arduino Uno board. The output voltage value dropped to about 1800 mV. Reading the voltage value at AREF pin with a simple sketch:.

the serial monitor printed:

as if the voltage dividere did not exist.
What am I doing wrong? or what I don’t understand?
Thank you for your attention.

analogRead(EXTERNAL)? EXTERNAL s 0. you read A0

On the AREF pin you provide a reference voltage that is compared with the voltage you will measure on the Ax pins. AREF is not a Ax pin. You can not measure it directly with analogRead(EXTERNAL)  but you can connect AREF to e.g A0. But as VREF is the reference you compare A0 with the result would always be 1023. The Voltage you measured on the VREF pin is lower than  you measured on the unconnected voltage divider because VREF has a low impedance and changes the  voltage divider.

One solution to stabilize the voltage divider is to use a Zener diode with a reverse breakdown voltage of 3V (or what ever you need for AREF) instead of the R2 resistor. The arrow/triangle of the Z-Diode  must face towards the R1. You can not measure the AREF with the same Arduino because AREF is the reference of the measurement, its result would always be 1023, if you measure the reference itselfe .

You could also build a stabilized voltage source with a LM317. And you should consider using the 5V of the Arduino to create the reference voltage from. (As long as you need about 3V that's no problem). Then you get rid of the 9v batterie.

Very clear and detailed. Thanks.Paolo

I was using a 9V battery and a voltage divider made with a 1k resistor and a 2k one.

Using a battery is not a good way of getting a stable voltage. A battery's voltage will change over time.
Using a voltage divider is not a good way of generating a reliable stable voltage. The output impedance is very high and will be affected by any loading you apply to it causing it to droop.
If you want 1mV per LSB then you need a 1024mV voltage reference (since there are 10 bits of resolution, or 1024 possible divisions, in the ADC). For that you want a 1024mV voltage reference, which is a standard value for precision voltage reference chips such as the LM4140CCM-1.0/NOPB from Texas Instruments. Personally I like to use a precision DAC like the MCP4821 to provide a settable analog reference voltage.

Reading the voltage value at AREF pin with a simple sketch the serial monitor printed 8890 as if the voltage dividere did not exist. What am I doing wrong?

You cannot read anything from the AREF pin. It is merely a voltage reference, not an active pin you can read. When you use analogRead(EXTERNAL) you are actually doing analogRead(0) since EXTERNAL is a macro that expands to 0. That means you are really reading from pin A0 not the AREF pin.  And then you just map that to 8890 when it's at maximum anyway. Since A0 is (probably, since you don't show anything else in your circuit) floating it will most likely be above the voltage you are feeding in to AREF and will return 1023 all the time anyway.


text:
Arduino Mega Clone CH340G Capacitor Values
I'm making my own Arduino Mega board with ATmega2560-16AU and CH340G. Jump to the end of the post to find the real question.
I have already ordered a PCB before and it didn't work when I soldered everything in place. I have already asked why that board didn't work on another post here: Programming custom Arduino Mega with Arduino Uno
But I was not satisfied with the answers and started suspecting whether or not the capacitor values were right on my board.
I'm trying to make my own version of RobotDyn's Arduino Mega 2560 Pro so I tried taking the already programmed ch340g and soldering it on my own board and still failed. When I put a previously not programmed ch340g on the RobotDyn board and programmed it using Arduino UNO (Arduino as ISP) the board would work.
So now I ordered a new PCB but haven't ordered any of the passive components yet.
If any of you could tell me where I could find the values from the schematic below I would really appreciate that.
https://robotdyn.com/pub/media/0G-00005641==MEGA-PRO-CH340GATmega2560/DOCS/Schematic==0G-00005641==MEGA-PRO-CH340GATmega2560.pdf

Most capacitors are decoupling capacitors, so 100nF. C1 is from the original Arduino schematic - also 100nF. As is C12. All the others depend on the components they are supporting - the load capacitance of the crystals, the required input and output capacitance for the voltage regulators, etc.

Just a dumb question, the processor chip is programmed with the bootloader?

@Majenko Oh yeah sorry forgot to tell about the regulators, I don't need the values for that but I believe I'm having trouble with CH340G capacitors.

@Dorian Uhhh.. yeah. I want to be able to program my Arduino via USB so I have CH340G there to translate the program to the MCU.

C3/4 are dependent on whatever crystal you're using. C2 is for the internal 3.3V regulator in the Ch340G. No idea what it needs, but probably 1uF is more than adequate.

The values can be easy found for generic CH340g and ATmega2560 implementations:
C1,C2 = 100nF, C3,C4 = 22pf but depends on the crystal you use, all others excepting C12 are decoupling capacitors.
C12 has no sense where it's placed, it seems that the schematic is a bad combination of schematics, this capacitor should reset the board at power on but it breaks the reset pulse from CH340g so you cannot program the board without pressing manually the reset pushbutton. Don't place C12 at all.
Also place a short instead of R5 and R6 that are not in the CH340g manual (there is a special mention to connect the pins straight to USB bus), remove R8, is not needed for the same reason, R3 makes no sense, don't place-it.
R2,R4 = 1K, R7,R9 = 10K, R10,R11,R12,R13 = 1K, R14 = 10K , R15 = 1M.
Y1 = 12Mhz, Y2 = 16Mhz
A 22 ohm resistor is missing in your schematic between Y2 XTAL1 and ATMEGA XTAL2 but I don't think it's important.
I hope I didn't missed something
The bare minimum is to remove c12 and maybe R3 and check the values you used for R2, R4 against the above values.
If something would be wrong with CH340g the USB connection would fail but I see no mention about that in your post.

"C4 has no sense where it's placed".  I'm guessing you didn't mean C4 there, because you mention C4 above that point.  So, perhaps C5?.  But it is connected to AREF (for decoupling) rather than RESET.  Anyway, something for you to check.

@timemage you're right, sorry, it's C12. Fixed.

I think the  "all others excepting C4" may be caught up in that as well.  Referring to C12 as well?  Regarding C12, you can see it represented in AVR042 figure 3-1, along with the reason for it a few paragraphs above.  That said, it's probably not needed here.

@timemage Yes, missed that to. Yes, it's a combination of some schematics,  in the AVR042 the reset line is not driven by another chip. The spike through C1 that should reset the chip to enter in botloader mode when programming is filtered by C12 and the programming fails.

Scratching my above comment.  You're right, it likely is counter-productive to have it there.  Before, I'd throught the pulse might make it through okay.  But, assuming two caps around equal value, the pulse will stop quite short of being adequate for reset.

@timemage  Not only short  but also half size because the pulse voltage will be divided between capacitors. At best would be 2.5V. As I know the Reset input has histeresis and needs more than half VDD to activate.

We're in violent agreement.


text:
Where to define web server callback functions so they can access server object? (ESP8266WebServer library)
I want my ESP8266-based device to create an accesspoint that allows the user to input their home ssid and password. There is a device object that holds most of the data defined elsewhere.
I'm trying to use the ESP8266WebServer library. It requires me to define parameterless callback functions. Where should I declare and define these callback functions so that they can access the server object? In all the example code, the server object is global. I'd want to avoid that, and I'd also like to avoid having a server object as a permanent Device class member.
How should I go about this? It is not allowed to define the callback functions inside Device::getWifiCredentials, and if I declare them outside then server isn't in scope.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {

    ESP8266WebServer server(80);
    server.begin();

    // define callbacks
    server.on("/", handleRoot); // initial page

    server.on("/ssid", handleCredentials); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

    while( WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(500);
    }

    return ACTION_SUCCESSFUL;

}

// **Where can these functions be defined to allow them to access the server object?**

void handleRoot() {
};

void handleCredentials() {

    String ssid;
    String pw;

    if( server.hasArg() ){
        ssid = server.arg("ssid");
        pw = server.arg("pw");
    }
};

"It is not allowed to define the callback functions inside Device::getWifiCredentials", it can be done with an anonymous function like server.on("/ssid", []() { }.

i would move ESP8266WebServer server(80); to the 4th line; outside any function. I think you might need to call on() before begin() as well, just once, like in setup(), at least that's how mine works.

put your server declaraition outside the constructor and call a class callback :
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {
server.begin();

    // define callbacks
    server.on("/", std::bind(&Device::handleRoot, this); // initial page

    server.on("/ssid", std::bind(&Device::handleCredentials, this); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

    while( WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(500);
    }

    return ACTION_SUCCESSFUL;
}


text:
analogReference(INTERNAL) configuration
I need some help because I did not understand the configuration analogReference(INTERNAL).
I would measure the intensity of a Laser beam passing through a filter. This is the circuit I would implement, using the 3.3 V power supply:

In order to rise up the resolution of the system, I would use the 1.1 V power supply (Arduino Uno) to feed the sensor, keeping the Laser power supply at 5 V. In the analogReference(EXTERNAL) configuration shown in the schematic, the sensor is powered by the 3V3 pin, which is connected to the AREF pin. How should I change the circuit in analogReference(INTERNAL) configuration?

What exactly is the sensor?

If you use the internal reference voltage, you must remove the wire from 3.3v to AREF. So it's not connected to anything.

Changing the analog reference does not change the resolution.  All it does is change the measurement range. It compresses the existing resolution into a smaller voltage range.
If you then compress the voltage range of your signal in the same way to fit into the now compressed analog reference voltage range (for example by reducing the supply voltage to 1.1V) you end up achieving absolutely nothing.
The only time you would use the 1.1V internal reference is if your incoming signal is already between 0V and 1.1V and you would otherwise be wasting the resolution above the highest voltage the sensor gives out.


text:
Arduino IDE on eOS? Java?
Tried to install Arduino IDE on Juno, install script gave warnings about icons not being installed on desktop (which is fine since no desktop folder for eOS) but then when try to launch the IDE icon from Applications it doesn't go. I'm guessing it's a java app? I don't want to run java on eOS unless it's already there. Any insight to running this IDE on Juno would be welcome.

Yes, the Arduino IDE is java, so you need java to run it. You could try to use arduino-cli (commandline tool to compile and upload code to Arduinos). It seems to be written in go

"it doesn't go" is not a good problem description. Have you tried running the Arduino IDE from a terminal and watch, if errors are displayed there? If yes, these errors belong into the question.

I'd be fine w just coding and compiling. Am obv new so didn't know IDE had a cli (sounds counterintuitive). Doesn't go means I click the icon and app doesn't launch. Am setting this all up for the first time so be kind. For now am able to download hex files to the hardware, so am going to backstep and try hand compiling some code via gcc. Not a fan of java so prob isn't on my system by default. No other IDE option?

The CLI is not part of the IDE. It's an extra program. For the case, that you want to stay in the Arduino Framework without much configuration. You can use any C++ IDE to write the sketches as ino files. Then you can execute the compilation and uploading over the CLI. Another option would be Atmel Studio, though I think you need to configure it to use the Arduino framework (google might help you there. Haven't done that myself).

version for what platform did you download? Linux 64-bit?  To what folder did you unpack the installation? The IDE has Java bundled. The install.sh only creates a desktop icon, nothing else.

@Navin eOS is "Elementary OS" - a premium version of Linux.  "Juno" is a release name for the current version. There's no network switch involved. I think you may be getting muddled up with Juniper.

@Majenko thank you, I did get it muddled up with Juniper Junos


text:
Problems with detecting button digital state
I am trying to start an event after pressing and holding the FLASH built-in Nodemcu button for a specific time, I wrote two functions, one for debouncing and detecting the state, the other is to detect the pressing time, I'm not getting any result unless I decrease the input pressing time to less than 1s, which makes the button works as a single-push button, I think i have a problem with debouncing the button, I can't figure out where it is?
/**
* @brief debounces the button and returns the current level high or low
*
* @return int the button state 0: low, 1: high, -1 indetermined
*/
int button_state(int btn)
{
    int const DEBOUNCE = 200;
    static int hi = DEBOUNCE;
    static int lo = 0;
    if (digitalRead(buttonPin[btn]))
    {
        if (hi < DEBOUNCE)
        {
            hi++;
        }
        if (lo > 0)
        {
            lo--;
        }
    }
    else
    {
        if (lo < DEBOUNCE)
        {
            lo++;
        }
        if (hi > 0)
        {
            hi--;
        }
    }

    if (hi == DEBOUNCE)
    {
        return 1;
    }
    else if (lo == DEBOUNCE)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}
/**
 * @brief Detects the button state and starts a time to calculate pressing duration
 *
 * @param btn input button pin
 * @param PressTime Desired pressing duration to compare to
 * @return int returns 1 when PressTime is reached
 */
int PressNHold(int btn, int PressTime)
{
    int lastButtonState = 0, Startpressed = 0, endPressed = 0, holdTime = 0,
    buttonState = button_state(btn);
    if(buttonState != -1)
    {
        if (buttonState != lastButtonState)
        {
            if (buttonState == 1)
            {
                Startpressed = millis();
            }
            else
            {
                endPressed = millis();
                holdTime = endPressed - Startpressed;
                if (holdTime >= PressTime)
                {
                    Serial.printf("Button %d pressed for %ds or more\n", btn, holdTime);
                    holdTime = 0;
                    return 1;
                }
            }
        }
    }
    lastButtonState = buttonState;
}
.....

void loop {

if (PressNHold(buttonPin[1], 5 * 1000) == 1)
  {
   //launch your event
  }

I don’t follow your debounce routine.  It is very unorthodox.  Perhaps it would do some good to study some other existing debounce code and write something that we know works.

the debounce code looks like it should work .... it would be easier to read if the if statements were one-liners .... replace the PressNHold code to just print a timestamp at button transitions ... that may help narrow down the area of failure

Does your button have a pulldown resistor?

turns out that it is very simple, I shouldn't put buttonPin[1] a variable for PressNHold, I had to put just1, buttonPin was used already in button_state, also, PressnHold local variables should be declared static to not get a reset after function execution.


text:
Unable to send UDP packets while performing OTA update on the esp8266
I am sending specific UDP packets with my esp8266 every 5s, I have added an OTA update command, and added the update_progress callback aiming to send it back to my laptop, using a serial terminal I noticed that regular packets, as well as the progress packet, are not sent during the update, everything gets back after. Is the esp able to send and receive packets simultaneously?, is there any interference or the OTA update process causes an interruption?
Hardware: ESP8266MOD Nodemcu
Software: VS code with portable Arduino 1.8.9, espcore 2.6.3

esp8266 ArduinoOTA library has
  WiFiUDP::stopAll();
  WiFiClient::stopAll();

to ensure undisturbed OTA upload

Any way to trick it to enable UDP, or sweep between TCP(for OTA) and UDP, I am using the ESP8266httpUpdate library and it disables all wifi clients except TCP, commenting that section did nothing

@AlaeddineSalem, you can try to remove the lines from the library


text:
#define from main (.ino) not considered by comiler in own libaries
I have got the problem, that my #define from main (.ino) is not considered by the comiler in my own libaries. This #define MQTT_MODULE is only considered in the main (.ino) programm, but not in MyRemoteLib.cpp
This example works normally, if I compile it with gcc.
Code in my Test.ino :
#define         MQTT_MODULE             1
#include        "MyRemoteLib.h"
loop() {
  my_test() ;
}

Code in MyRemoteLib.h
#define     MYREMOTELIB_H
#define     MY_TEST         1
#if         MQTT_MODULE
  #define       MQTT_MOD_R              1
#endif

Code in MyRemoteLib.cpp :
#include        "MyRemoteLib.h"
void my_test() {
  #if   MQTT_MOD_R
      test.... > nothing -> ignored by compiler
  #endif
  #if   MQTT_MODULE
      test.... > nothing -> ignored by compiler
  #endif
  #if   MYTEST
      test.... > error-> not ignored by compiler
  #endif
}

Your approach of using #define to selectively include different parts of your library is doomed to fail, because it does not work that way. You might want to learn more how to build a "real" library. In a tiny nutshell, separate all parts in their own source. When the linker resolves references, it will only add the needed modules. However, if this is doable with the Arduino IDE, is another issue.

This is the expected behavior. The library and the main program are two
different compilation units: there are processed by the compiler
separately.
In the main program, the inclusion of the header file yields this:
#define         MQTT_MODULE             1
// Included from MyRemoteLib.h:
#define     MYREMOTELIB_H
#define     MY_TEST         1
#if         MQTT_MODULE
  #define       MQTT_MOD_R              1
#endif
// end of included code
loop() {
  my_test() ;
}

The remaining preprocessor code has no effect at all.
In the library, the same inclusion yields this:
// Included from MyRemoteLib.h:
#define     MYREMOTELIB_H
#define     MY_TEST         1
#if         MQTT_MODULE
  #define       MQTT_MOD_R              1
#endif
// end of included code
void my_test() {
  #if   MQTT_MOD_R
      test.... > nothing -> ignored by compiler
  #endif
  #if   MQTT_MODULE
      test.... > nothing -> ignored by compiler
  #endif
  #if   MYTEST
      test.... > error-> not ignored by compiler
  #endif
}

The conditional compilation gives an empty my_test() (that is, unless
by MYTEST you actually mean MY_TEST).
I do not know what you are trying to achieve, but you may look at ways
to put the code to be conditionally compiled in the header itself. You
may try using inline functions, or maybe templates.
Edit: about removing code using conditional compilation: this is not
always as useful as it may sound, for two reasons.

By default, the Arduino IDE compiles your code with the options
-ffunction-sections and -fdata-sections, and links it with
-Wl,--gc-sections. This means that any function or method that is
never used, or any global variable that is never referenced, is not
included in the final executable.

The code is also compiled with -flto, which enables link-time
(full program) optimizations. This means that code that depends
on a condition that is always false (the conditional expression can
be resolved as a compile-time constant) is also removed from the
final executable.

Thanks for the answer. Well I try to achieve a universal code in my own library's so I can "activate" a "Module" in my main program. And I thought the pre-processer is the best ways, so it even won't be complied (if I don't need it). For example, some sensor functions should only send mqtt msg if I activate my "wifi module"... otherwise the compiler also complains!
That's why I prefer to use #defines. Also if I use the "normal" gcc compiler it works.

@stevo Some of this is probably intended as a comment on Edgar Bonet's answer and some of it may be something that's supposed to be edited into the question. Careful that you don't edit the question out from underneath the existing answer. This is not a forum. The way it's supposed to work is that there are questions with matching answers. Not a forum thread.

@stevo I doubt that your "normal" gcc works differently and "sees" the #define in the source of another translation unit. BTW, the compiler used by the Arduino IDE is a gcc, too.


text:
Fresh install getting Assembler Error
I am using Raspberry Pi 4 to connect via usb to program ardino Nano, I intend to communicate with the nano via i2c, but this is irrelivant.
With a fresh install of Arduino for ARM 32 bit I get this error when tring to compile a default (fresh) script:
Arduino: 1.8.13 (Linux), Board: "Arduino Nano, ATmega328P"

/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/arduino-builder -dump-prefs -logger=machine -hardware /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/tools-builder -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -built-in-libraries /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10813 -build-path /tmp/arduino_build_228832 -warnings=none -build-cache /tmp/arduino_cache_202507 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -verbose /tmp/untitled1895295462.tmp/sketch_feb16a/sketch_feb16a.ino
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/arduino-builder -compile -logger=machine -hardware /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/tools-builder -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -built-in-libraries /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10813 -build-path /tmp/arduino_build_228832 -warnings=none -build-cache /tmp/arduino_cache_202507 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -verbose /tmp/untitled1895295462.tmp/sketch_feb16a/sketch_feb16a.ino
Using board 'nano' from platform in folder: /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr
Using core 'arduino' from platform in folder: /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr
Detecting libraries used...
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/cores/arduino -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/variants/eightanaloginputs /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp -o /dev/null -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/cores/arduino -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/variants/eightanaloginputs /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp -o /tmp/arduino_build_228832/preproc/ctags_target_for_gcc_minus_e.cpp -DARDUINO_LIB_DISCOVERY_PHASE
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_228832/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/cores/arduino -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/variants/eightanaloginputs /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp -o /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp.o
Assembler messages:
Error: unrecognized option -mmcu=avr5
exit status 1
Error compiling for board Arduino Nano.

I am not sure if it's related, but when I try sudo ./install.sh I get the result
pi@raspberrypi:~/Desktop/arduino_32_bit/arduino-1.8.13 $ sudo ./install.sh
Adding desktop shortcut, menu item and file associations for Arduino IDE...

touch: cannot touch '/root/.config/mimeapps.list': No such file or directory
/usr/bin/xdg-mime: 848: /usr/bin/xdg-mime: cannot create /root/.config/mimeapps.list.new: Directory nonexistent

 done!

But arduino studios runs by the script in the folder. I have tried selecting different Programmers with the same result.
I am using arduino arm 32 bit as the 64 bit arm version does install with no error, but it does not start with the script.
Thanks in advance for any ideas on how I can fix this

I would download the Linux ARM 32 IDE and look at something in it to troubleshoot, but their donation screen doesn't want to let me by today.

If you follow the menu back to downloads page, then try again it lets you past.
Or click https://downloads.arduino.cc/arduino-1.8.13-linuxarm.tar.xz

Familiar with that.  Went through  quite a few times.  They're just getting more obnoxious with it.

Well, you can try getting it to download a different version of the AVR core files in the package manager.  Or perhaps dig around in the result of running strace -f on an execution of avr-g++ with file containing nothing but int main(){}  See what (avr-)as it is running.  Kind of sounds like it's locating the wrong assembler, assuming it's really the assembler and not the linker that's actually complaining.

Thank you for your reply timemage, I installed an old version of Arduino (1.8.6) and I use the old bootloader and it works. (Probably should have tried that first, whoops)
Sorry, I'm too new to Linux and avr to know how to run an execution of avr-g++

Finding the the last working core or IDE version may be useful to someone wants to troubleshoot this to a definitive answer.


text:
Switching time of a multiple input switch
I basically have two switches
Both switches will be pressed simultaneously in different order
I want to know which switch was pressed first

Please include in your question a description of what exactly is your problem with doing that. You can edit your question (this information belongs into the question, not in the comments)

simultaneously and different order are mutually exclusive ... you either press them at the same time, or you press them sequentially ... you can't do both

Use External Interrupts is the short answer.
Longer version:
You probably want to make a buzzer system like what in family feud game show.
I assume you are using Arduino UNO/MEGA and or having experience with programming.
1/ Use INT0 and INT1 for button 1 and button 2.
When an interrupt is raised, the mcu jumps to a specific address to run the interrupt service routine. INT0 and INT1 vectors are pointing to two distinctive addresses to run 2 different functions. For this, mcu takes the least amount of CPU clock to capture which button press first.
2/ Use PCINT vectors which is PinChange Interrupt. But personally I prefer to call it PortChange Interrupt.
There are 3 PinChange interrupt vectors PCINT0, PCINT1, PCINT2 to run 3 distinctive service routines. But this kind of interrupt doesn't know which pin is changed.
So inside the interrupt service routine, you have to check for that specific pin. You can do this the arduino way digitalRead(button1) or capture the whole port register, ie. PORTB, PORTC or PORTD.
In a nutshell, PORTB holds values of digital pin 8 to 13 while port D hold values of digital pin 0 to 7 and PORC for A0 to A7.
You can shave off some CPU clocks (3-10 clocks probably) by put 2 buttons different PCINT vectors. So that each button still triggers distinctive function.
In 3 cpu clocks (or around 180 ns) a lot of things may change and you may not get the correct result.
3/ Polling in main loop()
This is the worst way to do it. Nevertheless, it still gives good result.
if (digitalRead(button1)==LOW) {
// do something
}

if (digitalRead(button2)==LOW) {
// do something else
}

The simple version: check continuously for the state of the digital inputs the switches are connected to. When one is HIGH that is the switched pressed first.
The intermediate version: check the 'blink without delay' example to make sure you don't get too many false positives.
The advanced version: use interrupts when one of the two switches gets 'HIGH', using the 'blink without delay' to prevent false positives.

If you want to know if both are pressed at the same time, but one is pressed first, use variables to keep track on it.
like two variables:
bool button1Pressed = false;
bool button2Pressed = false;

Set them accordingly (depending on which of the 3 possibilities you use). Then when you know a button is changed, you can easily check the booleans to know which was already pressed.
Or you can use an enum that combines the state of both:
enum EState { ALL_OFF, BUTTON_1_PRESSED, BUTTON_2_PRESSED, BOTH_BUTTONS_PRESSED };

EState buttonState;