text:
Suggested pullup resistor values for 1-wire network
I'm attempting to connect 6 DS18B20 temperature sensors to an Arduino GPIO pin in a topology that looks something like this:

Conceptually, it's a star network with two star subnets.
The GPIO pin on the Arduino is connected to point "E" through a 4-inch wire, a JST connector, and another 4-inch wire.
The 3 wires (shown in green) connecting sensors "A", "B", and "C" to point "D" are approximately 3 feet long (and are, in fact, the original ~1-meter wires that came pre-attached to the sensors when I bought them). Segment ED is ~4 feet long.
The 3 wires (shown in blue) connecting sensors "G", "H", and "I" to point "F" are approximately 20-30 feet long (including the original 3-foot wires attached to the sensors when I bought them). Segment EF is ~8 feet long.
No parasitic power is involved. Every DS18b20 has 3 wires... +5v (probably closer to 4.5v by the time it gets to G/H/I), ground, and 1-wire data.
So... where would YOU recommend putting resistors (feel free to describe points besides the ones I labeled with letters), and what values would you use?
And... would it actually be any better to take advantage of the fourth (presently unused) wire in the cables I have connecting G, H, and I to F as a 'return wire' to turn it into a much longer daisy chain (E to F, F to G, G back to F, F to H, H back to F, F to I), or something even more radical (say, ED, DA, AD, DB, BD, DC, CD, DE, then continuing the daisy chain with EF as described previously)?
For what it's worth, I presently have a single 4.7k pullup resistor sitting at point "E", and it seems to work... but after reading Maxim's AppNote about "Building reliable long 1-wire networks" (Appnote 148), I'm feeling like it shouldn't work, and that I really ought to do something more sophisticated for the sake of long-term reliability.

where would YOU recommend putting resistors?  ... that question seeks an opinion, which is off topic here ... perhaps ask what is the optimal location for a resistor?

Can you add link to that application note you mentioned? I would place one pullup at the master but I'm not aware of what Maxim suggest...

I think 4.5v is sufficiency unless you experiencing of getting reading of 85000. I once use 3.3v and started get some error reading 85000 if the supply line is noisy.

Added link to AN148

I have a linear network with three thermos at roughly 5', 20', and 40-50' from the micro (a 5v '328p), as well as being parasitically powered. The physical bus is a twisted pair from a Cat-5 cable. The pullup is 4.7KOhm on the processor board.
I've tested this network using a 3.3v '328p and it wasn't as reliable, but reducing the pullup to 2.2K (IIRC) fixed it.
I find Maxim's App Note 148, "Guidelines for Reliable 1-Wire Networks" to be very helpful and is my go-to for 1-wire network questions.


text:
Using an I2C barometer
When buying a barometer for my current project at work, I chose the MikroElektronika click 3 barometer. However, as it turns out, the library for it doesn't exist for Arduino.
I know it uses I2C communication, so I tried connecting the board to my Arduino UNO R3 as follows:

simulate this circuit – Schematic created using CircuitLab
However, I do not know how to use the output of the sensor. Is there a way to access the raw data measured by the sensor and post-process it myself, or is a library needed?
Thanks for your help

Of course there is a way. There is a document called "Data Sheet" for your barometer IC and there should be everything about communication.

The datasheet for DPS368 is available at infinion site. You can use wire library to read the i2c data from it. There are also some information on Mikroe about the board configuration and some c snippets.

I have found MikroElektronika library for the barometer 3. You can get basic idea how to communicate with the sensor.
MikroElektronika c libraray
You can develop your own library based on that one for Arduino or you can read the data sheet of the sensor for more details.

You have an invalid link

I have fixed the link

Hi Arslan, thank you for your answer. However, it seems this library is only usable with MikroE compilers? Or is ther a way to import it on Arduino?

The code is in C, however, a quick looks at the library source file, it does allows to be compiled in C++.  So you need to copy the barometer3.c and barometer3.h into your arduino project file, copy the main.c to your project folder and rename it to barometer3.ino (or your project_name.ino), and modify it to the Arduino sketch format, and if compiler complains, do the modification to the source code or your sketch to make it work.

You need to modify the file to be able to use them

source: Stack Exchange

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

sort: votes


text:
`noInterrupts()` causes the arduino to no longer appear in ports
Minimal working example:
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  noInterrupts();
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

When uploaded to my Arduino Nano 3.3v BLE from my M1 Mac, this causes the Nano to no longer appear in the ports menu. In order to get it to appear again, I have to double press the reset button on the Nano so that it resets to a default script. After doing this, the Nano is available in the ports menu again.
I also cannot see the Nano via cat /dev/cu.<TAB> when this script is uploaded to it.
Does anyone know why this happens? Or alternatively (if this is intended behaviour) why it is not documented in interrupts() or noInterrupts?
I've looked through some other posts, but I don't think they're duplicates of this one:

What functions are disabled with noInterrupts()?: doesn't highlight the behaviour I've seen in the MWE.
Trying to understand interaction of interrupts, noInterrupts and delays: Gives interesting techniques for interrupts and embedded programming, but doesn't mention the behaviour I've seen

Edits in response to answers
So the MWE wasn't quite descriptive enough of my problem and some of the answers got caught up on that (which is my fault). I've included a more detailed description of what I'm doing below to describe what I'm actually doing, but I've also accepted the answer which I think answers the heart of the question "why do interrupts cause the Nano to not appear in port?".
What I'm actually doing is I've got two Arduino Nanos (call them primary and secondary) connected via I2C and Wire.h. Each Arduino nano is reading 15 analog inputs (via a multiplexer). The secondary Nano is then sending its 15 analog readings to the primary over I2C. But I'm getting a lot of noise in the analog readings of the primary Nano, but no noise in the secondary. This noise disappears when I disconnect I2C. So my theory was that digital SCL and SDA wires were causing noise in the analog sensor wires, but I observed the noise would only occur for ~2ms every ~10ms. I thought I'd disable interrupts (and therefor disable Wire.h from pulsing SCL/SDA) while I was reading the primary's analog sensors, and enable interrupts afterwards. This caused the Nano to not appear in the Ports tab, and the rest is the result of this post.
I now think I didn't include the 4.7Ohm pull-up resistor on SDA and SCL which seems to only be included on the official Arduino examples, and never on any random internet examples.

I have no idea what an MWE and you have edited your question to the point where where my answer was no longer in sync with it.

Apologies, MWE=Minimum working example.

I'm not really an expert on the Nano 3.3v BLE, however it appears that it is directly connected to the USB port and thus disabling interrupts will also disable its ability to respond to USB handshakes, thus it will appear to the host that it has been unplugged.
The original Nano had a separate chip (FT232RL) which handled the USB interface, and thus disabling interrupts on that Arduino would not drop the USB connection.

Or alternatively (if this is intended behaviour) why it is not documented in interrupts() or noInterrupts?

Probably the documentation has not kept up-to-date with later product releases. It is not uncommon for documentation to lag behind what the released products actually do.
As timemage points out in another answer, your attempts to blink LEDs with interrupts turned off will not succeed. In fact, turning interrupts off should only be done for milliseconds, not permanently. I assume that is a demonstration sketch, but still ... if you turn interrupts off only briefly the problem should go away.

Yeah, I'd tacked on the clarification about the typical time scale about two minutes before this answer came in. So it probably wasn't in there when you were composing. It's a good point about the documentation. So much of it is really oriented toward the early boards.

Thanks! Yeah the LED part of the MWE wasn't really relevant to the full problem, but you still answered the root question of why this happens. I'm gonna submit a PR to update the docs. Any idea if this is just the Nano, or if it's other boards as well?

It wouldn't surprise me if it related to the more modern boards with the new processors, however I'm not on top of which ones they may be.

@NickGammon I got rid of my answer. Their question is apparently about I2C now... or something. Not interested in chasing the redefinition.

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


text:
How do I build and upload a C++ program without the Arduino Library or IDE?
Note: This is a reference question (but feel free to write answers of your own!)

I want to use the AVR tools directly -- no arduino-builder or arduino-cli. I would also like compilation and uploading to be as fast as reasonably possible

How fast? Can you put a metric on that? Uploading necessarily takes time, because it uses serial communications. Compiling, once invoked by the IDE is likely to be as fast as if you typed it on the command line. Of course, we would all like it to be faster than it currently is. But your requirement to be "fast" is rather un-specific.

Oh, I see this is a reference question. In that case see: https://arduino.stackexchange.com/questions/15893/how-to-compile-upload-and-monitor-via-the-linux-command-line/15898#15898

Create a new file called Makefile in your project directory. Populate it with the following contents:

TEMPDIR := $(shell mktemp -d)

all:
    avr-g++ -DF_CPU=<CLK> -mmcu=<PARTNO> -fno-threadsafe-statics -O3 -flto -std=c++23 -isystem/usr/avr/include -lm -fuse-linker-plugin -Wl,--gc-sections *.cpp -o ${TEMPDIR}/a.elf

    avr-objcopy -O ihex -R .eeprom ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex
    avrdude -V -p<PARTNO> -carduino -P/dev/tty<SERIAL_PORT> -b<BAUD> -D -Uflash:w:${TEMPDIR}/a.hex

    rm ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex
    rm -d ${TEMPDIR}

In the Arduino IDE, press Ctrl+, and enable verbose output during compilation and uploading.
Start uploading with Ctrl+U. Replace the groups of angled brackets in Makefile (e.g. <CLK>) with the values in the Arduino IDE's build output.
Run make.

-lm links in the AVR math library. *.cpp refers to your c++ source files. -V prevents avrdude from reading back the flash contents and verifying it, which saves time, but you may want to disable it while diagnosing problems.

For a similar but more general solution, you may want to take a look at Sudar Muthu's Makefile. If you are not using the Arduino core library, you can remove a lot of cruft from the g++ command line.

Checking the signature and verifying the flashed application are important safety features, I recommend to keep them to avoid long hours of searching errors.

@busybee Amended, thanks

@edgar I just realized "a lot of cruft" refers to my answer, and not Sudar Muthu's Makefile. Fixed, thanks :)

You could enhance your answer a lot, if you add explanations why each step is necessary, and what it contributes to the process. I'm missing for example that the intermediate step with the Arduino IDE is just for finding some decent values for clock and MCU, which could be entered as well manually, since you chose them in the IDE before. -- A great answer would also reason on each option of each tool. Especially as a beginner you need to learn what is important and what is not. Currently this is just one possible way thrown without additional information to unaware users.


text:
How do I escape a boot loop?
Note: This is a reference question (but feel free to write answers of your own!)

I uploaded code that contains a bug that causes my Arduino to immediately reset itself when starting using this code from the AVR libc FAQ. The built-in LED keeps flashing. Because it's in this state of constantly resetting, I'm unable to upload my sketch to it.
I tried holding the reset button while uploading and burning a new bootloader, but neither of those worked.
How do I get my Arduino out of this boot loop so I can upload sketches again?

If you are planning to answer your own questions, which is a great idea, it helps to note that it is a "reference question". That is, you are posting to help other people, not necessarily to canvas for answers. I did this a few times before people pulled me up on it. :)

Thanks for contributing these questions + answers to the community.

Thanks for the tip @Nick, I added a note to all of my questions :)

Start holding the reset button. This is to prevent the Arduino from entering the boot loop.
Unplug the Arduino and plug it back in.
Open a new sketch. Remove all of the code and replace it with int main(){}. This is to create a small program that will upload quickly.
Start uploading the sketch. Avrdude will attempt to upload the sketch ten times -- each time it tries, the RX LED on the Arduino will flash briefly.
Notice how often the LED flashes (0.2 Hz for me). Right before it flashes again, release the reset button. There's a small window of oppurtunity for avrdude to upload the sketch before the arduino starts up. If the TX and RX LEDs flash, success!

Since you have not specified which Arduino you have, answered your own question in quite short time, and commonly a sketch has no main(), this looks fishy.

"answered your own question in quite short time" StackExchange encourages this. This is not a Q&A site, it's a resource

"you have not specified which Arduino you have" This is not relevant

"commonly a sketch has no main()" All sketches have a main(), you just can't see it. This main() can be overridden, which is what happens in my answer

"this looks fishy" What fishy agenda could I possibly have? My answer hurts nobody, but it can help some people. I don't gain any rep from it (thanks to you, I just lost some) -- I posted it solely to help others with the same problem

decent answer to a poorly written question...

I just gave you some rep. Don't worry too much about rep. If you post good questions and answers you will soon have so much rep you won't know what to do with it. ;)


text:
NRF24L01 modules fail to stay connected. Work intermittently
I am trying to get the NRF24 Modules to work but all I get is short lived moments of when it works. I am using the transmitter to send signals to the receiver, which in turn sends a signal to the Motor Controller module to spin the motor.
Both the transmitter and receiver are connected on Nano Every's. Currently they both Arduinos are powered with 9v batteries with the NRF24 modules connected to the 3.3v pin. Both NRF24 modules have 10uf caps connected. I double checked for connections issues and shorts.
Sometimes the Rx and Tx connect and the motor spins correctly and everything is fine. This lasts only a few moments before it stops responding again. Usually it happen when I connect the USB to the transmitter to see what the Serial console is printing. Once I open up the Serial monitor it might, if I am lucky, connect and work for a bit.
I don't have any reason to believe that it is a connection issue since it sporadically works as intended. I can post a diagram if needed. If anyone has any clue I'd appreciate the help.
Here is my Tx code:
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

const byte ledPin = 5;

RF24 radio(7,8); //CE, CNS
const byte address[6] = "00001";
const int button = 3;
int buttonPressed;

int joystick;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MAX);
radio.setDataRate(RF24_250KBPS);
radio.stopListening(); //transmitter

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
digitalWrite(ledPin, HIGH);
delay(300);
digitalWrite(ledPin, LOW);
radio.printDetails();

}

void loop() {

  // put your main code here, to run repeatedly:

  joystick = analogRead(A1);
  Serial.println(joystick);

  if(joystick > 530)
  {
    motorForward(joystick);
  }
  if(joystick < 480)
  {
    motorBackward(joystick);
  }
  if(joystick >= 480 && joystick <= 530)
  {
    motorStill();
  }

}

void motorBackward(int jsInput)
{
 //digitalWrite(motorPin1, LOW);
 //digitalWrite(motorPin2, HIGH);
 int motorSpeed = map(jsInput, 480, 0, 0, 255);
 int message[] = {2, motorSpeed};
 radio.write(&message, sizeof(message));
 //analogWrite(motorPWM, motorSpeed);

 delay(20);

}

void motorForward(int jsInput)
{

 int motorSpeed = map(jsInput, 530, 1023, 0, 255);
 int message[] = {1, motorSpeed};
 radio.write(&message, sizeof(message));

 delay(20);

}

void motorStill()
{

    int message[] = {0};
    radio.write(&message, sizeof(message));
}

Here is my Rx code:
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#define motorPWM 6

RF24 radio(7,8); //CE, CNS
const byte address[6] = "00001";

byte motorPin1 = 4;
byte motorPin2 = 5;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(0,address);
radio.setPALevel(RF24_PA_MAX);
radio.setDataRate(RF24_250KBPS);
radio.startListening();

 pinMode(motorPin1, OUTPUT);
 pinMode(motorPin2, OUTPUT);
 pinMode(motorPWM, OUTPUT);

 //test motor
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPWM, 600);
Serial.print("Test motor started");
delay(2000);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin1, LOW);
Serial.print("Test motor complete");
radio.printDetails();

}

void loop() {

  // put your main code here, to run repeatedly:

if(radio.available())
{
   //0 = still, 1 is forward and 2 is backward
  int message[2];
  Serial.println("radio detected");
  radio.read(&message, sizeof(message));
  Serial.println(message[0]);
  Serial.println(message[1]);

  if(message[0] == 1)
  {

    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, LOW);
    analogWrite(motorPWM, message[1]);
    delay(20);
    Serial.println("move forward");
  }

  if(message[0] == 2)
  {
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, HIGH);
    analogWrite(motorPWM, message[1]);
    delay(20);
  }

  if(message[0] == 0)
  {
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, LOW);
    delay(20);
  }

  Serial.println("radio available");

}

}

what kind of 9 V batteries are you using? ... these are only good for very low power applications, such as smoke alarms ... https://duckduckgo.com/?q=9v+block+battery&iax=images&ia=images

I am using recharable 600mAH 9v batteries. Would a USB connection be enough?


text:
Can read Serial but cannot write - serial communication Arduino Mega 2560 clone
I am having issues using the following USB to UART module. I am using an Arduino 2560 clone.
I have two connections with the Arduino:

COM7 which consists of the given module, connected to the main Rx0/Tx0 on the Arduino, with yellow to Tx0, orange to Rx0 and ground to the Arduino ground.
COM4 which consists of a usual USB to USB module, connected to the Arduino's USB port.

I can read from the Arduino perfectly fine using either COM4 or COM7, but I cannot send data through the serial or upload a program to it through COM7, only through COM4.
I have tried the following for uploading data with COM7: PuTTY and Arduino Serial.
Once again: The Arduino can correctly receive a program file or read serial input data from COM4, it correctly outputs data to either COM4 or COM7, but I cannot upload data to it from COM7.
Code I am using to test the COM7's ability to send data:
int incomingByte = 0; // for incoming serial data

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
  }
}

test the USB to UART cable using a PC without an arduino

you can upload over USB while the the external USB Serial adapter is still wired to RX0/TX0?


text:
How do I upload a sketch without a bootloader, using another Arduino as a programmer?
Note: This is a reference question (but feel free to write answers of your own!)

My Arduino takes too long to start up, I need to use the space taken up by the bootloader and I don't want a brown-out to be able to move the program counter to bootloader code, which could lead to my code being corrupted.
I considered buying an Arduino programmer, but since I already have an Uno lying around doing nothing, I would rather use that as a programmer.
I found a few guides on the internet, but most of them leave important details out and aren't specific enough.
So, how can I upload a sketch without a bootloader, using another Arduino as a programmer?

a 10-year old blog post about another stack might not be as relevant here as imagined. Of course SO wants any and all free content, but do users? I don't have a problem with it, but you should probably make your "questions" better fit the usual format; for this one, the "what have you tried" part is lacking, which makes this effort seem more like fishing for points than a useful Q+A combo. Your information is well laid-out and your intentions well-laid, but you should likely pay a bit closer attention to the rules, conventions, and expectations. If you beef up the question I will UV...

@dandavis I beefed up this question and the other one. I rewrote them in a more asking-help kind of manner and added things that might have been tried by the questions' target audiences. Do they look good now?

@dandavis Reference questions are perfectly fine. Our expectations are that people will contribute to the community, which glibg10b seems to be doing. Let's try to encourage new contributors.

There are a few guides on the internet that explain how to do this, but I've
found that most of them contain too much ambiguity or leave important details
out. This is my attempt at writing a short but complete guide that's easy to
follow.
Prerequisites

The board that will run your sketch
A board that will act as a programmer (a.k.a. "ISP")
7 wires
Any small capacitor

Steps
Programming the programmer
First, you'll need to upload the ArduinoISP sketch to the programmer. Here's
how:

In the Arduino IDE, press Alt+F and open Examples ->
11.ArduinoISP -> ArduinoISP.
Plug in the programmer board (USB).
Press Alt+T and set "Board" to your programmer
board's type and "Port" to your programmer board's serial port.
Press Ctrl+U to upload the sketch to your programmer.

Connecting the boards
Then you need to connect the programmer to the board that will run your sketch.

Unplug the programmer board. This is to prevent accidental short-circuits.
Connect pins GND, 10, MOSI, MISO, SCK and 5V of the programmer to pins
GND, RESET, MOSI, MISO, SCK and 5V of the board that will run your
sketch, respectively. Pins MOSI, MISO and SCK correspond to pins 11, 12 and
13, respectively, on the Uno and the Nano. Consult your board's datasheet if
you're uncertain.
Connect the capacitor between pins 5V and RESET of the programmer board. This
is to prevent it from auto-resetting while programming.
Plug in the programmer board. You will never need to plug in the board that
will run your sketch.

Uploading your sketch
The order of these steps is important due to a bug in the Arduino IDE.

Press Alt+T and set "Board" to the board that will run
your sketch's type, "Port" to your programmer board's serial port and
"Programmer" to "Arduino as ISP".
Open the sketch you would like to upload.
Press Ctrl+Shift+U to upload the sketch using the programmer.

Troubleshooting
If something went wrong, press Ctrl+, and enable verbose
"compilation" and "upload" and repeat the step that went wrong. Look out for
these error messages:
avrdude: stk500_recv(): programmer is not responding
Followed by something similar to:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

Remove the capacitor before uploading a sketch to your programmer board.
avrdude: Yikes!  Invalid device signature.
Scroll up and copy the line that looks similar to the following:
...avrdude -C...avrdude.conf -v -V -p... -c... -P... -b... -Uflash:w:....hex:i

Paste it into a terminal and add  -F to the end. You can reuse this command
every time you upload the same sketch.
The upload seems to succeed but my sketch is still running the same code!
If the board that runs your sketch's CPU clock is slower than 1MHz (e.g. your
sketch modifies the CPU prescaler), you need to change (1000000/6) in the
ArduinoISP sketch to something slower and re-upload the sketch to your
programmer.


text:
How can I clear two FastLEDs strip ws2812b separately? One strip is connected to pin 7 of UNO and other strip to pin 6 of UNO
The power supply is external. I want to clear one strip say pin 7, and meanwhile i dont want other strip say pin 6 to switch off...I use
FastLED.clear();
FastLED.show();
But it clears all the led strips connected to pin6 and pin7. What is the code to switch off only one strip?

You can use two CLEDController instances, which you can control separately, and by using the clearLedData you can clear either one or the other LED strip (depending on the CLEDController instance).
Below is the code I copied from
https://forum.arduino.cc/t/xrads-fastled-fastled-clear-question/693569/8
which contains more info:
#include <FastLED.h>

#define COLOR_ORDER GRB
#define LED_TYPE WS2812B

#define DATA_PIN 9
#define NUM_LEDS 26
CRGB leds[NUM_LEDS];

#define HEADLIGHTS 10   //headlight led pin
#define NUM_HEADLIGHTS 2
CRGB leds2[NUM_HEADLIGHTS];

CLEDController &ledController = FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
CLEDController &headlightController =   FastLED.addLeds<LED_TYPE, HEADLIGHTS, COLOR_ORDER>(leds2, NUM_HEADLIGHTS);

void setup() {
  ledController.setCorrection(TypicalLEDStrip);
  headlightController.setCorrection(TypicalLEDStrip);

  ledController.clearLedData();
  headlightController.clearLedData();
  FastLED.show();
}

void loop() {
}

Thanks a lot Michel it worked wonderful!!


text:
Arduino Nano IOT33 - Using flash
I'm looking for a way to store data on flash as on ESP8266 or ESP32 using FS.h,  LITTLEFS.h but it fails.
Is is possible on Nano IOT33 ?

the SAMD21 on Nano IoT has only 256 kB of flash. esp has at least twice as much. and file system is usually used on esp with 4 MB flash

It seems this library can be used:
https://github.com/cmaglie/FlashStorage
Library: FlashStorage library for Arduino
About info: A convenient way to store data into Flash memory on the ATSAMD21 and ATSAMD51 processor family
Mentioned in external related article (thanks to Juraj): https://forum.arduino.cc/t/persistent-storage-for-arduino-nano-33-iot-no-eeprom/623137
UPDATE
(See remark of Juraj below: this is NOT for a Nano IOT33)
See Library: https://github.com/khoih-prog/FS_Nano33BLE
About info: Wrapper of FS (LittleFS or not-advisable FATFS) for Arduino MBED nRF52840-based boards, such as Nano_33_BLE boards. This library facilitates your usage of FS (LittleFS or FATFS) for the onboard flash. FS supports power fail safety and high performance
Mentioned in:
https://forum.arduino.cc/t/fs-nano33ble-library-for-nano-33-ble-using-littlefs-fatfs/900463

That one I saw, but it seemed as EEPROM more than FS

It's not the same thing, but you can kind of mimic it (it both stores data).  As Juraj already mentioned, it also is about the amount of memory.

I updated my answer with a FS library.

Nano BLE is a different board with a different MCU and a an Arduino core based on mbed. the nRF52840 has 1 MB flash memory

@Juraj Thanks for that remark, I will keep the answer but make a comment just to keep others informed.


text:
How can I log data to a thumb drive?
I am working on a project where I need to log data, but I was wondering if it is possible to log that data to a thumb drive? I know that I can log data to an SD card, but I thought a thumb drive would be more accessible to users who wish to obtain the data. And if it is possible to log to a thumb drive, could it be done in CSV format?
The data is just sensor data.

they make tiny readers that convert sd/microsd into usb drives, in about the same form factor as a thumb drive. not exactly the same thing, but way easier and cheaper to interface with an MCU.

In principle you can log to a thumb drive any data you want, binary and text (thus also CSV).
However, the Arduino Uno does not support connecting a USB stick directly. If you want to connect a USB stick, you need a so called USB Host shield (for Arduino).
More information can be read on the Arduino site at this page:
https://docs.arduino.cc/retired/shields/arduino-usb-host-shield

[Updated]
As an alternative to a Uno host shield, changing to a different Arduino MCU may also assist. USB host capabilty is needed for communicating with thumb drives.
Some Arduino models have a native USB port (e.g., Arduino Due, Arduino Leonardo, Arduino Micro, Arduino Nano 33 IOT, Arduino Zero, Arduino MKR Zero, Arduino MKR1000 ... ) which will work as a USB client device role.
A smaller set of MCU can act as either a USB client or host (e.g., Arduino Due, Arduino Portenta, ...). There is a USBHost library for Arduino Due listed in the Arduino Reference. Documentation for Arduino Portenta in USB host mode is here.
Here is a discussion (and reference to an alternative library) regarding using a Due to write files to a thumb drive.
Of course an adapter cable or a thumb drive with a physical connector matching the native USB port on the selected MCU is required. Both are commonly available.
See also Can the Arduino interface with USB devices without the USB host shield?

For the Micro and Leonardo, the datasheet of the ATmega32U4 says its USB controller “Supports full-speed and low-speed Device role”. I see no mention of support for the host role. Are you sure they can act as a host?

Hi Edgar, no my experience has been with the Due, and so I relied on the linked discussion for the list of other MCU with native USB. I’ll edit my answer. Thanks. Do you know of a list of MCU with host capable native USB?

No, sorry. My experience with USB-capable Arduinos is limited to playing with the Keyboard library on a Micro. I just learned that the Due is host-capable, thanks to your answer.

Thanks for the help!


text:
ESP32, NTP and SW reset
After HW reset (button or power reconnect) I get the correct NTP shift, but when I use ESP.restart() via MQTT I get the correct time without 3 3 HRS shift due to Tz. What happens after SW reset that behaves in such manner and how to fix it?
bool myIOT2::_startNTP(const char *ntpServer, const char *ntpServer2)
{
    unsigned long startLoop = millis();
    while (!_NTP_updated() && (millis() - startLoop < 20000))
    {
#if defined(ESP8266)
        configTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer); // configuring time offset and an NTP server
#elif defined(ESP32)
        configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);
#endif
        delay(1000);
    }
    if (!_NTP_updated())
    {
        return 0;
    }
    else
    {
        return 1;
    }
}
bool myIOT2::_NTP_updated()
{
    return now() > 1640803233;
}

Would you please add in the (relevant bits of the) application code as well?

Apparently, time in ESP32 survives a sw reset, while in ESP8266 doesn't.
So in code, which is same for both  - if clock is updated (a rough criteria that time is greater than some day in 2020 ), it skipped TZ update  configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);
So after a crash and/or sending a MQTT message to reboot, time was missing TZ update.
Hope it'll help someone.
Guy


text:
How to cut down size of imported DigiKeyboard library
I'm working on a project with a Digispark ATTiny85, that performs keystrokes using the DigisparkKeyboard library (https://github.com/digistump/DigisparkArduinoIntegration/tree/master/libraries/DigisparkKeyboard). Besides the DigiKeyboard, I also import EEPROM.h.
My own code is only about 150 lines, I've cut down the size following a number of online guides, trying to avoid larger data types and so on. The Digispark is limited to ~6kB and the imported DigiKeyboard library takes up a little more that 5.4kB. In total the compiled project takes up about 7kB, which exceeds the boards capacity.
From the DigiKeyboard library I only use DigiKeyboard.sendKeyStroke() and DigiKeyboard.print() (with about only ten different characters). So I assume there is a lot of unused code I could remove, but I don't know how to approach this. I use Visual Studio Code and PlatformIO.
How could I reduce the size of the used DigisparkKeyboard library?

Are you printing numbers or only fixed messages? In the later case, does it help if you use write() instead of print()?

Also, I have no experience with PlatformIO, but I guess you should be able to enable a “verbose” mode that shows you the full command used to call the compiler. Could you please check whether this command contains the option -flto?

Thanks @EdgarBonet! The compiler flag -O3 -flto didn't change a byte for me and I couldn't find any documentation on write(). However, I switched to .sendKeyStroke for all write operations from .print(), which shaved off about 3kB! and the code fits the board! If you formulate an answer, I'll gladly accept it!

I just noticed that the big issue here wasn't the inclusion of print(), but rather one single instance of print, where I did: DigiKeyboard.print("Time: "+String(round(runtime/1000)));. So I believe the large code was due to the inclusion of String().

Re “If you formulate an answer, I'll gladly accept it!”: Well, actually you found your solution yourself! In such a case, the recommended practice it to post and accept your own answer.

With input from @EdgarBonet, I looked into the functions used and it turned out that the String() function, I used once in my code, takes up about 3kB of space in the compiled program.
I ended up removing the line with String() and kept the imported DigiKeyboard library as it is.

The compiler/linker will remove unused functions/methods automatically, so I doubt you can save memory by removing unused functions/methods yourself.
However, you could possibly gain by:

Removing the calls of check functions/methods when you know the result will be always false, true, or always the same number, string or data type in general.
Removing (parts of) functions/methods which are related to physical or logical functionality you never use. Like e.g. if, case statements that will never apply).
Prevent using an entire class (e.g. String) (see second comment of Emma Makes below).

Thank you for the feedback! I wasn't aware that unused functions and methods aren't included anyways! I was able to shave off about 3kB by switching from .print() to .sendKeyStroke! I'll keep the other suggestions in mind for future issues!

I would need to edit the comment, but it's too late to do so. The reduced size was not due to the change from print() to sendKeyStroke(), rather the fact that I didn't use String(), which I previously used in the print() function call.

That's also indeed a good way to reduce size, to preventing using a complete class (String in your case). I will add it to my answer


text:
Why is my SD shield making my Arduino not power on?
I wanted to use an SD shield on an Arduino Elegoo to make a typewriter (for saving files).
I put the shield on the Arduino Elegoo, then connected an LCD screen, then tried to power on using USB to computer, but my Arduino Elegoo wouldn't power on.
I tried to power it on with the external power supply, but it still wouldn't power on.
If I power it on without the shield it works perfectly fine, so why is my Arduino Elegoo not powering on?

When you say you "remove the shield" I assume that also implies removing that tangle of wires too? What about leaving the shield on but disconnecting the wires? I'll bet it works then. The problem won't be with the shield, it'll be a mistake in your own wiring.

Majenko  Yes you are correct it powers on without the wires but the lcd screen powers on without the sheild plus the elegoo powers on too whereas if i have the sheild and elegoo connected to the lcd screen then it does not work so how do i fix this since the lcd screen is important in the project

pins 10 to 13 are SPI pins used by the SD shield. it looks like you use the same pins for the LCD and I doubt the LCD works on SPI bus.

If you want to make your question answerable to the point of receiving specific instructions you'd need to include images of the sort of quality that would allow readers to trace each connection unambiguously. There are common SD card shield designs, but someone answering this would likely want to know exactly which design your shield follows. To get the sort of answer that would lead you to a successful outcome as a whole project you'd also want to include your code as well.

juraj yep you're right it worked


text:
Safe to solder a slide switch to unused GPIO pins?
I have a Digispark Rev.3 Kickstarter with ATTiny85 (see pinout below) and a three pin slide switch (see example below). I want to use the slide switch to control a task running on the Digispark, with the example code below.
The center pin of the slide switch will be connected to GND, one pin will be soldered to pin 2 on the Digispark (pinMode(2, INPUT_PULLUP);) and the remaining pin will be unused.
To install the switch, I want to have the center pin of the switch go through P3 on the pinout, one pin through P2 (which will be addressed in the code) and the remaining pin through P4. This means, P3 will be soldered to GND and depending on the switches position, P2 or P4 will connect to GND as well.
Could these connections between P2, P3 or P4 and GND interfere with the functionality or damage the Digispark?
int switchPos;
void setup() {
  pinMode(2, INPUT_PULLUP);
}

void loop() {
  switchPos = digitalRead(2);
  if (sensorVal == HIGH) {
    runCode();
  } else {
    delay(1000);
  }
}

Yes, you will lose the USB connection, since PB3 and PB4 are used for the USB communication. Normally you wouldn't solder a component directly onto a board if it doesn't fit with all pins. Instead you would use wires or a breakout PCB to do the job.
If you really want to to that and you don't need any of the other pins, then you can use PB0 and PB1. Set PB1 to OUTPUT LOW and PB0 as input. The OUTPUT LOW is basically the same as ground and configuring a pin as INPUT will make it high resistance, so it doesn't interfere with the circuit.

Thank you for the feedback! By USB connection loss you mean via the pins 3 and 4 or in general? Because I am using the USB male plug to emulate a keyboard on this project. As for your suggestion about the pins 0 and 1, you'd say I could solder the switch like so https://i.imgur.com/67Uhvu2.png and use the OUTPUT LOW on pin 1 as an alternative to ground, correct?

Pins PB3 and 4 are the data pins for the USB connection (emulated via software). When you want to send any data over USB you cannot use these. And yes, thats the wiring that I suggested (besides using wires)

Thank you for the feedback and your patience @chrisl! I've just checked the schematics of the Digispark and I understand how it makes sense, that the USB connection is impaired if I meddle with those pins.


text:
How to shift binary into a shift register (serial in, parallel out) sequentially
I'm trying to make a continuity tester at work where I connect the input and output of a harness into a test fixture powered by an Arduino. This tester tests whether the position of the connects are pinned correctly.
Here is the diagram of my initial idea:

From one end of the connector (the output in the diagram), I want to shift in a binary that is in the power of 2. For instance, shifting in 0001, check for continuity by reading the 75HC165 (parallel in, serial out), then clear the register and then shift in 0010, and then 0100 and so on. For a correctly pinned harness, the write and read binary subtraction will be zero.
Here is my loop that attempts to perform the above:
void loop() {
  for (int i = 1; i < 4; i++) {
    reset_SIPO_register();
    shift_SIPO(pow(2,i));
    delay(2000);
    shift_SIPO(0x00));
    check_continuity(); // not implemented yet
  }
}

void reset_SIPO_register() {
  digitalWrite(reset_pin, LOW);
  digitalWrite(reset_pin, HIGH);
}

void shift_SIPO(int sequence) {
  digitalWrite(latch_pin, LOW);
  shiftOut(data_pin, clock_pin, MSBFIRST, sequence);
  digitalWrite(latch_pin, HIGH);
}

I am testing this concept on a breadboard with LEDs and the above kind of works. However, the LED is lit up one at a time and they don't turn off, not following the binary.
Is there something I'm missing here? thanks!

yes, you are missing the full schematic diagram and complete code from your post

Do not use pow(). This is a function that works with floating point
numbers. It is roughly equivalent (for y > 0) to
double pow(double x, double y)
{
    return exp(y * log(x));
}

As all transcendental functions, its implementation is prone to rounding
errors. It is not even guaranteed to give you the “correctly” rounded
version of the exact (i.e. infinite precision) result. In fact, very few
floating point functions give this guarantee.
As an example, if you compute pow(2, i) for i = 3, you get
7.9999980926513671875. This is 4 ULPs smaller than the exact value.
Passing this number to shift_SIPO() implicitly converts it to an
int, and this conversion always rounds to zero. Thus you get 7, i.e.
0b0111.
What you want is an integer, exact implementation of pow(2, i). It
turns out this is quite simple: Take the integer 1 in binary, then shift
it i times to the left. That is
shift_SIPO(1 << i);

Thank you! that worked!


text:
Interrupt is sporatic, potentially after 220Hz or so
Background although likely not needed: I am recieving a frequency on the destination side of a opto isolater.  A fan trips a hall effect sensor, and grounds a circuit which lights the opto.  On the recieving end I have a fully isolated arduino circuit that accurately reads this 550Hz (peak) signal.  However, my Uno stopped reading this value correctly.  So I debounced the circuit which did not fix the issue.  I now brought in a new (and isolated) Uno that has nothing else going on but reading this signal and its Interrupt is also sporatic after several seconds.
I believe it is operating OK until the signal gets to about 420Hz (which is nothing..).  PulseIn also returns many "0" durations with the "900ns" good durations.  So it seems the high/low trigger is flipping too often, which was not fixed with debounce. I can see using the oscilloscope that the signal is good at 550Hz
21:34:12.750 -> Htz: 0
21:34:14.575 -> L: 44
21:34:14.575 -> Htz: 88
21:34:15.265 -> L: 70
21:34:15.265 -> Htz: 140
21:34:15.479 -> L: 89
21:34:15.479 -> Htz: 178
21:34:15.913 -> L: 109
21:34:15.913 -> Htz: 218
21:34:16.452 -> L: 117
21:34:16.577 -> Htz: 234
21:34:16.986 -> L: 134
21:34:16.986 -> Htz: 268
21:34:17.511 -> L: 186
21:34:17.511 -> Htz: 372
21:34:18.036 -> L: 213
21:34:18.036 -> Htz: 426
21:34:18.567 -> L: 702
21:34:18.567 -> Htz: 1404
21:34:19.195 -> L: 1913
21:34:19.196 -> Htz: 3826
21:34:19.838 -> L: 3508
21:34:19.838 -> Htz: 7016

code
unsigned long timestamp;
int lsensorpin = 2;
int PWMpin = 3;
String printout;
unsigned int reading;
unsigned long L;
unsigned int lRPM;
unsigned int Htz;

void setup() {
  pinMode(lsensorpin, INPUT);//_PULLUP); //2
  pinMode(PWMpin, OUTPUT);
  analogWrite(PWMpin, 100);
  Serial.begin(9600);
  Serial.println("FInish Setup");
}

void loop() {

  //printout=" High:";
  //reading= pulseIn(lsensorpin, HIGH);
  //printout=printout + reading + " Low:";
  //reading= pulseIn(lsensorpin, LOW);
  //printout= printout + reading;
  //Serial.println(printout + reading);

  L=0;
  attachl();
  delay(500);
  detachl();
  Htz=L*2;
  lRPM= L*60;
  Serial.print("L: ");
  Serial.println(L);
  //Serial.print("Htz: ");
  //Serial.println(Htz);

  //Serial.print("RPM: ");
  //Serial.println(lRPM);
}

void tickL() {
L=L+1;
}

void attachl(){
    attachInterrupt(digitalPinToInterrupt(lsensorpin), tickL, RISING);
}

void detachl(){
    detachInterrupt(digitalPinToInterrupt(lsensorpin));
}

Did you consider that delay() is influenced by the interrupts? Each interrupt service takes some run time, and the delay is prolonged by that run time. The function realizes the delay through a certain number of instruction cycles. You might want to use a timer to realize the measurement interval.

Why are you attaching and detaching the interrupt in your main loop? Try using a faster baud rate, eg. 115200 baud. (9600 is really slow).

From my post about interrupts:

I have seen example code suggesting you count things for a second by turning interrupts off for a second and then on again. I don't recommend this, because for one thing, you can't do serial prints if interrupts are off.
Example (not recommended):
volatile unsigned long events;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  events++;
  }   // end of eventISR

void setup ()
  {
  Serial.begin(115200);
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }   // end of setup

void loop ()
  {
  events = 0;       // reset counter
  interrupts ();    // allow interrupts
  delay (INTERVAL); // wait desired time
  noInterrupts();   // stop interrupts

  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of loop

That may work for simple situations, but turning interrupts off means that the Serial prints won't work until they are turned on again (which they may not be in a more complex sketch).
It is better to use the millis() result and just detect when the time limit is up.
Improved sketch:
volatile bool counting;
volatile unsigned long events;

unsigned long startTime;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  if (counting)
    events++;
  }  // end of eventISR

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }  // end of setup

void showResults ()
  {
  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of showResults

void loop ()
  {
  if (counting)
    {
    // is time up?
    if (millis () - startTime < INTERVAL)
      return;
    counting = false;
    showResults ();
    }  // end of if

  noInterrupts ();
  events = 0;
  startTime = millis ();
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  counting = true;
  interrupts ();
  }  // end of loop

In loop() here we wait for the interval (1 second in this case) to be up, otherwise we return, effectively doing nothing. You could of course do other things instead of just returning.
If the time is up we display the count.
If counting is not currently active (and presuming we want it to be active) we remember the start time, reset the counter to zero, and let it start counting up.
That code seemed to work OK up to 100 kHz, although the counts were getting a bit inaccurate. You can do more precise timings by using the hardware counters / timers. Details here:
http://www.gammon.com.au/timers

Also you should declare the variable L to be volatile.

Interresting formatting, looks somehow like python style.. I can't see blocks properly either :D (subjective feeling)

@KIIV  Why? The entire block is indented. I find that is the easiest to read. I think it is called Whitesmiths style. "It was also popular in the early days of Windows, ..." - I've been around for a while, so I probably picked up that style years ago.

It's just that I'm not used to this style. I'm somehow used to search end bracket with smaller indentation than code. You know, almost 2 decades of using one or two similar styles


text:
Disable USB support for mega32u4
I have a custom Leonardo board (mega32u4-based) that does not use at all the USB features.
When I build my sketch (vscode and platformio) I read:
Compiling .pio/build/leonardo/FrameworkArduino/CDC.cpp.o
Indexing .pio/build/leonardo/libFrameworkArduinoVariant.a
Compiling .pio/build/leonardo/FrameworkArduino/HardwareSerial.cpp.o
Archiving .pio/build/leonardo/lib02e/libFadeLed.a
Compiling .pio/build/leonardo/FrameworkArduino/HardwareSerial0.cpp.o
Indexing .pio/build/leonardo/lib02e/libFadeLed.a
Compiling .pio/build/leonardo/FrameworkArduino/HardwareSerial1.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/HardwareSerial2.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/HardwareSerial3.cpp.o
Archiving .pio/build/leonardo/libfa3/libWire.a
Indexing .pio/build/leonardo/libfa3/libWire.a
Compiling .pio/build/leonardo/FrameworkArduino/IPAddress.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/PluggableUSB.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/Print.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/Stream.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/Tone.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/USBCore.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/WInterrupts.c.o
Compiling .pio/build/leonardo/FrameworkArduino/WMath.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/WString.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/abi.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/hooks.c.o
Compiling .pio/build/leonardo/FrameworkArduino/main.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/new.cpp.o
Compiling .pio/build/leonardo/FrameworkArduino/wiring.c.o
Compiling .pio/build/leonardo/FrameworkArduino/wiring_analog.c.o
Compiling .pio/build/leonardo/FrameworkArduino/wiring_digital.c.o
Compiling .pio/build/leonardo/FrameworkArduino/wiring_pulse.S.o
Compiling .pio/build/leonardo/FrameworkArduino/wiring_pulse.c.o
Compiling .pio/build/leonardo/FrameworkArduino/wiring_shift.c.o

I wonder if I can disable the USB support (CDC, PluggableUSB, USBCore) and also network stuff (IPAddress) in order to save flash space.

I think the optimizer will kick that stuff out when you don't use it. So that should already happen.

USBCore creates the com port for upload and handles the 1200 baud 'touch' for reset to bootloader before upload

@Juraj, yes but as I said I have no bootloader neither any USB com port

@Juraj done. I can't find any entry about IPAddress but all the USB stuff is there

main.cpp has USBDevice.attach();

@Juraj sorry I don't understand you. Which main.cpp? Anyway, is it possible to save flash space disabling the USB stuff?

https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp

I doubt the optimizer will determine that it can eliminate the USB ISRs and their dependencies. Where the core conditionally compiles the USB parts based on the presence of USB peripheral register definitions, you're left with a bunch of options that aren't great. E.g. modifying the core to not include these features all or to extend the expression with something like && !defined(NO_ARDUINO_USB_STACK). Or to fake out the core by (not/un)defining the USB peripheral with a modified avrlibc, again perhaps conditionally. And maybe modifying board.txt to pass feature flags for that purpose.


text:
Unpredictable behavior of a 74HC595, Q0 has no output and LED flickering
Below is my schematics:
I am using a 74HC595 shift register and to test my connections, I have placed 8 LEDs to the output and shifted 0xFF into the shift register (1111 1111), this should light up all the LEDs. However, Q1 to Q7 lit up, but Q0 didn't, it is very dim and flickering,
After doing some research and came across the decoupling capacitor and I have place a 10uF capacitor between the 5V and GND rail on the breadboard. However, the problem still persists, Am I missing something?
thanks!
Here is my code:
int data_pin = 8;
int latch_pin = 9;
int clock_pin = 10;
int reset_pin = 11;

void setup() {
  pinMode(latch_pin, OUTPUT);
  pinMode(data_pin, OUTPUT);
  pinMode(clock_pin, OUTPUT);
  pinMode(reset_pin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  reset_SIPO_register();
  shift_SIPO(0xFF);
}

void reset_SIPO_register() {
  digitalWrite(reset_pin, LOW);
  digitalWrite(reset_pin, HIGH);
}

void shift_SIPO(byte sequence) {
  digitalWrite(latch_pin, LOW);
  shiftOut(data_pin, clock_pin, MSBFIRST, sequence);
  digitalWrite(latch_pin, HIGH);
}

the power rails are separated in the middle on those long breadboards

@Juraj I have several long breadboards, and the ones that are separated also have the red/blue lines interrupted in the middle to show. But Brendon: it's worth checking anyway.

It sounds like a loose connection. Try using a different part of the breadboard - the metal clips in the breadboard sometimes bend and fail causing bad connections.

So, green wire is 5V and is connected to the top red power rail and bottom blue... I wouldn't be surprised if you have LED cathodes on 5V, instead of 0V :D

There is a maximum current the 74HC595 can deliver. Probably you are using more than this current.
See e.g. https://electronics.stackexchange.com/questions/77841/how-much-current-can-my-74hc595-handle-on-each-output-pin
Some easy checks:

Increase the resistor value so the total current is lowered
Temporarily remove some LEDs, to see if the others behave like expected.
Use other LEDs with a higher forward voltage to reduce the current.
Changing the sketch to light one LED at a time to see if all outputs work.

I have tried removing 2 LEDs and Q0 still off,

How much current is going through the total LEDs? I read there is a max of 70 mA and if you put 7 x 20 mA = 140 mA it's double it can handle.

I haven’t done the analysis yet, but what makes me think that the current is okay is because sometimes the leds do light up but for some reason, sometimes it doesnt


text:
Same code working on Arduino IDE but not in PlatformIO IDE
I'm running into this weird problem. My code is working just fine when I upload it to an ESP32 from Arduino IDE. That same code is not working when I upload it using PlatformIO IDE. The same libraries versions are being used on both environments.
I've been reading that in PlatformIO you might have to make use of forward declaration (something that Arduino IDE solves out of the box). I do not know if this is the case. And if it is... I do not know how to apply it.
Can someone help me out with this?
#include <Arduino.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define DHTPIN 23
#define DHTTYPE DHT11

LiquidCrystal_I2C lcd(0x27,16,2);

DHT dht(DHTPIN, DHTTYPE);

void setup() {

  lcd.init();
  lcd.backlight();

  Serial.begin(115200);
  dht.begin();
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print(F("Humedad: "));
  Serial.print(h);
  Serial.print(F("% Temperatura: "));
  Serial.print(t);
  Serial.println(F("°C "));

  lcd.setCursor(0,0);
  lcd.print("Humedad: ");
  lcd.println(String(h));
  lcd.setCursor(0,1);
  lcd.print("Temp.: ");
  lcd.print(String(t));
}

EDIT:
platformio.ini
[env:fm-devkit]
platform = espressif32
board = fm-devkit
framework = arduino
monitor_speed = 115200
upload_port = COM9
lib_deps =
    adafruit/DHT sensor library@^1.4.3
    adafruit/Adafruit Unified Sensor@^1.1.5
    marcoschwartz/LiquidCrystal_I2C@1.1.2

What exactly does "not working" mean here? Do you get compilation errors? Or uploading errors? Or is the behavior of the code different than expected after successfull compilation and upload?

can you post your platformio.ini file? The problem could be that you are using a different version of the ESP-IDF which is pre-compiled in the arduino environment (which is not neccessarily the case when working with platformio).

@chrisl The code just compiles and runs... but it does not print anything to the display

@SimSon I added the plaformio.ini

hmm, the .ini looks like I'd expect it, except that I don't know that board (I assume that you'd choose the exact same board in the Arduino IDE). Maybe you could try to use board=esp32dev in case the pin mapping is messed up some how for that board (the pin mapping should not depend very much on the actual board as long as it's based on an ESP32. But that's my only idea here and I'm actually not sure if that makes much sense...

does not work either... thanks anyway

Does the code print to the serial monitor as expected? Could you try removing the “°” character in F("°C ")? Could you try removing the casts to String (lcd.println(h); instead of lcd.println(String(h));, same for t)?

And what is on the serial interface? (You can always add more trace messages to figure out how far it gets)

yes it does print to the serial monitor as expected

Verbose compile and link output for both environments might be of some use.


text:
Help with the Arduino Wire I2C Communication with MAX16826 LED Controller IC
I'm trying to read and write to this MAX16826 LED controller evaluation board through I2C. There is no specific library for this IC so I have to use the Wire library and the datasheet to try to communicate with it. My use of this library is limited and my test code doesn't seem to work. While I wait for the MAXIM tech support, I thought I'd ask here.
According to the IC datasheet, the 7-bit address is 0x58 while the 8-bit read and write addresses are 0xB1 & 0xB0 respectively. I was able to detect the 7-bit address using the i2c_scanner example sketch but after a while, it seems to lose communications with it. Attached below is a picture of what I meant.

My code tries to read and write to the MAX16826's register 0x00 by following along the Wire API and the datasheet. However the results I got out of the register from Wire.requestFrom() was 255 when it should be 0. Not sure what's exactly going on. I read through the Wire API but still not sure how to detect the ack bits from the slave IC.
Here are the relevant key information from the datasheet:

Here is my Arduino test code. I did remove parts that were extra and unnecessary for simplicity purposes:
#include <Arduino.h>
#include <Wire.h>

#define MaxAddr 0x58        //7-bit address
#define MaxAddrRead 0xB1    //8-bit read address
#define MaxAddrWrite 0xB0   //8-bit write address
#define enPin 12            //Arduino pin for IC enable

//protoype function declarations
void basicWriteTest();
void basicReadTest();

void setup() {
  Serial.begin(115200);
  Wire.begin();
  //enable the MAX16826 IC
  pinMode(enPin, OUTPUT);
  digitalWrite(enPin, HIGH);
  //wait for the serial monitor to be opened
  while (!Serial);
  delay(1500);
  //function to write to register 0x00
  basicWriteTest();
}

void loop() {
  //function to write the value at register 0x00
  basicReadTest();
  delay(1500);
}

void basicWriteTest(){
  Wire.beginTransmission(MaxAddrWrite);
  //write to register 0x00
  Wire.write(0x00);
  //write the value 0x00 to that register
  Wire.write(0x00);
  Wire.endTransmission();
}

void basicReadTest(){
  Wire.beginTransmission(MaxAddrRead);
  Wire.write(0x00);
  Wire.endTransmission();

  Wire.requestFrom(MaxAddrRead, 1);
  if (Wire.available() <= 1){
    uint8_t data = Wire.read();
    Serial.println("Data = " + String(data));

    float mV = float(316) - 1.72 * (data & 0x7F);
    float mA = mV/2.2;

    Serial.println("mV = " + String(mV));
    Serial.println("mA = " + String(mA));
  }else{
    Serial.println("Failed to get read on MAX!");
  }
}

You should be using the 7bit address for beginTransmission/requestFrom

@Mat how would I write the final bit for read or write then?

The library does it. Check the docs (parameter descriptions) for those two functions.

Check your pull up resistors.

@Gil I have a 10K pull up resistor on both the SDA and SCL line so I highly doubt that's the problem.

That is a bit light, try using 4.7K pull up resistors one for SCA and one for SCL I think your problem will go away. Without a schematic or knowing how long the wires are I cannot be sure. If you are operating on 3V3 go to something in the 3K range.


text:
Requires accurate RGB color values by the tcs3200 RGB color sensore
I used the TCS3200 sensor to read the RGB color values.First, I calibrated the sensor with white and black colors.The sensor detects red, blue, and green correctly, but does not give an accurate value.For example, green is 105 190 150 instead of 0 255 0 .  I have to recognize the brown copper with the RGB value 138 73 49 .But it seems that I can not recognize this color with this method.I will be grateful if you can guide me.
#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8
int redPW = 0 ;
int greenPW = 0 ;
int bluePW = 0 ;

void setup() {
  // Set S0 - S3 as outputs
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);

  // Setting frequency-scaling to 20%
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);

  Serial.begin(9600);

}

void loop() {

// Calibration Values
int redMin=40;// Red minimum value
int redMax=470;//346 Red maximum value
int greenMin=40;// Green minimum value
int greenMax=510;//348 Green maximum value
int blueMin=30;// Blue minimum value
int blueMax=390;//262 Blue maximum value

int redValue;
int greenValue;
int blueValue;

//Read Red Pulse Width
digitalWrite(S2,LOW);
digitalWrite(S3,LOW);
// Read the output Pulse Width
redPW = pulseIn(sensorOut,LOW);
redValue=map(redPW, redMin,redMax,255,0);
delay(200);

// Read Green Pulse Width
digitalWrite(S2,HIGH);
digitalWrite(S3,HIGH);
// Read the output Pulse Width
greenPW = pulseIn(sensorOut,LOW);
greenValue=map(greenPW, greenMin,greenMax,255,0);
delay(200);

// Read Blue Pulse Width
digitalWrite(S2,LOW);
digitalWrite(S3,HIGH);
// Read the output Pulse Width
bluePW = pulseIn(sensorOut,LOW);
blueValue=map(bluePW, blueMin,blueMax,255,0);
delay(200);

// Print output to Serial Monitor
Serial.print("redValue = ");
Serial.print(redValue);
Serial.print(" - greenValue = ");
Serial.print(greenValue);
Serial.print(" - blueValue = ");
Serial.println(blueValue);

}

I'm not sure I really get your question, but it kind of sounds like what you want is to convert RGB to HSV and compare the hue against your target's hue, mostly irrespective of value and maybe to some degree saturation as well.

How do you perform the calibration? The spectrum of the light source is essential for the calibration! Is it a green LED?

Btw, did you take a look at the spectral sensitivity of the sensor on page 5? Your reading sound reasonable for a green LED...

How exactly are you calibrating a color sensor with only white and black?

As I said, you MUST either

know the spectrum of the light source that exposes your sample or
calibrate the sensor under the exact same light you use for detection later on.

However, the actual calibration values don't matter at all. It should be as simple as saving the value you get for copper as a reference and compare your test color with that value, including some margin, of course. Any sensor will always have specific/individual properties, like the spectral sensitivity in case of the TCS3200. But the reason of calibration is that you don't have to bother.


text:
How can I rename how my Arduino UNO (or any other Arduino) shows up on the computer?
I need to rename my Arduino UNO in a way that when it connects to the computer then it reads not as "Arduino" in device manager but as "My instrument name". I need to know how to do this on an UNO and Pro micro specifically but also on other arduinos. Please also suggest if there are other development boards available where names is not preprogrammed but programmable. Thank you.

For the Pro Micro, have you tried something like this (found by googling for "Arduino change PID")? For the Uno you would need to reflash the Atmega32u4 chip, that is responsible for the USB communication. Thats a bit more hacky, but there are tutorials for that online.

If "the computer" is a Linux computer you can create UDEV rules.  For example, you may, based on which USB port you plug your Arduino into, control most aspects of the USB connection.  In this way  you wouldn't have to change the PID or VID of the Arduino.  But the question should then be posted in a Linux stackexchange site.


text:
How to get the name of connected device over BLE?
I am implementing a BLE peripheral in my firmware with Arduino ESP32.
When the central gets connected to it, I'd like to log the name of the central & its address.
How can I do that?
#include <BLEServer.h>

class ServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
        ble.log("ServerCallbacks: Connected");

// ==> how can I add the connected device ID or name in the log?

        ble.deviceConnected = true;

        #if SUPPORT_LEDS_INDICATOR

        // === Show France flag colors
        // RGBW = 1,2,3, 4
        // CODE : BBWRR
        // CODE = 33411
        const String code = "BBWRR";
        ledIndicator.showAccessCode(code);
        #endif

        #if SUPPORT_BUZZER
        /// BLE connection jingle
        buzzer.playBleConnectedMelody();
        #endif
    };

    void onDisconnect(BLEServer* pServer) {
        ble.deviceConnected = false;
        ble.log("ServerCallbacks: Disconnected");

        #if SUPPORT_BUZZER
        /// BLE connection jingle
        buzzer.playBleDisconnectedMelody();
        #endif
    }
};

/// Somewhere in the setup:
server = BLEDevice::createServer();

// == Set up our calbacks
server->setCallbacks(new ServerCallbacks());

(Note: this is all just from reading the library source code, nothing has been tested).
You can't get the details of the just-connected-client. However you can get a list of the currently connected clients.
There is a function in the BLEServer class:
std::map<uint16_t, conn_status_t> getPeerDevices(bool client);

You can use that to get the list of connected clients. The "key" of the map is the connection id, and the "value" of the map is the "conn_status_t" struct, which includes a pointer to the peer device structure:
typedef struct {
    void *peer_device;
    bool connected;
    uint16_t mtu;
} conn_status_t;

You can keep your own list of "current" connection IDs and compare that to the "live" list when a new connection is made to find which is the new connection.
So you can take that peer_device pointer, cast it to a BLEClient pointer, then you call any of the normal BLEClient functions on that, including toString() which will return a string representation of the client.
That of course isn't the "name" of the client. I am not sure (not being an expert on BLE) how you get the name, but I think you may have to actively query it from the client, which should be perfectly possible now you have the BLEClient object pointer.


text:
ESP8266 soft resets when using a GPIO Expander
In my project I'm trying to use a PCF8574 to drive some peripherals, since the ESP8266 doesn't offer all the GPIO pins I need, however I seem to be having problems at the most basic level of driving the pins of an e-paper display.
The e-paper display is connected to MOSI, MISO and SCL to the "native" pins GPIO12, 13 and 14, and I wanted to rely on the PCF to drive the other four pins (CS, DC, RST, BUSY).
I modified the original library so that it could accept an arbitrary Pin abstraction that looks like the following:
class Pin {
public:
  Pin(void){};
  ~Pin(void){};

  virtual uint8_t read() = 0;
  virtual void write(uint8_t value) = 0;
};

and at first implemented it as ArduinoPin, which all it does is setting up the pin mode and calling digitalRead or digitalWrite when needed.
While connecting the EPD with the ArduinoPin implementation, using D0, D1, D2, D4 as pins, the e-paper display works correctly, so I proceeded to make another implementation of Pin with the GPIO Expander.
Following the GPIO Expander and relative Pin implementations
gpio-expander.h
class GpioExpander {
public:
  GpioExpander(uint16_t address);
  GpioExpander();
  uint8_t read(uint8_t pin);
  void write(uint8_t pin, uint8_t value);

private:
  uint8_t buffer[1] = {0xFF};
  uint16_t address;
};

class GpioExpanderPin : public Pin {
public:
  GpioExpanderPin(GpioExpander *expander, uint8_t pinNumber);
  ~GpioExpanderPin(void);
  virtual uint8_t read();
  virtual void write(uint8_t value);

private:
  uint8_t myPin;
  GpioExpander *expander;
};

gpio-expander.cpp
GpioExpander::GpioExpander(uint16_t address) {
  this->address = address;
  buffer[0] = 0xFF;
  Wire.beginTransmission(address);
  Wire.write(buffer[0]);
  Wire.endTransmission();
}

GpioExpander::GpioExpander() : GpioExpander(0x20) {}

uint8_t GpioExpander::read(uint8_t pin) {
  write(pin, 1);
  Wire.requestFrom(address, 1);
  buffer[0] = Wire.read();
  return (buffer[0] >> pin) & 1;
}

void GpioExpander::write(uint8_t pin, uint8_t value) {
  if (value == 1)
    buffer[0] |= (1 << pin);
  else
    buffer[0] &= ~(1 << pin);
  Wire.beginTransmission(address);
  Wire.write(buffer[0]);
  Wire.endTransmission();
}

gpio-expander-pin.cpp
GpioExpanderPin::GpioExpanderPin(GpioExpander *expander, uint8_t pinNumber) {
  this->expander = expander;
  myPin = pinNumber;
}

GpioExpanderPin::~GpioExpanderPin(void) {}

uint8_t GpioExpanderPin::read() { return this->expander->read(myPin); }

void GpioExpanderPin::write(uint8_t value) {
  this->expander->write(myPin, value);
}

These implementations work fine, I tested everything with a multimeter and I can arbitrarily write 1s and 0s on all 8 pins of the PCF, but when I try to drive the four pins of the e-paper, the ESP8266 resets and I have no clue on why. I tried with the exception decoder and the following stacktrace appears:
Exception Cause: Not found

0x40202984: Twi::read_bit() at ??:?
0x402029db: Twi::write_byte(unsigned char) at ??:?
0x40202b94: Twi::writeTo(unsigned char, unsigned char*, unsigned int, unsigned char) at ??:?
0x40202bb9: Twi::writeTo(unsigned char, unsigned char*, unsigned int, unsigned char) at ??:?
0x40202cc0: twi_writeTo at ??:?
0x40201720: TwoWire::endTransmission(unsigned char) at ??:?
0x40105cfe: os_printf_plus at ??:?
0x40201748: TwoWire::endTransmission() at ??:?
0x402017f5: GpioExpander::write(unsigned char, unsigned char) at ??:?
0x40201794: GpioExpanderPin::write(unsigned char) at ??:?
0x402011f9: Epd::spiTransfer(unsigned char) at ??:?
0x40201238: Epd::sendData(unsigned char) at ??:?
0x40201385: Epd::clear() at ??:?
0x402010b6: setup at ??:?
0x4020583c: std::_Function_handler<bool (), settimeofday::{lambda()#1}>::_M_manager(std::_Any_data&, std::_Function_handler<bool (), settimeofday::{lambda()#1}> const&, std::_Manager_operation) at time.cpp:?
0x4020583c: std::_Function_handler<bool (), settimeofday::{lambda()#1}>::_M_manager(std::_Any_data&, std::_Function_handler<bool (), settimeofday::{lambda()#1}> const&, std::_Manager_operation) at time.cpp:?
0x4020583c: std::_Function_handler<bool (), settimeofday::{lambda()#1}>::_M_manager(std::_Any_data&, std::_Function_handler<bool (), settimeofday::{lambda()#1}> const&, std::_Manager_operation) at time.cpp:?
0x4020583c: std::_Function_handler<bool (), settimeofday::{lambda()#1}>::_M_manager(std::_Any_data&, std::_Function_handler<bool (), settimeofday::{lambda()#1}> const&, std::_Manager_operation) at time.cpp:?
0x40202158: loop_wrapper() at core_esp8266_main.cpp:?
0x40100e85: cont_wrapper at ??:?

(Not sure why I can't get the source lines to appear, any suggestion in that is most welcome.)
Anyway apparently the problem appears when ending the I2C transmission, at the lowest level possible, at Twi::read_bit, which I include for the sake of all of you trying to help me out
core_esp8266_si2c.cpp
bool Twi::read_bit(void)
{
    SCL_LOW(twi_scl);
    SDA_HIGH(twi_sda);
    busywait(twi_dcount + 2);
    SCL_HIGH(twi_scl);
    WAIT_CLOCK_STRETCH();
    bool bit = SDA_READ(twi_sda);
    busywait(twi_dcount);
    return bit;
}

The most upsetting thing is that this same setup, when programmed in Micropython works just fine (I can't use Micropython though, because I need all the RAM I can get from the ESP to draw pictures, and I'm much interested in the overall performance I can get with C++).
Anyone had this same problem? Any advice on how to fix this behavior?
EDIT
With some experimentation, I managed to replicate the problem in a smaller scale. The following code resets the ESP8266 as well:
void setup() {
  Wire.begin();
  GpioExpander expander;
  GpioExpanderPin pin(&expander, 0);
  while(true) {
    pin.write(0);
    pin.write(1);
  }
}

It looks like fast cycles of on-off crash the system (which is what the EPD library does when sending data, turning on and off the pins relatively fast to switch between modes etc.). Not sure how to address this though, but I believe it might be something related to the Twi libraries at this point.
EDIT 2
Adding a yield() to the write function of the gpio expander class makes the issue go away, but the time to execute a simple display clear grows to unacceptable levels (~3 seconds to perform a full display refresh).
Any suggestion is appreciated at this point.
EDIT 3
I did some more experimenting and benchmarking, and reached the following conclusions:

the time that it takes for the Wire library to send data to the GPIO expander (the write function) is ~50µs
when using the gpio expander, the time to write data to the SPI device (DC write + enable CS + SPI transfer + disable CS) takes a total of ~170µs (which checks out, 3 times calling the gpio expander makes for ~150µs and the rest is SPI transaction)
when using the arduino pins, the time to write data to the SPI device takes ~10µs (an order of magnitude less than the GPIO expander).

To send a total of 150,000 bytes to the e-paper display, then, with the GPIO expander takes roughly 3 seconds, while with the normal pins it would take 10 times less (0.3 seconds).
The reset issue is surely due to the time spent in the send loop: the watchdog thinks the program is stuck in an infinite loop and thus resets the board. This is why the calls to yield remove the reset issues.
I believe I must either find a faster implementation of wire (?) or try to minimize usage of CS / DC pins

Are you sure you are decoding the stack trace with the right binary?

build, upload, run, crash, copy stack dump, decode in one pass so the decoder can use the elf file corresponding to the bin which was uploaded

@SimSon yes, I believe I am. I am building everything with platformio which outputs the final binary in .pio/build/nodemcuv2/firmware.elf, and that is the target I'm supplying to the exception decoder, which, by the way, is the jar one found here: https://github.com/littleyoda/EspStackTraceDecoder

You didn't post your code on how you create the instance of GpioExpander. But judging that your GpioExpander construct is conducting a Wire transaction, this will depend on where you create an instance of GpioExpander, if it is created before the setup() function, the Wire.begin() has not be established yet. It is better to create a GpioExpander::begin() method and move most of the code in the construct to the begin() method.

@hcheung sadly, that changes nothing. As I mentioned, the gpio expander works just fine, I can arbitrarily turn on and off pins. The issue only presents itself when using it with the epaper display.

I edited the question because I found out a way to replicate the issue. It seems fast duty cycles crash the system.

Adding yield() help to "feed the dog"... Maybe you should consider to use a different MCU, ESP8266 do not have a hardware i2c.

In the end the answer to the problem is the update frequency of the pins that drive the e-paper display:
The original waveshare library (as linked in the post) does the following to send data to the EPD:

enable DC (to tell the EPD that it's receiving DATA)
enable CS (to tell the EPD to listen to the incoming SPI data)
send SPI data
disable CS (to tell the EPD that anything received after that is not its competence)

Normally with arduino's digitalWrite this happens in a matter of ~10µs, and even if we repeat this process 15k times (that's how many bytes a 4.2 inch display supports) we spend 0.15 seconds to update half of the display's content (because the EPD has 2 memory banks which must be written).
When using the GPIO expander, instead, the mean time to send data via I2C is something around 50µs, which means that to enable / disable the pins three times we increase tenfold the time that the normal digital write takes (~150µs) which translates to 1.5 seconds to update half of the display and finally roughly 3 seconds for a full update.
During this loop, the watchdog thinks that the program is stalling and resets the chip. This is why using yield the update runs its course correctly.
To fix this issue, I worked on the EPD library and reduced the use of the digital writes, by creating a "session" of sorts: whenever I start writing data in a loop, I enable the CS pin, and disable it only at the end of the loop, so that the 100µs are only expended around the data transfer loop.
This is actually what happened in the Micropython driver for the e-paper display: the SPI connection sent data in chunks, enabling and disabling the chip select pin only at the beginning and end of the "transaction".
I'm planning to publish the updated library at some point, once everything is smoothed out, if this can interest anyone leave a message :)


text:
SIM800L stays in 1sec-blink-state
I've bought such on Amazon. My main problem is that it stays in 1sec-blink, meaning it can't registrer cellular network.
First I tried with all anntennas possiblities (one of each, both, none) - failed.
Using NodeMCU (for 3.3 TxRx) and SoftwareSerial.h to communicate. It answers all AT command as expected.
I tried several powering possibilities (as noted extensively about 2A on the internet), including 18650 , 2000mAh battery connected only to SIM800L module with no MCU connected, still same state.
What Can be done else?
SEE PELEPHONE:

is the SIM card valid?

@jsotola AT command replies with sim’s serial number, I guess it is ok

Are you connecting to a suitable network? Not all networks will work with SIM800L. GSM/GPRS is obsolete now and being gradually switched off by operators around the globe.

@Majenko See network properties (PelePhone)

You're with PelePhone? Well, 2G says "N/A". So no, simply no.

@Majenko Meaning that only 2G capable networks can apply?

Correct. https://en.wikipedia.org/wiki/2G -- For PelePhone you need an LTE or better modem.

@Majenko Thank you very much! Based on that table, can you point which carrier can I use using SIM800L (since neither are not 800, if it refered to freq).
THNX

The 800 in SIM800L does not refer to the frequency. The SIM800L works on 850/900/1800/1900MHz. So pretty much any 2G network.

Your mobile network provider does not provide a 2G (GPRS / GSM) network.
2G is graduallly being phased out around the globe, so switching to an LTE modem is really the way forward.
If you still want to use the SIM800L then you need a network provider that gives 2G services. Fortunately the SIM800L is a "quad band" modem, so it will work with pretty much any 2G provider (it works on 850/900/1800/1900MHz, hence the "quad" of "quad band").


text:
Wrong use of memory?
Probably I'm doing something wrong.
I'm writing an Arduino sketch for ESP32.
Among the others I have this function:
#define HDR_MAX_LENGHT 4
#define CMD_MAX_LENGHT 5
#define ARG_MAX_LENGHT 5
#define ARG_MAX_NUMBER 8

void ProcessLine(HardwareSerial *serial, char *line)
{
  int ret;
  int argc;
  char header[HDR_MAX_LENGHT + 1];
  char cmd[CMD_MAX_LENGHT + 1];
  char argv[ARG_MAX_NUMBER][ARG_MAX_LENGHT + 1];

  return; // for debugging
}

Usage example:
void loop()
{
    static char inBuf[64];

    if (Serial.available())
    {
      size_t size = Serial.readBytes(inBuf, 64);
      inBuf[size] = '\0';
      ProcessLine(&Serial, inBuf);
    }
}

In the last days all worked fine.
After adding other code, I noticed that sometimes my program "hangs": nothing runs. Perhaps it goes in an exception trap.
Commenting out the different sections of the code, I discovered that if I remove the declarations of the variables in ProcessLine() no more hangs happen.
The current RAM consumption is negligible: 0.5%.
During the tests NO serial data was received! So the function ProcessLine() was never called.
Hence, only the declaration of the variables lead to the "hang".
I wonder if there are some mistakes in the code above.
Otherwise, how I can further debug my code to understand what I've done wrong?

if size is 64 then you write \0 out of the array

@Juraj good catch, thanks. But as said I'm not sending any data right now.

Can you write a testable, minimal example that reproduces the issue?

@EdgarBonet unfortunately not because with a minimal example all works as expected (as said, in the beginning of the development there were no issues). For this reason I'm asking how to debug in addition to commenting out some part of the code.

This is just a guess, but what about compiler optimization? Try to turn optimization off and test again.

Modify optimize_level  in \hardware\arduino\avr\platform.txt. Acceptable values are  -O0 ,  -O1 ,  -O2 ,  -O3 ,  -Os  and  -Ofast . Default is  -Os .

There is nothing wrong with these declarations. The fact that the program works when you comment out some lines of code does not mean that these lines are causing the problem. It looks like you may have triggered undefined behavior somewhere. When this happens, the behavior of the program becomes unpredictable, and can depend on changes to parts of the code that are completely unrelated to the actual problem. A typical example is memory corruption.

As I said in a comment, there is nothing wrong with these declarations.
Now, here are some debugging strategies you may try:

You can rebuild your program with all compiler warnings enabled. Look
carefully at the compiler messages and investigate any warning you
see.

You can continue with your current strategy: put back those
declarations, then try to remove something else. You may find that
there are multiple pieces of code that, when removed, make your
program work again. Chances are the problem resides in one of those
pieces. But then, it may be that the problem is in the interaction
between multiple pieces rather than in one specific piece.

You may just read the code carefully and see if you spot something
suspicious. This can work sometimes: see how @Juraj spotted a buffer
overflow in your code snippet just by reading it.

You can add debug messages across your program, to check what
branches are executed, the values of variables...

I don't know the ESP32 dev environment, but you can check whether the
compiler supports adding “sanitizers”. These are pieces of code added
by the compiler that do run-time checks on your program, and report
problems as they happen. You may want to enable at least an address
sanitizer and an undefined behavior sanitizer.

If the environment supports it, you can try to run the program in a
debugger. No success guaranteed: if the program corrupts its memory,
it may crash in some place unrelated to the actual problem. The
debugger will tell you where it crashed, which may not be very
helpful in this case.

If the ESP dev environment supports neither 5 nor 6, you may try to
run your program on your PC. There are a couple of Arduino-compatible
cores that you can download for running on a PC.


text:
Problem with messuring capacitance with 50 Arduinos connected by I²C
I want to measure changes in capacitance over time. One Arduino is used per capacitance sensor. There is one anode per Arduino and a total of one common cathode (see the picture)
With four Arduinos connected in series via an I²C master-slave connection, successful results were obtained.
With more than four Arduinos, all measurement results were 0, because no voltage is measured at the input pin anymore.
I then lowered the reference voltage for analogRead. So 10 Arduinos in series were possible. However, the measured values are clearly lower. However, no absolute values are to be measured, but any difference in the capacitance is sufficient. Finally 50 Arduinos should be used.
I have thought of the following possibilities:

reduce the reference voltage further, but this may reduce the measurement results further, so that no deflection is measured.
increase the output voltage at the Arduino via an operational amplifier to compensate the voltage drop.

How could I proceed to get a usable result with all 50 Arduinos? The code I used is to be found below.

Master
#include <Wire.h>

volatile byte x1, x2;
volatile int val_slave;

const int OUT_PIN = A0;
const int IN_PIN = A2;

#define nodeMax 10
#define nodeStart 2

void setup() {
  analogReference(DEFAULT);
  Wire.begin();

  pinMode(OUT_PIN,OUTPUT);
  pinMode(IN_PIN,OUTPUT);

  Serial.begin(9600);
  // put your setup code here, to run once:

}

  void loop() {

    pinMode(IN_PIN,INPUT);
    digitalWrite(OUT_PIN,HIGH);

    int val = analogRead(IN_PIN);

    digitalWrite(OUT_PIN,LOW);
    pinMode(IN_PIN,OUTPUT);

    Serial.print(val);
    Serial.print(",");

      delay(10);

    for (int node = nodeStart; node <= nodeMax; node++) {

        // Ask the slave to release the input pin.
        Wire.beginTransmission(node);
        Wire.write(0);
        Wire.endTransmission();
        delay(10);  // give it time to do so

        // Charge the capacitors.
        digitalWrite(OUT_PIN, HIGH);

        // Ask the slave to read val.
        Wire.requestFrom(node, sizeof(val));

        // Discharge.
        x1 = Wire.read();
    x2 = Wire.read();

    val_salve = (int)x1 << 8 | (int)x2;

        Serial.print(val_slave);
        Serial.print(",");

        digitalWrite(OUT_PIN, LOW);
        delay(10);

    }
    Serial.println();
    delay(50);
}

Slave
const int IN_PIN=A2;

#include <Wire.h>
#define node 10

void setup() {
    // ...
    analogReference(DEFAULT);
    Wire.begin(node);
    Serial.begin(9600);

    pinMode(IN_PIN,OUTPUT);

    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);

}

// Release IN_PIN when the master sends a message.
void receiveEvent(int byte_count) {
    pinMode(IN_PIN, INPUT);
    while (byte_count--)
        Wire.read();  // discard the received message
}

void loop ()
{
}

void requestEvent() {
    int val = analogRead(IN_PIN);
    // transmit the result... then

    Wire.write(highByte(val));
    Wire.write(lowByte(val));

    pinMode(IN_PIN, OUTPUT);  // discharge
}

You will need to massively reduce the pullup resistors on your I2C bus to counteract the increased gate capacitance of the number of devices. The more devices you have the lower the pullup resistors. After a while it becomes impractical to reduce the pullup resistors any more and you hit a limit on how many devices you can have on the bus. I would say 50 devices is far more than any sensible bus could cope with.

Is there any reason you are using 50 Arduinos rather than 4 Arduinos connected to 8-port multiplexers? That would reduce cost and also avoid your problem.

"Finally 50 Arduinos should be used" - why? Isn't this creating the problem you are trying to solve?

The cathode line is being shared by all the Arduinos' OUT_PIN. When
one of them tries to set the pin HIGH, all the others are trying to
hold it LOW. This is a short-circuit condition that can damage the
Arduino's outputs. Even if they do survive, the voltage on the line will
be significantly below 5 V because of those Arduinos pulling the
line LOW. The more of them pull the line LOW, the lower the voltage
will be.
The simple solution would be to change the protocol such that only the
Arduino that is currently making a measurement can pull that line, while
the others keep their OUT_PIN in high-impedance mode (i.e. INPUT).
This is fragile because... bugs happen, and you may still be making a
short-circuit. A more robust solution would be to connect only the
master to the cathode, and give it the responsibility to drive the line
HIGH and LOW.
Now, a coupe of unrelated comments:

A float is four bytes: there is no point in transmitting ten bytes.

You can measure up to four capacitors with each Arduino (pins A0
through A3, you can use a digital pin for OUT_PIN), it is wasteful
to use one Arduino per capacitor.

Edit: If only the master controls OUT_PIN, then some communication
protocol is needed in order to synchronize it with the slaves, so that
they can release IN_PIN at the right time. The simplest protocol I can
think of is the following: when the master sends something (anything)
to a slave, this message means “please release IN_PIN now”.
Here is some untested code implementing this idea:
master:
void loop() {
    // ...
    for (int node = nodeStart; node <= nodeMax; node++) {

        // Ask the slave to release the input pin.
        Wire.beginTransmission(node);
        Wrire.write(0);
        Wire.endTransmission();
        delay(10);  // give it time to do so

        // Charge the capacitors.
        digitalWrite(OUT_PIN, HIGH);

        // Ask the slave to read the capacitance.
        Wire.requestFrom(node, sizeof(capacitanceSlave));

        // Discharge.
        digitalWrite(OUT_PIN, LOW);

        // ...
    }
}

slave:
void setup() {
    // ...
    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);
}

// Release IN_PIN when the master sends a message.
void receiveEvent(int byte_count) {
    pinMode(IN_PIN, INPUT);
    while (byte_count--)
        Wire.read();  // discard the received message
}

void requestEvent() {
    int val = analogRead(IN_PIN);
    // transmit the result... then
    pinMode(IN_PIN, OUTPUT);  // discharge
}

In an I2C configuration no-one sets the output high. The pull-up resistors do that.

@NickGammon: I am talking about the line labeled “cathode” in the drawing, not about the I2C SDA.

OK. The "circuit diagram" wasn't all that clear.

@Eggar Bonet: First of all thanks for the answeres,
i tried your suggestion by only connecting the master to the cathode and changing the code, but it didnt work. the sensor conected to the master gives a way better capacitance output, but the slaves output is "nan".
I have to use one arduino per Sensor because in previouse scientific works two sensors interferre on one Arduino and the results are bad.

@Imogdia: There must be something wrong with either your updated circuit or your updated code. You may want to update the question in order for it to reflect the current circuit and code.

@Imogdia: With the updated code, the slaves are still pulling down on OUT_PIN. And they release IN_PIN after the master has set OUT_PIN to HIGH, which is too late. You need a more elaborate communication protocol, where the master tells the slave when to release IN_PIN.

And how do I can do this?
Im totally new to arduinos and i have no programming experience

@Imogdia: See expanded answer.

I´ve tested your code (see updated threat), but the outcome is still the same.
i´ve tested your code on 10 arduinos and the results are these:
only the master gets a messurement
12:22:21.472 -> 1.38,45,nan,nan,nan,nan,nan,nan,nan,nan,nan,
12:22:21.710 -> 1.38,45,nan,nan,nan,nan,nan,nan,nan,nan,nan,
12:22:21.947 -> 1.41,46,nan,nan,nan,nan,nan,nan,nan,nan,nan,
12:22:22.186 -> 1.38,45,nan,nan,nan,nan,nan,nan,nan,nan,nan,
12:22:22.426 -> 1.38,45,nan,nan,nan,nan,nan,nan,nan,nan,nan,
12:22:22.700 -> 1.38,45,nan,nan,nan,nan,nan,nan,nan,nan,nan,

@Tizian: 1. Your slaves are still driving OUT_PIN. 2. They are not sending anything (my comment // transmit the result... was meant to be replaced by your result-transmitting code). 3. Why call Wire.onRequest() twice? 4. Try sending a fixed value (e.g. 12.34) to rule out a communication problem. 5. Why not send the raw ADC reading instead of the computed capacitance?

@EdgarBonet I´ve updated my code again. Thanks for your help! im gonna test it tomorrow and can tell you if it worked.

@EdgarBonet It worked perfectly, thank you for your help!

The I²C bus was never intended as a distribution bus between many computers. The outputs are not designed to drive long wires. With a lot of kludging you may get this to work, but it is definitely not repeatable or reliable.
Consider something else. CAN can do maybe 60 nodes, depending on the transceiver chosen. It is relatively inexpensive.

You might want to consider using a RS485 protocol. Unlike I2C this uses "balanced" wiring so is more suitable for longer cable runs.
I described a way of coding a number of Arduinos using a "rolling master" protocol here - this lets you connect a considerable number of Arduinos to the two wires, and they take turns to send the data.
However in your case, since you are measuring capacitance (not capacity?) then each of your Arduinos can measure 6 (or possibly more) analog readings, so you don't need 50, you need 50/6 = 8.33 Arduinos (OK, nine).
The Arduino Micro, for example, has 12 analog input channels, so you would only need 4 (to get 48 inputs) or 5 (to get 60 inputs). Then you could stick to I2C.

I recommended CAN because of the 50 nodes, RS485 has a limit of 32. To extend beyond that repeaters are needed.


text:
Connect to 8Base API with TLS on Arduino Uno Wifi Rev2
I'm trying hit some endpoints on the 8Base API with the Arduino Uno Wifi Rev2. I was able to get this API call to work with Postman, but I've had no luck once I convert it to my Arduino code. In Postman, clicking the "Code" button reveals that this is what the successful Postman request looks like:
POST /MY_PATH HTTP/1.1
Host: api.8base.com
Authorization: Bearer MY_TOKEN
Content-Type: application/json
Content-Length: 64

{
    "query": "{ listOfMachinesList { items{ machineID } } }"
}

Here's what the relevant parts of my Arduino code look like after translating this API call into my Arduino:
#include <ArduinoJson.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include <Arduino.h>

WiFiSSLClient client;
char server[] = "api.8base.com";

const String requestBody = "{\"query\": \"{ listOfMachinesList { items{ machineID } } }\"}";
int status = WL_IDLE_STATUS;

void setup(){
  Serial.begin(9600);
  Serial.println("Starting");
  status = WiFi.begin(WifiSSID, WifiPassword);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Waiting for connection");
  }

  Serial.println("Connected to wifi");
  attemptConnect();

}

void attemptConnect() {

  Serial.println("\nStarting connection to server...");

  if (client.connectSSL(server, 443)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.print("POST /MY_PATH HTTP/1.1");
    client.println("User-Agent: Arduino/2.2.0");
    client.print("Authorization: Bearer ");
    client.println(String(APIKey));
    client.println("Content-type: application/json");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: keep-alive");
    client.println();
    Serial.println("finished POST request");
  } else {
    Serial.println("didn't connect");
  }

}

The connection appears to fail on"client.connectSSL(server, 443)" before it can get inside the "if". My Serial Monitor shows the "didn't connect" message. Further, I added some additional Serial.println statements inside the connectSSL function. It looks like the connection fails in a function called void ServerDrv::startClient'", specifically here:
 if (!SpiDrv::waitResponseCmd(START_CLIENT_TCP_CMD, PARAM_NUMS_1, &_data, &_dataLen))
 {
        WARN("error waitResponse");
 }

I added the certificates from both api.8base.com and 8base.com following the instructions here: https://support.arduino.cc/hc/en-us/articles/360016119219-How-to-add-certificates-to-Wifi-Nina-Wifi-101-Modules-
Using this code and the certificate instructions above, I was able to connect to google.com on port 443, but no luck with 8base. I know that 8base uses GraphQL for their connections, but I was able to hit another GraphQL endpoint on a different, non-SSL server. I also checked to see if 8base was using a non-standard port, but, according to Postman, it is using 443. I'm a little confused why I can't get past the connectSSL function. On the surface, it seems like it should behave the same way as it does when I connect to Google, but there must be something else going on that I'm missing. Any help would be greatly appreciated!

I am passing this along to our support team to take a look. Please send me an email so we can be in touch at albert@8base.com. Thanks and best of luck! Albert

Thanks, Albert! I'll reach out over email

Unfortunately, our 8base team doesn't have much knowledge/content around C++. That said, I'd check out the following.

Here's a high-level HTTP client for Arduino that's modeled after the browser fetch API: https://github.com/instanceofMA/arduino-fetch

You wrote the API string as "api.8base.com". Try it with the full API endpoint; "https://api.8base.com/WORKSPACE_ID" (where is your workspace ID?)

LMK if this helps.

Thanks for the reply! Unfortunately, it looks like that library is only for ESP8266 and ESP32 modules. I was using the Arduino Uno Wifi Rev 2. I tried adding the workspaceID and got the same result. I was adding the workspaceID    in the client.print("POST /MY_PATH HTTP/1.1"); line. That seemed to work with another GraphQL request. Maybe I'm missing something important about how the 8base API is setup, though

Hmmm...yeah the 8base API is a very standard implementation of a GraphQL API. We didn't implement anything funky as far as I know! Would you be able to try deploying a webhook function and seeing if you're able to get a response from a HTTPS GET request?

I gave that a shot, as well. I also tried with a new free-tier account to make sure that it wasn't simply an issue with that account. I still can't get past the client.connectSSL(server, 443) line, unfortunately. Do you know if any other customers have connected to their endpoints with an Arduino?

Unfortunately, I don't. We do not have a way of determining what devices incoming traffic to workspaces originates from. Also, even if we did, we couldn't share it lol! You're the first to reach out regarding this. So please keep us informed on the process and I'll keep digging as well.