text:
POST request (HTTPClient) with ESP8266 not working on localhost (http code = -1)
I've been looking around for a solution, but couldn't manage to find one. I'm looking to send a post request from an ESP8266 on a local API.
Here is my code :
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

String ssid = "HUAWEI P30 lite";
String password = "testazerty";
String serverName = "http://192.168.56.1:3030/drink/voltron";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

    if(WiFi.status()== WL_CONNECTED){
      WiFiClient client;
      HTTPClient http;

      http.begin(client, serverName);

      http.addHeader("Content-Type", "application/json");
      int httpResponseCode = http.POST("{\"city\":\"toronto\"}");

      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);

      http.end();
  }
}

Both my computer and ESP8266 are connected to my phone network (HUAWEI).
192.168.56.1 is the IP of my computer.
API is running, and I can successfully make the request from postman (see image below).

It always return -1 as http code. I activated debug level HTTP_CLIENT, here is what I have on the serial monitor :
11:07:41.645 -> SDK:2.2.2-dev(38a443e)/Core:3.0.2=30002000/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-48-g7421258/BearSSL:6105635
11:07:41.645 -> fpm close 1
11:07:41.645 -> mode : sta(30:83:98:b1:da:62)
11:07:41.645 -> add if0
11:07:41.645 -> Connecting
11:07:42.160 -> .....scandone
11:07:45.348 -> state: 0 -> 2 (b0)
11:07:45.348 -> .state: 2 -> 3 (0)
11:07:45.441 -> state: 3 -> 5 (10)
11:07:45.441 -> add 0
11:07:45.441 -> aid 6
11:07:45.441 -> cnt
11:07:45.441 ->
11:07:45.441 -> connected with HUAWEI P30 lite, channel 6
11:07:45.441 -> dhcp client start...
11:07:45.864 -> ....ip:192.168.43.88,mask:255.255.255.0,gw:192.168.43.1
11:07:47.870 -> .
11:07:47.870 -> Connected to WiFi network with IP Address: 192.168.43.88
11:07:47.870 -> [HTTP-Client][begin] url: http://192.168.56.1:3030/drink/voltron
11:07:47.870 -> [HTTP-Client][begin] host: 192.168.56.1 port: 3030 url: /drink/voltron
11:07:47.870 -> [HTTP-Client][sendRequest] type: 'POST' redirCount: 0
11:07:53.021 -> [HTTP-Client] failed connect to 192.168.56.1:3030
11:07:53.021 -> [HTTP-Client][returnError] error(-1): connection failed
11:07:53.021 -> HTTP Response code: -1
11:07:53.021 -> [HTTP-Client][end] tcp is closed

firewall on PC?

I completely turned off Windows Defender, but still have the same output

Can your PC ping the ESP32?

I tried to do it connecting to my home router, and it worked perfectly !
The problem comes from sharing internet with my mobile, but at least it can work with router. I looked it up, and seems that it might be because of the protocol used (IPv4/IPv6). Here is what I found.

localhost is the device itself ... synonymous with 127.0.0.1 ... did you mean to say local host instead?

try to Disable your windows firewall or add exption to allow access

You are on different subnets. Your API is 192.168.56.1 and your device is 192.168.43.88, but your subnet mask is 255.255.255.0. That puts these devices on separate subnets within the network. Try changing your subnet mask to 255.255.0.0. Reference: http://www.steves-internet-guide.com/subnetting-subnet-masks-explained/

TLDR:
This is a networking problem, not a programming problem. Try changing your subnet mask to 255.255.0.0 on your router/network configuration, or make sure they're actually connected to the same router. If different routers, try to change one to a "Wireless Access Point" configuration. If you can't get them on the same network, you will have to expose your API to the Internet.
Long version:
You are on different subnets. Your API IP address is 192.168.56.1 and your device IP address is 192.168.43.88, but your subnet mask is 255.255.255.0. That puts these devices on separate subnets within the network.
There are a lot of complicated explanations of subnets and subnet masks on the internet. I linked one of the better ones below. Technically, you are not just on different subnets but on different networks entirely. You have a 192.x.x.x IP address, making it a Class C network. That makes your address pattern one of "network.network.network.node". Depending on your router configuration or other network hardware, you can upgrade it to a Class B network by customizing your subnet mask as 255.255.0.0 ("network.network.node.node"). Class B addresses might require a lot of customization on your end depending on your specific circumstances. By using a subnet mask of 255.255.0.0 on a Class B address, you classify the IP address parts .56.1 and .43.88 as being on the same network AND subnet. If you change it to Class B addressing without changing the subnet, the .56 will be one subnet and .43 will be a different subnet.
Sometimes this addressing is done automatically based on the installed hardware. This is especially problematic in home networks containing multiple wireless routers but connected to the same modem. Many home routers have a "Wireless Access Point" setting that removes a lot of the more complex router configuration. This might convince your router(s) to put you onto the same subnet. If that works, you now have your devices able to connect locally! Additional router configuration might be required to expose ports for your API to incoming requests across subnets.
If your network class is being determined by your ISP and you can't get your devices onto the same network, you have to expose your API to the Wild Wild Web :D There are many services which allow for Dynamic DNS, but I'd suggest reading through https://www.ionos.com/digitalguide/server/tools/free-dynamic-dns-providers-an-overview/ and selecting one that meets your needs. This WILL require advanced router configuration to expose ports to the internet. Please select a Dynamic DNS services that provides DDOS protection. Once it is exposed, your ESP8266 can hit your API as it would any public API. Please put authentication on your API.
References:

Subnet explanation -
http://www.steves-internet-guide.com/subnetting-subnet-masks-explained/
Dynamic DNS providers -
https://www.ionos.com/digitalguide/server/tools/free-dynamic-dns-providers-an-overview/


text:
Is there any way to export a sketch from an Arduino to my laptop?
I was having a sketch but I accidentally downloaded a file which was containing a virus. That virus deleted all my Arduino sketches. I uploaded a sketch into my Arduino UNO and it is still in there.
Is there any way to get it back?

No. The sketch is not on the Arduino. The compiled binary code is on the Arduino. The sketch is gone. Don't you have a backup?!

As Majenko said you can never get the original sketch back from the Arduino, since it is compiled first to assembler and then to binary machine code. You can only get back that binary machine code. Then you can use a decompiler to get a corresponding assembler code. Though that won't be anything like a sketch. Especially the symbols (variable names etc) are totally gone. And it sounds like getting the machine code won't help you.

Like the others said. If you lost something you put a lot of effort into, it may be worth taking the time to run something like TestDisk to scrape the drive for chunks of text and then and grep the results for Arduino-related substrings, e.g. "Serial.print". This assumes they haven't been overwritten. If you try that and have questions about it, it's probably in the domain of superuser. If you had a complex project, the odds of success and required effort might be worth it. It wouldn't be particularly fun to do though.

source: Stack Exchange

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

sort: votes


text:
Why must I detach the Arduino from the computer when making adjustment to the circuit?
I am new to Arduino and am reading Learn Electronics with Arduino: An Illustrated Beginner's Guide to Physical Computing. On page 118, it says:

Remember, whenever you make adjustments to a circuit, your Arduino should not be attached to your computer.

To give more context, it means when you make adjustment to the circuit on the breadboard, you should detach the USB cable from the computer.
I am wondering why?
Is it because a short circuit can crash my computer similar to how the USBKill works? Are there other reasons?

Arduino should not be attached to your computer. that is misleading ... it should say Arduino should not be powered.

Is it because a short circuit can crash my computer ...

It is more that you don't want an inadvertent mis-routing of cables to burn out your chips while they are powered.
I wouldn't personally be making changes to a breadboard circuit while it is powered. It is better to do it un-powered, and then check it over, than wonder why there is smoke coming from it.

"Adjustments to a circuit" can mean removing, adding or repositioning components on the breadboard. One can accidentally position a component lead in an incorrect location on the board, creating a circuit that is undesirable and possibly damaging to the assembled project.
If the misplaced lead or leads are in a particularly unsuited location, the circuit can include the USB portion of the system. The probabilities are low that one would accidentally damage that specific set of traces, or send voltage where it should not be, but they are non-zero. Even if one damages the Arduino, the cost is low compared to a damaged USB port or computer.
If you've been creating simple Arduino circuits and have misplaced or mis-routed a lead or component, you've learned how easily that can happen. Disconnecting the USB is comparably a minor inconvenience.

Is it because a short circuit can crash my computer

More than crashing it, there is some risk that a short-circuit on your board could cause damage to the computer's USB port that is powering it. Most computers have overload protection on their USB ports but you don't want to test it unnecessarily, risking permanent damage to the port.

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


text:
Need help with Bluetooth component for TinyCircuit
I am looking to get some assistance to learn how to program the Bluetooth module for TinyCircuits.
I am currently using the UARTPassThrough.ino example to try and learn BlueNRG's functions.
I see that in the UARTPassThrough.ino code, the loop() function calls the aci_loop() function in UART.ino. I'm not too sure what are ACI commands. What does the aci_loop() function do for its Bluetooth functionality?
void aci_loop() {
  HCI_Process();
  ble_connection_state = connected;
  if (set_connectable) {
    setConnectable();
    set_connectable = 0;
  }
  if (HCI_Queue_Empty()) {
    //Enter_LP_Sleep_Mode();
  }
}

Also, when I try to use the aci_gap_start_general_discovery_proc() function, the value returned is 255. What does the value 255 mean?
Main .ino file:
void setup() {
  SerialMonitorInterface.begin(9600);
  while (!SerialMonitorInterface); //This line will block until a serial monitor is opened with TinyScreen+!
  BLEsetup();
}

void loop() {
  aci_loop(); //Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short.
  BLEdiscoverymode();
}

Added own function to UART.ino file:
void BLEdiscoverymode() {
  uint8_t output;
  output = aci_gap_start_general_discovery_proc(0x4000, 0x4000, 0x00, 0x01);
  PRINTF("--Bluetooth function return value: %d--\n", output);
}

Output from Serial Monitor
03:44:21.572 -> --Bluetooth function return value: 255--
03:44:23.774 -> --Bluetooth function return value: 255--
03:44:25.989 -> --Bluetooth function return value: 255--
03:44:28.208 -> --Bluetooth function return value: 255--
03:44:30.407 -> --Bluetooth function return value: 255--

Help would be much appreciated.
My TinyCircuit uses these components:

TINYZERO PROCESSOR BOARD

TINYSCREEN OLED TINYSHIELD

BLUETOOTH LOW ENERGY TINYSHIELD (ST)
(Uses the BlueNRG-MS chipset with the SPBTLE-RF module)

Lithium Ion Polymer battery - 3.7V 150MAH

Why are you asking the same question again? If you have new information you should edit it into the original question instead of asking a new one

You may be better off asking the authors through a github issue since they are far more likely to know what this does than we do (since this is some unknown third party board and library and not something many other Arduino users even know exists, let alone have a clue how to use).


text:
USB serial port no longer detected after successful upload
I successfully uploaded a sketch to my Arduino Micro using the USB serial port but if I try to change the sketch that port is not available. The sketch I uploaded on the Micro runs fine when I plug in the USB cable. The ports shown are /dev/cu.Bluetooth-Incoming-Port and /dev/cu.wlan-debug. If I plug in a different chip the port is there. What would cause it to disappear for the Micro?

You are probably encountering a very common problem which is already answered on here. Does your non-working Arduino appear in your USB hardware list briefly after reset?

You are simply running a sketch that doesn't create and expose a serial port to the computer.

I'm not sure what that means but more importantly, what can I do to be able to upload new sketches (and avoid this issue in the future)?

Problem fixed by following suggestion from namakada81 "Open an empty arduino sketch, select the pro micro and no port, click upload and as soon as the ide says "uploading" reset the arduino

Who is namakada81?

All I know is that someone with this username posted this solution on reddit 3 years ago https://www.reddit.com/r/arduino/comments/cliro2/how_to_reset_arduino_pro_micro_bootloader/


text:
L LED keeps staying on
I am trying to get the Arduino to reboot my PC when it is off.
Using the front panel header on the PC, I connected the power switch and PLED directly to the Arduino Uno as the header only outputs 5 V.
I'm able to check the status using the L LED, but once I connect the power switch pins to the Arduino to turn on the PC the L LED is always on. This kind of defeats the purpose of what I was trying to do as I wanted the L LED to be off when the PC is off and on when the PC is on, similar to how the LED on the PC power button works.
If someone can give their insight please, the code and pin diagram is below.
const int ledPin = 13; // LED on arduino should be on when PC is on and off when PC is off
const int pwrPin = 8; // attached to power switch to turn on and off PC
const int PLED = 7;

void setup() {
  Serial.begin(9600);  // initialize serial communication:
  pinMode(PLED, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(pwrPin, OUTPUT);
}

void loop() {
  int status;
  status = digitalRead(PLED); // reads the status of PLED
  if (status == HIGH) { // if PC is on keep on until Python script shuts down PC.
    digitalWrite(ledPin, HIGH);
    Serial.print("PC is on");
    delay(5000);
  }
  else { // when PC is off, arduino should turn back on to cold reboot the PC
    digitalWrite(ledPin, LOW);
    Serial.print("PC is off. Turning on in 10 seconds");
    delay(10000);
    // Added Code. Emulates pushing the PC button when PC is off
    digitalWrite(pwrPin, LOW);
    delay(500);
    digitalWrite(pwrPin, HIGH);
  }
  delay(500);
}

The little box with circles is the front panel header on the mobo.

what's an L LED?

@jsotola The Arduino built in LED.

why is it called ledPin in your code?

what is printed in the serial console? ... please copy and add to your question

why are you assuming that there is something wrong with the LLED? ... maybe your code is working correctly

Did I understand right in that the LED correctly showed the status of the PC, until you finally connected the power switch pins to the Arduino? Please clarify. If this is correct: How exactly did you connect everything?

@chrisl Yes, that is correct. When I disconnect the power switch pins the LED works as intended: ON when the PC is on and OFF when the PC is off. Yet, when I put the power switch pins in, the LED is always turned on. I edited my post to show the pin connections.

Can you try it again with connecting to the power switch pins, but configuring the pwrpin as INPUT? It won't turn your PC on that way but INPUT makes a pin high impedance (electric equivalent of an unconnected pin) and I want to check if that changes something (and maybe find something about the core problem)

@chrisl I've tried that before, but I just took another crack at it and same thing happened. Separately, I have tried running just the code to turn on the PC on another file and I found that setting the pwrpin to OUTPUT works , but INPUT does not. Which is why I set pwrpin as OUTPUT in my main code. Hope this information is useful.

@chrisl Also, I don't know if this will help or if you already know this but the pwr switch outputs 5v at anytime even when the PC is off. When I turn off the PSU, the pwr switch has no voltage and the built-in LED turns off.

@Ant, the power switch is connected between ground and power-on signal line ... the power-on signal is most likely pulled towards 5 V with a pullup resistor ... the switch pulls it to ground when the switch is pressed

Did you check the circuit internal to the motherboard, how the LED is controlled? Chances are that "PLED-" is switched, not "PLED+", so that connecting "PLED-" to GND as you did will make it on all the time. Measure the pins on the PC's header, for example.

@thebusybee I know that when the PC is on PLED is measured at 5v and 0v when the PC is off. Is that what you're talking about?

@jsotola would that be a potential cause for the built-in LED to be always on?

Hm, which of both PLED pins do you mean? -- What do you measure at "PLED-" if the PC is on, what if the PC is off, and what do you measure at "PLED+" the same time? Do not connect the Arduino and use "GND" as reference. Please add these four values to your question by [edit]ing it.

The led power pins on the motherboard you are connecting to are not "power led+" and "power led-", they are "led+" for two separate leds (specifically meant for a green led and a yellow led). See this page for the pinout used by Intel.
All the leds use the a common ground for "led-". By connecting it as you have, you are shorting out one of the led pins. Disconnect that pin from ground and you should be able to read the other pin correctly.


text:
I want a Rotary Encoder to make 10 steps at once, but my code isn't working. What am I doing wrong?
I'm using a rotary encoder on my Arduino Micro, that is supposed to do single steps or ten steps at once, depending on which position a switch is in.
The Rotary: https://www.reichelt.de/drehimpulsegeber-15-impulse-30-rastungen-vertikal-ec11mvbfx-p315144.html?&nbc=1 (on this site are pictures and datasheets as well.)
The Switch:
https://www.reichelt.de/miniatur-kippschalter-ein-aus-ein-3-a-250-v-goobay-10023-p285990.html?&nbc=1
Wiring: (image following later)

        1--------Pin16 |  Pin A3----Switch
Rotary  2--------GND   |  GND-------|
        3--------PIN17 |

The rotary encoder gives no output, neither the Serial.print nor the gamecontroller. Also there is no output in either switch position.
EDIT:
After using arrays and loops like @jsotola teached me, it works nearly the way its supposed to, but sometimes, although the switch is off, it clicks ten times.
The code looks like this shortened now
#include <Arduino.h>
#include <Joystick.h>
#include <BasicEncoder.h>
#include <TimerOne.h>

int EncoderPins[] = {
  4, 5, 6, 7, 8, 9, 10, 11
};
int EncoderCount = 8;

BasicEncoder encoder4(EncoderPins[6], EncoderPins[7], HIGH, 2);

void timer_service() {
  encoder4.service();
}

#define joyButton16 EncoderPins[6]  // Rotary4
#define joyButton17 EncoderPins[7]  // Rotary4
#define joyButton18 21              // HDG_SWITCH := Switch to select between single and 10 steps

//Joystick(Joystick HID ID, Joystick Type, Button Count, Hat Switch Count, Include X, Include Y, Include Z, Include Rx, Include Ry, Include Rz, Include Rudder, Include Throttle, Include Accelerator, Include Brake, Include Steering)
Joystick_ Joystick(0x15, JOYSTICK_TYPE_JOYSTICK, 19, 0,
                   true /*X*/, false/*Y*/, false/*X*/,
                   false/*Rx*/, false/*Ry*/, false/*Rz*/,
                   false/*Rudder*/, false/*Throttle*/, false/*Acc*/,
                   false/*Brake*/, false/*Steer*/);

const bool initAutoSendState = true; // code is sends continuously and doesnt wait for polling

int EncoderState[] = {
  0, 0, 0, 0
};

void setup() {
  for (int q  = 0; q < EncoderCount; q++)
  {
    pinMode(EncoderPins[q], INPUT_PULLUP);
  }

  Serial.begin(9600);
  Joystick.begin();

  Timer1.initialize(100);
  Timer1.attachInterrupt(timer_service);
}

void loop() {
  GET_CHANGE();

  int CurrentButton18State = !digitalRead(joyButton18);
  switch(CurrentButton18State){
    case 0:
      switch(EncoderState[3]){
        case  1: clickButton(15); Serial.println(EncoderState[3]); break;
        case -1: clickButton(16); Serial.println(EncoderState[3]); break;
        } break;
    case 1:
      switch(EncoderState[3]){
        case  1: clickTen(15); break;
        case -1: clickTen(16); break;
        } break;
  }
}

void clickButton(int pin) {
  Joystick.setButton(pin, 1);
  delay(2);
  Joystick.setButton(pin, 0);
}

void clickTen(int pin) {
  for (int ii = 0; ii < 10; ii++)
  {
    clickButton(pin);
    Serial.println("step: "); Serial.println(ii);
    delay(10);
  }
}
void GET_CHANGE()
{
  for(int E = 0; E<4; E++)
  switch(E) {
    case 3: EncoderState[E] = encoder4.get_change(); break;
  }
}

Please reduce the code to the minimum that produces the behaviour you describe. Is this code meant for the Arduino Uno? If so, Arduino pin A3 (your switch pin) is physically the same as pin 17 (one of your encoder pins). Pins 0 and 1 are the Serial RX/TX pins, which you can't use for other things if you need input/output on the Serial port.

@StarCat, it says Arduino Micro

@StarCat since "A3" is the marker on the board itself, i thought it would be easier to understand, ofcourse every analog pin can be used as an digital (in the code i do so). I postet the complete sketch, because i dont know, if the problem maybe is in an other part then the two switches.
The Buttons on pins 0/1 may get wired with a voltage distributor on an other pin

why are you talking about selecting between 10 steps and 1 step when you cannot get the encoder to work? ... please focus your question to the problem

No output, neither in on nor in the off position of the switch

Which rotary encoder and switch are you referring to? When I google those words, it seems there are millions of choices. Is the switch built in to the rotary encoder? I am having trouble seeing your rotary encoder from my computer. How about sharing a link to the manufacturer, or datasheet, or a picture of it?

I postet the complete sketch, because i dont know, if the problem maybe is in an other part then the two switches. - if you reduced the code to the encoder part only you would find that out, wouldn't you?

@jsotola the Rotarys above, which have no switch connected, are working.

@VE7JRO added them

Again, please reduce your source to the minimum that still reveals your problem.

I second the other commenters: you are posting too much code. Please, see How to create a Minimal, Reproducible Example. 2. May be unrelated to your problem but, your code assumes BasicEncoder::get_change() always returns −1, 0 or 1. This may not always be the case, especially considering that you have quite a few delay() in your code.

@EdgarBonet I read the link you posted and will reduce the code this afternoon (with help of Jsotola). get_change() should either give 1 or - 1 if rotary is used and 0 if it stands still, doesn't it?

Re the value returned by get_change(): as stated in the documentation, get_change() returns “the number of counts since the last call to the method”. If the loop executes very quickly, this will almost always be within ±1. The documentation suggests “Try adding a delay in loop() to see larger changes being reported.” You already have quite a few delays.

@EdgarBonet so you think i should compare if its higher or lower than 1 v -1?

And this I could put in a loop, so it pushes the button that often i rotated the switch, couldn't I?

i want to excuse for shorten the code that late, but now it is, had no time before and forgot when i wrote the question

This is not an answer to the question, but a tip about simplifying your code.
This is a snippet of your code.

void loop() {

// some more code here

  int encoder1State = encoder1.get_change();
  switch (encoder1State) {
    case 1:
      Joystick.setButton(8, 1);
      delay(25);
      Joystick.setButton(8, 0);
      //Serial.println(encoder1State);
      break;
    case -1:
      Joystick.setButton(9, 1);
      delay(25);
      Joystick.setButton(9, 0);
      //Serial.println(encoder1State);
      break;
    case 0:
      break;
  }
  int encoder2State = encoder2.get_change();
  switch (encoder2State) {
    case 1:
      Joystick.setButton(10, 1);
      delay(25);
      Joystick.setButton(10, 0);
      //Serial.println(encoder1State);
      break;
    case -1:
      Joystick.setButton(11, 1);
      delay(25);
      Joystick.setButton(11, 0);
      //Serial.println(encoder1State);
      break;
    case 0:
      break;
  }
  int encoder3State = encoder3.get_change();
  switch (encoder3State) {
    case 1:
      Joystick.setButton(12, 1);
      delay(25);
      Joystick.setButton(12, 0);
      //Serial.println(encoder1State);
      break;
    case -1:
      Joystick.setButton(13, 1);
      delay(25);
      Joystick.setButton(13, 0);
      //Serial.println(encoder1State);
      break;
    case 0:
      break;
  }
  int currentButton20State = !digitalRead(joyButton20);
  int encoder4State = encoder4.get_change();
  switch (currentButton20State) {
    case 0:
      switch (encoder4State) {
        case 1:
          Joystick.setButton(14, 1);
          delay(25);
          Joystick.setButton(14, 0);
          Serial.println(encoder4State);
          break;
        case -1:
          Joystick.setButton(15, 1);
          delay(25);
          Joystick.setButton(15, 0);
          Serial.println(encoder4State);
          break;
        case 0:
          break;
      } break;
    case 1:
      switch (encoder4State) {

        case 1:
          TenRotaryStepsUP();
          break;
        case -1:
          TenRotaryStepsDOWN();
          break;
        case 0:
          break;
      } break;
  }

  //GetParamFromFS2020();
  //ShowFlightParam();

  delay(10);

}

void TenRotaryStepsUP()
{
  for (int i = 0; i < 10; i++)
  {
    Joystick.setButton(14, 1);
    delay(25);  //for testing set on higher number e.g. 500
    Joystick.setButton(14, 0);
    Serial.println("step: "); Serial.println(i);
    delay(10);
  }
}

void TenRotaryStepsDOWN()
{
  for (int i = 0; i < 10; i++)
  {
    Joystick.setButton(15, 1);
    delay(25);
    Joystick.setButton(15, 0);
    Serial.println("step: "); Serial.println(i);
    delay(10);
  }
}

It can be simplified by putting repeated code into functions.

void loop() {

// some more code here

  int encoder1State = encoder1.get_change();
//Serial.println(encoder1State);
  switch (encoder1State) {
    case 1:
      clickButton(8);
      break;
    case -1:
      clickButton(9);
      break;
    case 0:
      break;
  }

  int encoder2State = encoder2.get_change();
  switch (encoder2State) {
    case 1:
      clickButton(10);
      break;
    case -1:
      clickButton(11);
      break;
    case 0:
      break;
  }

  int encoder3State = encoder3.get_change();
  switch (encoder3State) {
    case 1:
      clickButton(12);
      break;
    case -1:
      clickButton(13);
      break;
    case 0:
      break;
  }

  int currentButton20State = !digitalRead(joyButton20);

  int encoder4State = encoder4.get_change();
  switch (currentButton20State) {

    case 0:
      switch (encoder4State) {
        case 1:
          clickButton(14);
          break;
        case -1:
          clickButton(15);
          break;
        case 0:
          break;
      } break;

    case 1:
      switch (encoder4State) {
        case 1:
          clickTen(14);
          break;
        case -1:
          clickTen(15);
          break;
        case 0:
          break;
      } break;
  }

  //GetParamFromFS2020();
  //ShowFlightParam();

  delay(10);

}

void clickButton(int pin) {
  Joystick.setButton(pin, 1);
  delay(25);
  Joystick.setButton(pin, 0);
}

void clickTen(int pin) {
  for (int i = 0; i < 10; i++)
  {
    clickButton(pin);
    Serial.println("step: "); Serial.println(i);
    delay(10);
  }
}

You can even format your code like this.
switch (encoder3State) {
  case  1:      clickButton(12);      break;
  case -1:      clickButton(13);      break;
  case  0:                            break;
}

EDIT
Also refer to the following about the use of arrays as variables, to specify pins, instead of individual variable names
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Arrays
eg. use lastButtonState[1] instead of lastButton1State and joyButton[1] instead of joyButton1
that will allow the use of for loops to repeat the same action for multiple pins
int currentButton2State = !digitalRead(joyButton2);
if (currentButton2State != lastButton2State) {
  Joystick.setButton(1, currentButton2State);
  if (currentButton2State == 1) {
    delay(1);
    Joystick.setButton(1, 0);
  }
  lastButton2State = currentButton2State;
}

becomes
int currentButtonState[pin] = !digitalRead(joyButton[pin]);
if (currentButtonState[pin] != lastButtonState[pin]) {
  Joystick.setButton(pin-1, currentButtonState[pin]);
  if (currentButtonState[pin] == 1) {
    delay(1);
    Joystick.setButton(pin-1, 0);
  }
  lastButtonState[pin] = currentButtonState[pin];
}

Thanks @jsotola, will try this when I'm back at home!

added more info

Thanks, I will try this this afternoon (also I will reduce the code in the question)

You can also handle multiple encoder steps with something like if(encoder3State>0) while(encoder3State--) clickButton(12); if(encoder3State<0) while(encoder3State++) clickButton(13);.


text:
Software serial communication problem between ESP8266 and Arduino Mega for plant monitoring system (using Blynk IoT)
We're using the ESP8266 to receive data from the Arduino Mega board, where our sensors are connected. Supposedly, our ESP is connected to the Blynk App. However, the values showing up in our dashboard are 0 but, the app says that the device is online.
The values in the sensors are showing up in our LCD, so we think that the problem is the connection between the ESP and the Arduino.
We've attached our ESP and Arduino Mega code below for anyone's reference.
ESP code:
    #define BLYNK_TEMPLATE_ID           "ID"
    #define BLYNK_TEMPLATE_NAME         "CROPBOX"
    #define BLYNK_AUTH_TOKEN            "TOKEN"

    /* Comment this out to disable prints and save space */
    #define BLYNK_PRINT Serial

    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <SoftwareSerial.h>

    // Your WiFi credentials.
    // Set password to "" for open networks.
    char ssid[] = "WiFi_Name";
    char pass[] = "WiFi_PW";

    // This function is called every time the device is connected to the Blynk.Cloud

    SoftwareSerial swSerial(V5, V6);  // RX, TX

    void setup()
    {

    // Debug console
    Serial.begin(9600);
    Serial.println("ESP8266 standalone test");
    swSerial.begin(9600);
    Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
    Serial.print("connecting to WiFi");
    Serial.print(ssid);
    WiFi.begin(ssid, pass);
    Serial.println();
    Serial.print("Connecting");
    while(WiFi.status() != WL_CONNECTED ){
    delay(1000);
    Serial.println(".");
    }
    Serial.print("NodeMCU IP Address:");
    Serial.print(WiFi.localIP());

      pinMode(V5, INPUT);
      pinMode(V6, OUTPUT);
    }

    void loop()
    {

      Blynk.run();

      int i = 30;
      swSerial.print(i);
      swSerial.println("\n");
      delay(30);
      // You can inject your own code or combine it with other sketches.
      // Check other examples on how to communicate with Blynk. Remember
      // to avoid delay() function!

    }

Arduino code:
     /* Fill-in information from Blynk Device Info here */
    #define BLYNK_TEMPLATE_ID "ID"
    #define BLYNK_TEMPLATE_NAME "CROPBOX"
    #define BLYNK_AUTH_TOKEN "TOKEN"

    // Libraries
    #include <Wire.h>
    #include <RTClib.h>
    #include <LiquidCrystal_I2C.h>
    #include <DHT.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <HCSR04.h>
    #include <SoftwareSerial.h>
    #include <SD.h> // Include the SD library for microSD card functionality
    #include <BlynkSimpleStream.h>
    #include <Blynk.h>

    // Pin Connections
    #define DHTPIN 2
    #define DHTTYPE DHT11
    #define ONE_WIRE_BUS 4
    #define MQ135_AO A3
    #define MQ135_DO 7
    #define SD_CHIP_SELECT 53 // Pin 51 in Arduino Mega corresponds to pin 53 for SD_CHIP_SELECT
    #define CS_PIN 53        // Chip select pin for SD card
    #define SCK_PIN 52       // SCK pin for SD card
    #define MOSI_PIN 51      // MOSI pin for SD card
    #define MOSO_PIN 50      // MISO pin for SD card

    // Initialization
    DHT dht(DHTPIN, DHTTYPE);
    float calibration_value = 1 + 0.6;  // pH
    int phval = 0;
    unsigned long int avgval;
    int buffer_arr[10], temp;
    float ph_act;
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);
    namespace pin {
      const byte tds_sensor = A1;
    }
    namespace device {
      float aref = 4.3;
    }
    namespace sensor {
      float ec = 0;
      unsigned int tds = 0;
      float waterTemp = 0;
      float ecCalibration = 1;
    }

    UltraSonicDistanceSensor distanceSensor(12, 11);
    RTC_DS3231 rtc;
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    SoftwareSerial s(5, 6);
    String str;

    File dataFile;

    void setup() {
      Serial.begin(9600);
      //ArduinoMega.begin(4800);
      Serial.println("Humidity and Temperature");
      dht.begin();
      sensors.begin();
      if (!rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }
      lcd.begin(16, 2);
      lcd.backlight();
      s.begin(9600);

      // Initialize SD card
      if (!SD.begin(SD_CHIP_SELECT)) {
        Serial.println("Initialization failed!");
        return;
      }
      Serial.println("Initialization done.");

      // Create a file on the SD card if it doesn't exist
      if (!SD.exists("data.txt")) {
        dataFile = SD.open("data.txt", FILE_WRITE);
        if (dataFile) {
          dataFile.close();
          Serial.println("File created.");
        } else {
          Serial.println("Error creating file.");
        }
      }
    }

    void loop() {

      // Read all sensor values
      float h = readHumidity();
      float t = readAirTemperature();
      float ph = readPH();
      float waterTemp = readWaterTemperature();
      unsigned int tds = readTDS();
      float ec = readEC();
      float distance = readDistance();
      int lightIntensity = readLightIntensity();
      int co2Level = readCO2Level();
      DateTime now = rtc.now();

      Blynk.virtualWrite(V1, ec);
      Blynk.virtualWrite(V2, tds);
      Blynk.virtualWrite(V3, waterTemp);
      Blynk.virtualWrite(V4, ph);
      Blynk.virtualWrite(V5, h);
      Blynk.virtualWrite(V6, t);
      Blynk.virtualWrite(V7, distance);
      Blynk.virtualWrite(V8, lightIntensity);
      Blynk.virtualWrite(V9, co2Level);

      // Serial Output
      printToSerial(h, t, ph, waterTemp, tds, ec, distance, lightIntensity, co2Level, now);

      // Display Data on LCD
      LCDisplay(h, t, ph, waterTemp, tds, ec, distance, lightIntensity, co2Level, now);

      // Send to NodeMCU
      sendToNodeMCU(h, t, ph, waterTemp, tds, ec, distance, lightIntensity, co2Level);

      // Write data to SD card
      writeDataToSDCard(h, t, ph, waterTemp, tds, ec, distance, lightIntensity, co2Level, now);

      delay(3000);
    }

    float readHumidity() {
      return dht.readHumidity();
    }

    float readAirTemperature() {
      return dht.readTemperature();
    }

    float readPH() {
      for (int i = 0; i < 10; i++) {
        buffer_arr[i] = analogRead(A0);
        delay(30);
      }
      for (int i = 0; i < 9; i++) {
        for (int j = i + 1; j < 10; j++) {
          if (buffer_arr[i] > buffer_arr[j]) {
            temp = buffer_arr[i];
            buffer_arr[i] = buffer_arr[j];
            buffer_arr[j] = temp;
          }
        }
      }
      avgval = 0;
      for (int i = 2; i < 8; i++)
        avgval += buffer_arr[i];
      float volt = (float)avgval * 5.0 / 1024 / 6;
      return -5.70 * volt + calibration_value;
    }

    float readWaterTemperature() {
      sensors.requestTemperatures();
      return sensors.getTempCByIndex(0);
    }

    unsigned int readTDS() {
      sensors.requestTemperatures();
      sensor::waterTemp = sensors.getTempCByIndex(0);
      float rawEc = analogRead(pin::tds_sensor) * device::aref / 1024.0;
      float temperatureCoefficient = 1.0 + 0.02 * (sensor::waterTemp - 25.0);
      sensor::ec = (rawEc / temperatureCoefficient) * sensor::ecCalibration;
      sensor::tds = (133.42 * pow(sensor::ec, 3) - 255.86 * sensor::ec * sensor::ec + 857.39 * sensor::ec) * 0.5;
      return sensor::tds;
    }

    float readEC() {
      return sensor::ec;
    }

    float readDistance() {
      return distanceSensor.measureDistanceCm();
    }

    int readLightIntensity() {
      return analogRead(A2);
    }

    int readCO2Level() {
      return analogRead(MQ135_AO);
    }

    void LCDisplay(float h, float t, float ph, float waterTemp, unsigned int tds, float ec, float distance, int light, int co2, DateTime now) {
      lcd.clear();
      lcd.print("AirTemp: " + String(t) + "C");
      lcd.setCursor(0, 1);
      lcd.print("AirHumid: " + String(h) + "%");
      delay(2500);
      lcd.clear();

      lcd.print("pH: " + String(ph));
      lcd.setCursor(0, 1);
      lcd.print("WtrTemp: " + String(waterTemp) + "C");
      delay(2500);
      lcd.clear();

      lcd.print("TDS: " + String(tds) + "ppm");
      lcd.setCursor(0, 1);
      lcd.print("EC: " + String(ec) + " mS/cm");
      delay(2500);
      lcd.clear();

      lcd.print("WtrLvl: " + String(distance) + "cm");
      lcd.setCursor(0, 1);
      lcd.print("Light: " + String(light) + " units");
      delay(2500);
      lcd.clear();

      lcd.print("CO2: " + String(co2) + " ppm");
      delay(2500);
      lcd.clear();

      lcd.print(String(now.day()) + "/" + String(now.month()) + "/" + String(now.year()));
      lcd.setCursor(0, 1);
      lcd.print(String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second()));
      delay(2500);
    }

    void readTdsQuick() {
      sensors.requestTemperatures();
      sensor::waterTemp = sensors.getTempCByIndex(0);
      float rawEc = analogRead(pin::tds_sensor) * device::aref / 1024.0;
      float temperatureCoefficient = 1.0 + 0.02 * (sensor::waterTemp - 25.0);
      sensor::ec = (rawEc / temperatureCoefficient) * sensor::ecCalibration;
      sensor::tds = (133.42 * pow(sensor::ec, 3) - 255.86 * sensor::ec * sensor::ec + 857.39 * sensor::ec) * 0.5;
      Serial.print("TDS: ");
      Serial.println(sensor::tds);
      Serial.print("EC: ");
      Serial.println(sensor::ec, 2);
    }

    void printToSerial(float h, float t, float ph, float waterTemp, unsigned int tds, float ec, float distance, int lightIntensity, int co2Level, DateTime now) {
      Serial.print("Air Humidity: ");
      Serial.print(h);
      Serial.println("% ");
      Serial.print("Air Temperature: ");
      Serial.print(t);
      Serial.println("C ");

      Serial.print("pH Val: ");
      Serial.println(ph);

      Serial.print("Water Temperature: ");
      Serial.println(waterTemp);

      Serial.print("TDS: ");
      Serial.println(tds);

      Serial.print("EC: ");
      Serial.println(ec, 2);

      Serial.print("Ultrasonic Distance: ");
      Serial.println(distance);

      Serial.print("Light Intensity: ");
      Serial.println(lightIntensity);

      Serial.print("CO2 Level: ");
      Serial.println(co2Level);

      Serial.print(now.dayOfTheWeek());
      Serial.print(" ");
      Serial.print(now.day(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.year(), DEC);
      Serial.print(" -- ");
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.println(now.second(), DEC);
    }

    void sendToNodeMCU(float h, float t, float ph, float waterTemp, unsigned int tds, float ec, float distance, int lightIntensity, int co2Level) {
      s.print(h, 2);    s.print("A");
      s.print(t, 2);    s.print("B");
      s.print(ph, 2); s.print("C");
      s.print(ec, 2); s.print("D");
      s.print(tds, 2); s.print("E");
      s.print(distance, 2); s.print("F");
      s.print(waterTemp, 2); s.print("G");
      s.print(co2Level); s.print("H");
      s.print("\n");
      delay(500);
    }

    void writeDataToSDCard(float h, float t, float ph, float waterTemp, unsigned int tds, float ec, float distance, int light, int co2, DateTime now) {
      // Open the data file in write mode
      dataFile = SD.open("data.txt", FILE_WRITE);
      if (dataFile) {
        // Write sensor data to the file
        dataFile.print(h);
        dataFile.print(",");
        dataFile.print(t);
        // Write other sensor data similarly
        dataFile.print(",");
        dataFile.print(ph);
        dataFile.print(",");
        dataFile.print(waterTemp);
        dataFile.print(",");
        dataFile.print(tds);
        dataFile.print(",");
        dataFile.print(ec);
        dataFile.print(",");
        dataFile.print(distance);
        dataFile.print(",");
        dataFile.print(light);
        dataFile.print(",");
        dataFile.print(co2);

        // Write timestamp
        dataFile.print(",");
        dataFile.print(now.year(), DEC);
        dataFile.print("/");
        dataFile.print(now.month(), DEC);
        dataFile.print("/");
        dataFile.print(now.day(), DEC);
        dataFile.print(" ");
        dataFile.print(now.hour(), DEC);
        dataFile.print(":");
        dataFile.print(now.minute(), DEC);
        dataFile.print(":");
        dataFile.println(now.second(), DEC);

        // Close the file
        dataFile.close();
      } else {
        Serial.println("Error opening data file.");
      }
    }

Why do you use Software Serial when both of those boards have extra real Serial ports to use?  SoftwareSerial is for faking serial ports with software when you're out of real ones.  But you've got real ports left.  They'll work a lot better if you use them.

Test a basic communication sketch to verify that the SoftwareSerial communication between the ESP8266 and Arduino Mega is working correctly without the Blynk integration.

This is not how BlynkSimpleStream was intended to be used, but it is not supported now anyway.
There are a few options how to use esp8266 to connect to Blynk.
One option is what you attempt. A esp8266 sketch with Blynk which exchanges data with the main Arduino. But you have to code the exchange. The Blynk library will not help you with that.
Better option is to use only a esp8266 development board like Wemos D1 mini or NodeMCU board and wire the sensors and actuators to it. Then you have one sketch with Blynk.
If you have to use the esp8266 only as a WiFi adapter and you need other Arduino to handle the sensors, it is simpler to put AT firmware into the esp8266 and use a WiFi library in the Arduino. I recommend my WiFiEspAT library (available in Library Manager). It has an example on how to use it with Blynk. (I see the example is a little outdated, but it will help.)

When I use the AT command and enter "AT" on the serial monitor of the ESP8266 module, nothing shows up.

and did you put AT firmware into the esp8266? now it has your sketch.


text:
Using a bistable solenoid valve with arduino from battery
Context
I have been trying for some time to control a 4.5 V bistable solenoid valve (a bistable solenoid valve is controlled by reversing the polarities) using an ATmega328P in order to be able to control a flow of water. Everything will be on battery and therefore needs to consume as little as possible.
For now, all tests have been done at 5 V powered by USB and on 3.7 V battery.
Attempts
When I directly connect the valve between VCC and GND, whether it is with USB or battery, the valve correctly open/close.
I tried using a L9110s and a L293DNE, but with the battery, the problem is that the valve only makes a slight noise, but does not open/close. It also happens from time to time with USB, but it's probably a handling error on my part.
So I think the controllers have too big losses and don't give a high enough voltage to do anything. These are of course just assumptions, I don't know enough about it to say for sure.
Regarding the connections, I did as indicated in the datasheet:

By placing the valve in place of the motor and connecting one of the two inputs to the GND and the other to the VCC.
Values
I did some tests by measuring the voltage across the valve with the L9110s, as well as its current under different conditions.
In 5 V through USB

Voltage with valve
Voltage without valve
Current

Off
0 V

0 mA

Open
2.7 V
4.5 V
196 mA

Close
-3.3 V
-4.6 V
231 mA

And that work !
In 3.9 V through 3.7 V battery

Voltage with valve
Voltage without valve
Current

Off
0 V

0 mA

Open
1.8 V
3.3 V
140 mA

Close
-2.1 V
-3.5 V
150 mA

But here, it just makes little noises…
Finally
I would like to know if there is a way to increase the output voltage of the L9110s without consuming more when not in use. I had thought about using a DC-DC step up boost like this one, but the problem is that the L9110s reverses the polarities, and therefore I cannot connect my boost to the output of the latter.

Did you check how much current the valve requires? Are you sure your power supply can deliver that much current?

@EdgarBonet the current required for the valve is 500mA and the power supply is 2A so no problem. Additionally, the valve works correctly when I manually connect it between VCC and GND. So I don't think that's the problem . Thanks anyway for this remark!

use a transistor to drive the solenoid ... many examples on the internet

@jsotola this valve being a bistable valve, I have to reverse the polarities in order to open/close it. So I have to make an H-bridge with transistors? Isn’t that precisely the work of the l9110? I will try as soon as I have enough transistors at my disposal. Thank you for your idea!

are you certain that you have to reverse polarity?

Please measure voltage and current of the valve when you apply control signals for all three situations, off, open, close, and [edit] your question to add the results. BTW; what is the reference to Arduino? Perhaps it would be better to ask this at SE/EE?

Add a flyback diode (e.g., 1N4007) across the solenoid to protect the MOSFET from voltage spikes caused by the inductive load.

@tepalia Are you aware that the solenoid is driven in both directions? Additionally, the L9110 includes diodes for such applications.

@jsotola Yes, this is how a bistable solenoid valve works. This is also what it says in the item description, and it works correctly when I change the polarities manually.

@thebusybee I made the measurements as requested and put them in the original question.
I posted the question here because that's what I was asked when I asked on stackoverflow.com and the whole thing is controlled by an atmega328p. I'm not yet very familiar with all the available forums, so thank you for the link you provided, and I will ask there as soon as possible. THANKS

You did not yet post this question over at SE/EE, so I answer here. Anyway, it can be helpful for other Arduino users, too.

The data sheet clearly shows the saturation voltages at VCC = 9V:

Symbol
Meaning
Typical
Unit

VHout
Output high voltage
7.6
V

VLout
Output low voltage
0.45
V

So you need to take about 1.8 V voltage loss into account, and this matches your measurements.
Instead of boosting the output voltage to the solenoid, which does not work as you note, you can boost the supply voltage of the L9110. According to the data of the linked booster you should be able to use it.
The supply voltage of the L9110 does not need to be the same as that of the MCU.
The data sheet says this for the inputs:

Symbol
Meaning
Typical
Unit

VHin
Minimum input high voltage
2.5
V

VLin
Maximum input low voltage
0.7
V

This matches the output voltage produced by an ATmega328P at 3.6 V supply:

Symbol
Meaning
Typical
Unit

VOH
Minimum output high voltage (shall be higher than the value for the L9110)
2.9
V

VOL
Maximum output low voltage (shall be lower than the value for the L9110)
0.5
V


text:
LED ring with different effects cycling
I need help for my little project. I don't know Arduino, so I used ChatGPT to write me the code. After a few hours of testing, I almost got what I need. The scheme is the following: LED ring, push button and potentiometer. I use the potentiometer to control the brightness and the button cycle through different modes (effects). After trying to figure out what is going on, I think I found the issue, but I don't know how to fix it.
In the code below, the toggleMode() function is the problem. This expression: mode = (mode + 1) % 3;, breaks the correct execution. All three effects can be cycled only once, and then it stuck on the last effect. Is there any other expression I can use for calculating the "mode"? Here is the complete code (also there are some lines for debugging as you can see):
#include <FastLED.h>
#include <Arduino.h> // Include the Arduino core library for Serial support

// Define the number of LEDs in the LED ring
#define NUM_LEDS 24

// Define the data pin
#define DATA_PIN 6

// Define the LED type
#define LED_TYPE WS2812B

// Define the color order
#define COLOR_ORDER GRB

// Create an array of CRGB objects to store the colors of each LED
CRGB leds[NUM_LEDS];

// Define the pin for the potentiometer
#define POTENTIOMETER_PIN A0

// Define the pin for the button
#define BUTTON_PIN 2

// Define the minimum and maximum brightness values
#define MIN_BRIGHTNESS 0
#define MAX_BRIGHTNESS 255

// Variable to store the current mode (0: static rainbow, 1: sparkle)
int mode = 0;

int previousButtonState = HIGH;

void setup() {
  // Initialize Serial communication at a baud rate of 9600
 Serial.begin(9600);

  mode = 2;
  // Initialize FastLED library
 FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

  // Set initial brightness
 FastLED.setBrightness(MAX_BRIGHTNESS / 2);

  // Set the button pin as input with internal pull-up resistor
 pinMode(BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
  // Read the value from the potentiometer
 int potValue = analogRead(POTENTIOMETER_PIN);

  // Map the potentiometer value to the brightness range
 int brightness = map(potValue, 0, 1023, MIN_BRIGHTNESS, MAX_BRIGHTNESS);

  // Set the brightness of the LED ring
 FastLED.setBrightness(brightness);

  // Check the button state with debouncing
 int buttonState = digitalRead(BUTTON_PIN);
 if (buttonState == LOW && previousButtonState == HIGH) {
    // Button is pressed for the first time
    // Toggle the mode when button is pressed
 toggleMode();
  }

  previousButtonState = buttonState;

  // Call the appropriate function based on the mode
 if (mode == 0) {
 Serial.println("Mode: Rainbow");
 rainbow();
  } else if (mode == 1) {
 Serial.println("Mode: Sparkle");
 sparkle();
  } else if (mode == 2) {
 Serial.println("Mode: Static Rainbow Fade");
 staticRainbowFade();
  }

  // Display the updated LED colors
 FastLED.show();

  // Delay to control the loop rate
 delay(30);
}

// Function to toggle the mode between rainbow and sparkle
void toggleMode() {
  mode = (mode + 1) % 3;

    //DEbugging code
 Serial.print("Mode toggled: ");
 Serial.println(mode);
}

// Function to create a rainbow effect
void rainbow() {
  // Hue increment value determines the speed of the rainbow
 static uint8_t hue = 0;

  // Fill the LED ring with colors
 for(int i = 0; i < NUM_LEDS; i++) {
 leds[i] = CHSV(hue + (i * 255 / NUM_LEDS), 255, 255);
  }

  // Increment the hue value for the next iteration
  hue++;
}

// Function to create a sparkle effect with smooth fading and color change
void sparkle() {
  // Probability of an LED sparkling (adjust as needed)
 const float sparkleProbability = 0.02; // Adjust this value to change the density of the sparkle

  // Loop through each LED
 for (int i = 0; i < NUM_LEDS; i++) {
    // Check if the LED should sparkle
 if (random(0, 1000) < (sparkleProbability * 1000)) {
      // Set a random color to the sparkling LED
      CRGB sparkleColor = CHSV(random(0, 255), 255, 255); // Random color
 leds[i] = sparkleColor;
    }
    // Fade out all LEDs
 leds[i].fadeToBlackBy(10); // Adjust the fade rate (lower value fades faster)
  }
}

// Function to create a static rainbow effect with fading in and out
void staticRainbowFade() {
  // Fill the LED ring with rainbow colors
 rainbow();

  // Fade in
 for (int brightness = 0; brightness <= 255; brightness++) {
    // Set the brightness of all LEDs
 FastLED.setBrightness(brightness);

    // Display the updated LED colors
 FastLED.show();

    // Delay to control the fading speed (adjust as needed for desired effect)
 delay(7); // Adjust this value for fading in speed
  }

  // Delay between fade in and fade out
 delay(1000); // Adjust this value for the delay between fade in and fade out

  // Fade out smoothly
 for (int brightness = 255; brightness >= 0; brightness--) {
    // Set the brightness of all LEDs
 FastLED.setBrightness(brightness);

    // Display the updated LED colors
 FastLED.show();

    // Delay to control the fading speed (adjust as needed for desired effect)
 delay(7); // Adjust this value for fading out speed
  }
}

just increment mode mode++ ... then set to 0 if it reaches 3

Thank you! That looks much easier solution! The problem is I don't know where to add that... I tried to add it in the toggleMode() but nothing happens.

@Niki Did you read my answer? Replacing one working code with another working code will not heal your error, which has an unrelated reason.

@thebusybee Yes, I checked the Nordic link. I thought that Blinky example is from the Arduino SDK's examples but now I found it and will check it out.

@Niki this might help you ... something I wrote as a demo ... https://wokwi.com/projects/362275278547275777

I’m voting to close this question because it uses chatgpt which is banned on SE: https://meta.stackoverflow.com/questions/421831/policy-generative-ai-e-g-chatgpt-is-banned , https://stackoverflow.com/help/gen-ai-policy .

The mode changing line is correct. jsotola mentions an alternative form, like this:
void toggleMode() {
  mode++;
  if (mode == 3) {
    mode = 0;
  }

  // Debugging code
  Serial.print("Mode toggled: ");
  Serial.println(mode);
}

But this is not the error, and it will not help.
The error is that your staticRainbowFade() delays for about 4.5 seconds. Only after that time the button is read.
The relevant parts are condensed here:
void loop() {
  //...
  int buttonState = digitalRead(BUTTON_PIN);
  //...
  } else if (mode == 2) {
    Serial.println("Mode: Static Rainbow Fade");
    staticRainbowFade(); // <=== this takes about 4.5 seconds
  }
  // ...
}

void staticRainbowFade() {
  // ...
  for (int brightness = 0; brightness <= 255; brightness++) {
    // ...
    delay(7);
  }

  delay(1000);

  for (int brightness = 255; brightness >= 0; brightness--) {
    // ...
    delay(7);
  }
}

As an immediate "solution" you can leave the button unpressed for about 5 seconds, and then press it for about 5 seconds. This should change the mode.
However, this is just a work-around. Actually you should refactor your sketch to the non-delayed form. As this is some effort, I do not present it here. You might want to look in the Blinky example that does not use delay() to have an idea. Another topic to research is the "finite state machine" that decouples separate logic.

Or - as another workaround - read the button also in the for loops inside staticRainbowFade(). And at least reducing the 1s delay in between the for loops. Though rewriting the code for no-delay is way cleaner

I don't know what to rewrite. I just need it to work as I expect. I'm not programmer (obviously). I'm interested in many things and I can't learn everything even if I want to. That's why I started to play with ChatGPT coding and I'm happy with the results but there are some issues which the AI can't resolve (for now, hopefully). Thank you for the reply. I'll continue to read and try to fix it.

Well, well. I will not rant repeatedly against AIs, but they have no clue about programming, because they have no understanding. ChatGPT and similar are just good at guessing word sequences that are free from syntax errors. What you need instead is code that is semantically correct. -- What you want is a complete solution probably with explanation, which is far too broad here. Did you look into the suggested example? Did you grasp it? If you have a specific question about this Blinky, feel free to post a separate question here. You might want to link back to this question, though.


text:
Is it safe to leave an ATmega328PB's RX and TX pins unconnected?
I am using an ATmega328PB and was looking at Arduino's and others' schematics that use it. All schematics I've found use a serial chip to communicate between USB and TX & RX. However, I do not need USB, and I plan to program the ATmega through ICSP.
Is it safe to leave these pins unconnected or connect them directly to LEDs like some Arduino boards do (like in the photo)? I wasn't able to find clear information about it.

With a 120 ohm resistor those leds will be quite bright.

VCC will be connected to 3.3V, and the LED is rated for 2.7V with a forward current of 5mA. Should my resistors still have a greater resistance?

Look at these pins as any other I/O pin. There is nothing special about them, if you do not enable their special function, in your case USART0.
This is what the data sheet says:

17.2.6 Unconnected Pins
If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. Connecting unused pins directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output.

Therefore, if you do not use USART0 and do not need these LEDs, you can get away with no external circuitry. Just enable the internal pull-ups.

Thank you so much! I was worried as other posts I have seen showed issues with floating TX and RX pins that interfere with their script, but as you stated, I can enable pull-ups to avoid this. Have a great day!

@Acmek Better use the correct sources of information, for example data sheets and application notes. Forums posts are competent only in rare cases.


text:
Low power microcontroller with gprs/gsm and maybe gps on board
Good day to ya all. I have a general question and a potential problem to solve.
My plan is to make a device which will work on 2 li-ion batteries. The purpose of this board is to take data from 3/4 sensors and send them via gprs to a server.( it would be ideal if it had gps on board also )
It must be small and it must at least hold half a year on those 2 ( at max 4 batteries ).
My question to you all is do you know a good low power microcontroller board with gsm/gprs chip on it (and maybe gps) ?
One solution would be to use a Arduino pro nano and a separate sim800 module and a separate gps module but this solution is just complicating. I need something with similar functionality of an Arduino and not so power hungry.
Hope to hear from you.

this is a Q&A site, not a brainstorming forum ... what is the actual arduino related problem that you are trying to solve? ... what is your question about the problem that you are trying to solve?

Nothing to brainstorm here. Just asking is there some arduino or ATMega based board with gsm/gprs finctionality on it.

If someone helps than that is good. You as a senior member here dont have to be rude. If you can help than great. I know too that there probably is and that it is ATmega based. That is the reason i ask here and not my mother for it. Thanks <3

i do not mean to be rude and I apologize if you perceived it that way ... you asked for the existence of a component ... i said that it probably exists ... shopping questions are off topic here, so you cannot ask where to get one, but you can ask if one exists

Thanks for the apologize. I asked just for help if someone knows anything or has used something similar. Something to let me dig into just to set me on a right path.


text:
Need Help with HTTPClient.h and storing cookies
Im very new to Arduino. Using an ESP32, Im trying to login to a network device to read its log file. To login to the device I need to simulate a web browser with cookies.
The ESP32 is connecting to WiFI correctly, and Im including the HTTPClient.h file
Using http.begin I am able to browse to the device login page, but I dont know how to store the successful login in a cookie.
From doing some research I think that cookies are just HTTP headers, but I'm not really sure how to read/parse/resend the cookie header in another HTTP request.
I can successfully do it in PEARL using CURL (my code is below). Can someone help me port this to ESP32
use strict qw/refs/;
use HTTP::Cookies;
use LWP::UserAgent;
use HTTP::Request::Common qw/POST GET/;

my $Browser = LWP::UserAgent->new(
cookie_jar => HTTP::Cookies->new,
requests_redirectable => ,
timeout => 10,
pragma => "no-cache",
max-age => 0,
agent => "Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko/20100101 Firefox/11.0"
);

my $Page = $Browser->request(GET $Authenticate);

already posted at https://forum.arduino.cc/t/need-help-with-httpclient-h-and-storing-cookies/924772


text:
Library to set internal analog gain of the Arduino?
My original question was if there is a library that covers the internal comparator and differential and gain modes for the Arduino Uno, Mega 2560, Leonardo, Due, Zero, M0.
The answer is obvious: "No". To my surprise there is not even a start to make it and neither a collaboration to gather usefull code.
If you know pieces of code (Arduino compatible and documentation for which pins) for the analog comparator and gain, then please tell me about it, and I put them in this list.

analogComp, a library to manage the analog comparator.
To use the analog comparator for the ATmega8, Arduino Uno, Leonardo, Mega 2560, ATtiny85, and others. A routine is called with an interrupt every time a particolar condition happens.
Arduino Differential ADC and Gain ADC
A file "wiring_differential.c" should be added to the Arduino files. Functions "analogReadDiff" and "analogReadGain" will be added. For the Arduino Leonardo and the Arduino Mega 2560.
Nick Gammon: Using the Arduino Analog Comparator
A simple example of a comparator mode for the ATmega328.
Application Note AT11480: Analog Comparator Application Examples
Using the Analog Comparator for SAM D (that includes the ATSAMD21 of the Arduino Zero and M0) processors.

Please pick a board, as the all have wildly differing processors. Or tell us what you want to achieve if you are actually asking which board to buy.

@Gerben, But I don't want to pick a board. I don't want to have a single solution for one specific project, I would like to know that there is something that I might use when needed. Next time I have a project with Arduino with one of the more common AVR or SAM boards then I would like to use a library to use the comparator or gain features. If I try really hard, then I could get some of the ATmega32U4 extra analog features working, but then I would have to do it all over again when using a Zero. For example the EnableInterrupt library is there and ready to be used when needed.

For one, the UNOs processor doesn't have the option to set a gain. So that board is already incompatible. The different processors have different gain values that you can select. I'm not sure about any other incompatibilities, as I've never used the comparator. It's very hard to create a library that bridges these incompatibilities, without loosing functionality (lowest common denominator).

My intention is to find a way to use every possible extra analog feature. Not to find the common denominator and end up with nothing.

Then you need to use the datasheets. You can have library to use simple abstractions, or you can have every possible features, but they are different for every processor and hypotetical library covering that all would be much more complicated, than those datasheets, as it would need to doo everything in each datasheet and also translation to some API and solve all cases, when user tries feature A from uP AA on uP BB, which does not have mentioned feature. And solving all those cases would cost a lot of cycles, so it would not be able use the uP to full extend anyway (for being too slow)

@gilhad That's what I'm afraid of. It would be a nice feature to use in many situations, but I can't even find a proper guide about the possibilities for the different Arduino boards. I posted my question because searching for "arduino gain" does not help. As far as I know there is not even a website where the information is gathered and something is being made. Even https://www.pjrc.com/teensy/adc.html has not filled in the "Differential Inputs & Amplifier" section.

Arduino way is common denominator and easy to use. Your needs are get as much as possible at any cost, which is opposite to Arduino way. You should look for Atmel datasheets for their processors, is you want to squeeze max from them. Not for libraries targeted at Arduino, which tries make easy and "same for all" access to "some basic electronics" and accidentally used (only) some of Atmels processors and then other people expanded it to few other cheap processors too (at least the basics). If you want racing bike, it is not good start from childgarten one with ballance wheels and built on that

@gilhead, I mentioned the "EnableInterrupt" library. That is something that just works. It took a few years, but it is very useful. Since the ATmega2560 and ATmega32U4 have similarities and also the M0+ (Zero) and M3 (Due), there are two main paths, and a number of differences for each chip. I would be nice if someone at least made a start, but beside those two pieces mentioned in my question, I can't find anything.

@gilhad, I have lowered my goal in my question drastically. Now I'm just looking for pieces of code that use the comparator and gain.

I would recommend you to check Nick Gammon's example on using the analog comparator by means of configuring the relevant flag bits of registers in the ATmega328. Sample code from the link, by Nick:
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

That was already in the analogComp library. But I didn't know that Nick Gammon wrote a page about it. Therefor you get the +200 bounty. At this moment I'm looking at the Atmel Studio 7 API for the ATSAMD21.

You seem to be interested mainly in ATSAMD21. There is an application note from Atmel, AT11480: Analog Comparator Application Examples, which may be of interest for you.
From the Getting started section (3.1, page 8):

The AC [Analog Comparator] example project has to be opened from New
  Example Project option in Atmel Studio. Using the option Atmel Studio
  → File → New → Example Project will open the New Example Project from
  ASF or Extensions window. The project named Analog Comparator Examples
  – SAM D21 Xplained Pro has to be opened.

There you'll find example code that might be useful for you, as it will show how to configure and manage the registers involved in using the analog comparator of the ATSAMD21. Namely, the example code is related to the following example applications:

Level crossing detector.
Window mode operation.
Preventing false spike detection.
Gray signal frequency measurement.
SleepWalking with analog comparator.

If you look into the first case (level crossing detector) for guidelines for where to start from, you can see that the application example goes through the following steps:

Enable alternate function H (AC/CMP[0]) for pin PA12 so that the comparator 0 output is directly routed to the pin.
Select GCLK Generator 0 as GCLK source for AC module. The GCLK Generator 0 is clocked from internal OSC8M oscillator whose output is set to 8MHz.
Select AIN[0] pin (PA04) as positive input and internal voltage scaler output as negative input for comparator 0. The voltage scaler register is set to a value of 9 corresponding to a voltage output of 0.5156V.
Set comparator 0 in continuous comparison mode with hysteresis and filter mode disabled.
Enable comparator 0 output to be routed to I/O pin and select interrupt mode as toggle so that comparator output toggles when positive input crosses the negative input (both during rising and falling).
Enable comparator 0 and then enable the AC module.

You could get from that example code some ideas about the registers to be configured and managed, and then try to use that knowledge for creating (or even reusing) some code within the Arduino IDE.
Hope it helps...

Thank you. That is the comparator. What about the differential mode with gain (and offset). I would like to keep using the Arduino, therefor I would like to be able to use the Arduino definitions instead of the Atmel Studio API calls.

What you are trying to do can be easily done via simple programming of the channels bits in the ADV module - the datasheet is your best friend here.
So if you want to take this one, take a look at the datasheet and that's all there is to it.
Happy to provide a sample piece to get you going.

A "common" problem is with a simple pressure sensor that has a wheatstone output with a offset. I would need a differential input, preferably with offset compensation and a lot of gain. For example the M0+ (ATSAM21G18) in the Arduino M0 or Zero can probably not do all of that, but should be able to get a reasonable resolution, but I don't know where to start http://www.microchip.com/wwwproducts/en/ATSAMD21G18 and I don't understand this: https://electronics.stackexchange.com/questions/275940/understanding-differential-adcs-and-refrence-voltages

Yes. A differential acc would be the way to go. In ave, the channel selection buts control the inputs as well as gains. So the best place to start would be to look at the datasheet and write your own analog Read() or to customize the stock analog read.

but I don't know where to start. the device datasheet is generally a great place to start. in the case of certain avrs, the adc can be configured to have gain and different inputs by selecting the channel bits. You can also use an external instrumentation amplifier to convert different inputs into single-ended input for your mcu that doesn't have different adc capabilities.

For that approach, you can check out an experiement I did using the differential input on ATtiny85 to build a simple milliohm meter here: https://wordpress.com/post/dannyelectronics.wordpress.com/262

another alternative is to use external adc with differential inputs. I also built a millieohm meter with the super cheap HX711. You may find it helpful as well: https://wordpress.com/post/dannyelectronics.wordpress.com/219

I can not open those links.

here is the first link: https://dannyelectronics.wordpress.com/2015/11/08/a-mcu-based-milliohm-meter-version-2/

the link for the hx711: https://dannyelectronics.wordpress.com/2015/10/25/a-hx711-based-milliohm-meter/

Thanks, but I'm looking or Arduino compatible code, preferably for the official AVR and M0+ and Due boards.

not all AVRs have differential inputs, and when they do, not all of them have PGAs. of the AVRs used in popular Arduinos, ATtinyx5 and ATmega32U4 chips offer such capabilities - the ATmega32U4 is an exceptional chip actually.

Unfortunately, many 32U4-based Arduino boards don't route ADC0/1. Bone headed move.

another chip to consider is the less popular AT90USB128x/teensy.

I don't use Due but the datasheet would be your starting point. A quick scan suggests that gain control is done via CGR. But in a very limited range.

I tried to find further information that would help you about the ATSAMD21, but I only managed to find the source code for the definitions of the Analog Comparator Controller (ACC), the Power Management Controller (PMC), and some example code as well. The example code follows, to avoid this being a link-only answer:
 #include "asf.h"
 #include "stdio_serial.h"
 #include "conf_board.h"
 #include "conf_clock.h"

 #define VOLT_REF   (3300)

 #define MAX_DIGITAL (4095)

 #define DACC_CHANNEL_0 0

 #define DACC_ANALOG_CONTROL (DACC_ACR_IBCTLCH0(0x02) \
                           | DACC_ACR_IBCTLCH1(0x02) \
                           | DACC_ACR_IBCTLDACCORE(0x01))

 #define ADC_CLOCK 6400000

 #define ADC_STARTUP_TIME_SETTING 0x8u

 #define ADC_TRACK_SETTING 0x0u

 #define ADC_TRANSFER_SETTING 0x1u

 #define ACC_SELPLUS_AD5  0x5u
 #define ACC_SELMINUS_DAC0  0x2u
 #define ACC_EDGETYP_ANY  0x2u
 #define ACC_INVERT_NO 0x0u

 #define STRING_EOL    "\r"
 #define STRING_HEADER "-- ACC IRQ Example  --\r\n" \
         "-- "BOARD_NAME" --\r\n" \
         "-- Compiled: "__DATE__" "__TIME__" --"STRING_EOL

 void ACC_Handler(void)
 {
     uint32_t ul_status;

     ul_status = acc_get_interrupt_status(ACC);

     /* Compare Output Interrupt */
     if ((ul_status & ACC_ISR_CE) == ACC_ISR_CE) {

         if (acc_get_comparison_result(ACC)) {
             puts("-ISR- Voltage Comparison Result: AD5 > DAC0\r");
         } else {
             puts("-ISR- Voltage Comparison Result: AD5 < DAC0\r");
         }
     }
 }

 static void configure_console(void)
 {
     const usart_serial_options_t uart_serial_options = {
         .baudrate = CONF_UART_BAUDRATE,
         .paritytype = CONF_UART_PARITY
     };

     /* Configure console UART. */
     sysclk_enable_peripheral_clock(CONSOLE_UART_ID);
     stdio_serial_init(CONF_UART, &uart_serial_options);
 }

 static void dsplay_menu(void)
 {
     puts("-- Menu Choices for this example--\n\r"
             "  s: Set new DAC0 output voltage.\n\r"
             "  v: Get voltage on potentiometer.\n\r"
             "  m: Display this menu again.\r");
 }

 static int16_t get_input_voltage(void)
 {
     uint8_t i = 0, uc_key;
     int16_t us_value = 0;
     int8_t c_length = 0;
     int8_t ac_str_temp[5] = { 0 };

     while (1) {
         while (uart_read(CONSOLE_UART, &uc_key)) {
         }
         if (uc_key == '\n' || uc_key == '\r') {
             puts("\r");
             break;
         }

         if ('0' <= uc_key && '9' >= uc_key) {
             printf("%c", uc_key);
             ac_str_temp[i++] = uc_key;

             if (i >= 4)
                 break;
         }
     }

     ac_str_temp[i] = '\0';
     /* Input string length */
     c_length = i;
     us_value = 0;

     /* Convert string to integer */
     for (i = 0; i < 4; i++) {
         if (ac_str_temp[i] != '0') {
             switch (c_length - i - 1) {
             case 0:
                 us_value += (ac_str_temp[i] - '0');
                 break;
             case 1:
                 us_value += (ac_str_temp[i] - '0') * 10;
                 break;
             case 2:
                 us_value += (ac_str_temp[i] - '0') * 100;
                 break;
             case 3:
                 us_value += (ac_str_temp[i] - '0') * 1000;
                 break;
             }
         }
     }

     if (us_value > (5 * VOLT_REF / 6) || us_value < (1 * VOLT_REF / 6)) {
         return -1;
     }

     return us_value;
 }

 int main(void)
 {
     uint8_t uc_key;
     int16_t s_volt = 0;
     uint32_t ul_value = 0;
     volatile uint32_t ul_status = 0x0;
     int32_t l_volt_dac0 = 0;

     /* Initialize the system */
     sysclk_init();
     board_init();

     /* Initialize debug console */
     configure_console();

     /* Output example information */
     puts(STRING_HEADER);

     /* Initialize DACC */
     /* Enable clock for DACC */
     pmc_enable_periph_clk(ID_DACC);
     /* Reset DACC registers */
     dacc_reset(DACC);
     /* External trigger mode disabled. DACC in free running mode. */
     dacc_disable_trigger(DACC);
     /* Half word transfer mode */
     dacc_set_transfer_mode(DACC, 0);
     /* Power save:
      * sleep mode  - 0 (disabled)
      * fast wakeup - 0 (disabled)
      */
     dacc_set_power_save(DACC, 0, 0);
     /* Timing:
      * refresh        - 0x08 (1024*8 dacc clocks)
      * max speed mode -    0 (disabled)
      * startup time   - 0xf (960 dacc clocks)
      */
     dacc_set_timing(DACC, 0x08, 0, 0xf);
     /* Disable TAG and select output channel DACC_CHANNEL */
     dacc_set_channel_selection(DACC, DACC_CHANNEL_0);
     /* Enable output channel DACC_CHANNEL */
     dacc_enable_channel(DACC, DACC_CHANNEL_0);
     /* Setup analog current */
     dacc_set_analog_control(DACC, DACC_ANALOG_CONTROL);

     /* Set DAC0 output at ADVREF/2. The DAC formula is:
      *
      * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
      * ----------------------------------- = --------------------------
      *              MAX_DIGITAL                       digit
      *
      * Here, digit = MAX_DIGITAL/2
      */
     dacc_write_conversion_data(DACC, MAX_DIGITAL / 2);
     l_volt_dac0 = (MAX_DIGITAL / 2) * (2 * VOLT_REF / 3) / MAX_DIGITAL +
             VOLT_REF / 6;

     /* Initialize ADC */
     /* Enable clock for ADC */
     pmc_enable_periph_clk(ID_ADC);
     /*
      * Formula: ADCClock = MCK / ( (PRESCAL+1) * 2 )
      * For example, MCK = 64MHZ, PRESCAL = 4, then:
      *     ADCClock = 64 / ((4+1) * 2) = 6.4MHz;
      */
     adc_init(ADC, sysclk_get_cpu_hz(), ADC_CLOCK, ADC_STARTUP_TIME_SETTING);

     /* Formula:
      *     Startup  Time = startup value / ADCClock
      *     Transfer Time = (TRANSFER * 2 + 3) / ADCClock
      *     Tracking Time = (TRACKTIM + 1) / ADCClock
      *     Settling Time = settling value / ADCClock
      * For example, ADC clock = 6MHz (166.7 ns)
      *     Startup time = 512 / 6MHz = 85.3 us
      *     Transfer Time = (1 * 2 + 3) / 6MHz = 833.3 ns
      *     Tracking Time = (0 + 1) / 6MHz = 166.7 ns
      *     Settling Time = 3 / 6MHz = 500 ns
      */
     /* Set ADC timing */
     adc_configure_timing(ADC, ADC_TRACK_SETTING, ADC_SETTLING_TIME_3,
             ADC_TRANSFER_SETTING);

     /* Channel 5 has to be compared */
     adc_enable_channel(ADC, ADC_CHANNEL_5);

     /* Enable clock for ACC */
     pmc_enable_periph_clk(ID_ACC);
     /* Initialize ACC */
     acc_init(ACC, ACC_SELPLUS_AD5, ACC_SELMINUS_DAC0,
             ACC_EDGETYP_ANY, ACC_INVERT_NO);

     /* Enable ACC interrupt */
     NVIC_EnableIRQ(ACC_IRQn);

     /* Enable */
     acc_enable_interrupt(ACC);

     dsplay_menu();

     while (1) {
         while (uart_read(CONSOLE_UART, &uc_key)) {
         }

         printf("input: %c\r\n", uc_key);

         switch (uc_key) {
         case 's':
         case 'S':
             printf("Input DAC0 output voltage (%d~%d mv): ",
                     (VOLT_REF / 6), (VOLT_REF * 5 / 6));
             s_volt = get_input_voltage();
             puts("\r");

             if (s_volt > 0) {
                 l_volt_dac0 = s_volt;
                 /* The DAC formula is:
                  *
                  * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
                  * ----------------------------------- = --------------------------
                  *              MAX_DIGITAL                       digit
                  *
                  */
                 ul_value = ((s_volt - (VOLT_REF / 6))
                     * (MAX_DIGITAL * 6) / 4) / VOLT_REF;
                 dacc_write_conversion_data(DACC, ul_value);
                 puts("-I- Set ok\r");
             } else {
                 puts("-I- Input voltage is invalid\r");
             }
             break;
         case 'v':
         case 'V':
             /* Start conversion */
             adc_start(ADC);
             ul_status = adc_get_status(ADC);
             while ((ul_status & ADC_ISR_EOC5) != ADC_ISR_EOC5) {
                 ul_status = adc_get_status(ADC);
             }
             /* Conversion is done */
             ul_value = adc_get_channel_value(ADC, ADC_CHANNEL_5);

             /*
              * Convert ADC sample data to voltage value:
              * voltage value = (sample data / max. resolution) * reference voltage
              */
             s_volt = (ul_value * VOLT_REF) / MAX_DIGITAL;
             printf("-I- Voltage on potentiometer(AD5) is %d mv\n\r", s_volt);
             printf("-I- Voltage on DAC0 is %ld mv \n\r", (long)l_volt_dac0);
             break;

         case 'm':
         case 'M':
             dsplay_menu();
             break;
         }
     }
 }

I'm afraid you'll have to study how to configure the registers, taking the datasheet and, as a guideline, the ACC and PMC definitions linked above.

Thanks, but that is the ASF framework, and not how most Arduino code is (but I'm not sure). The Arduino has already all the bits defined for the differential and gain modes, for example "ADC_INPUTCTRL_GAIN_16X", but that might be the ASF framework as well (or not). I'm still like a rabbit staring into headlights.

I can feel and understand your frustration. I've searched but haven't been able to find exactly what you need. At this point I can only recommended that you take Nick Gammon's example code and modify it to configure instead the specific registers of the ATSAMD21 as per the linked ASF examples and definitions. Sorry...

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


text:
Can I make this changes to this diagram of a ESP32-CAM?
Have a good day! I am kinda new with electronics circuits, and therefore I got some doubts about this diagram of a ESP32-CAM.
I want to use a 5 V instead of 3.3 V. Do I need to add some resistors or capacitors to do so?
If the on-off switch is for turning on/off the device?
the push switch. It's a button that when GPIO13 receives changes on his signal activate a code (I mean, does it act like a button code activator) If it's not how can I put a button so the ESP32-CAM start /stop filming?

I got the image from this source
http://technoreview85.blogspot.com/2019/08/ESP32spycam.html

you cannot apply 5 V to a 3.3 V pin

@jsotola it does have a 5v pin. But  I didn't know if I do so I needed to add some more components

The ESP32-CAM can be powered via the 3.3V or 5V pins. It is safe to apply 5V to the ESP32 Vcc pin. Just make sure that no other ESP32 pin is exposed to a voltage over 3.3V.


text:
Can't read SD card
I get errors to open file on SD card. This is the instructions I use https://www.instructables.com/Micro-SD-Card-Tutorial/
/*
  SD card read/write

  This example shows how to read and write data to and from an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

I see "Initializing SD card..." and "initialization done." and "error opening test.txt"
Can you help me to solve problem?

run the CardInfo example. it is a diagnostic tool

Had you formatted the card in FAT32?

I added some delays to the code and it work perfectly now.
/*
  SD card read/write

  This example shows how to read and write data to and from an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");
  delay(1000);

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);
  delay(1000);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

your CS pins is not wired correctly if delays somehow help. it should work without the delays.

I ran your code unchanged on an Arduino Uno, and it worked first time. It output:
Initializing SD card...initialization done.
Writing to test.txt...done.
test.txt:
testing 1, 2, 3.

So your problem is either to do with the SD card itself or your connections to the board (or I suppose the SD card board could be faulty). For the card, make sure that it is formatted with FAT16 or FAT32. Mine is FAT32, and check that you can read and write to it using a PC - just drop a text file onto it to Write, and double click the text file to Read.
For the connections there is not really much to go wrong. Just check your wiring. And for the supply I used the 5v from the Arduino board.


text:
Can’t send string from arduino to processing via hc05
I’m trying to send and receive data from my laptop to arduino nano via hc05 Bluetooth for a rocket flight computer. For some reasons which I don’t know, I can send data from processing software using myPort.write() but cannot send a String back from arduino back to processing for telemetry purpose. At some point it was working, then stopped. I tried another code from HowToMechatronics.com and still it didn’t work. I’m using the Serial.println function on Hardware serial.
Pls help
In the processing code, I use all necessary libraries and functions e.g serialEvent(), myPort.bufferUntil(\n), myPort.readStringUntil(‘\n’)

Start by using something other than processing to try and receive your data. That way you can confirm which is the culprit: the Arduino setup or the Processing code.

I’ve done that. I first used the arduino ide, set the Port to COM8(Bluetooth )  and it didn’t work. I then used putty, also the same.

Ok, so next replace your firmware with a very simple one that just prints the value of millis() every second.

It works only on arduino serial monitor port not bluetooth Here’s the code I used.                                                     Void setup(){
Serial.begin(115200):
}
Void loop(){
float timer= millis();
Serial.println(timer);
Delay(1000);
}

Then it sounds like your problem is either hardware related or related to the bluetooth connection / configuration itself.

I removed both the hc05 and the nano from the circuit and made a new connection with voltage divide on a breadboard, still same result. Laptop can send data to bluetooth(arduino), but arduino can’t send back.   I also change the baud rate to 115200(formally 9600) using AT mode

Let us continue this discussion in chat.

Remove the HC05 from the Arduino. Connect the HC05 TX pin to the HC05 RX pin and power it from the Arduino. Try sending data from the PC and see if it gets echoed back.

Does the stop bit or parity bit of the Hc05 have anything to do with the transmission?

Update: After trying numerous codes, I was  sure that it wasn’t a software problem. I then removed the Hc05 module from the circuit, and I was able to put it in AT mode(this means my module is working fine). This leaves only one possible problem I.e the circuit. I used a multimeter to measure the voltage between Hc05 RX and GND. I got 1.8v(but how?). After retracing the connections, I figured out the problem was with the voltage divide I used to step down 5v to 3.3v. I used a 2k Ohm resistor in place of a 1k, and a 1k in place of the 2k resistor. So that’s why I’m getting a voltage of around 1.8v. Turns out 1.8v is too low for Hc05 rx pin to use. After correcting it, everything works fine


text:
Linear actuator with L298N board
I have a linear actuator that has 4 cables coming out, which I can control with the following connections:
red +  blue and black ⚫ + ⚪ white is going outside
red  + ⚪ white and black ⚫ +  blue is going inside
There is around 29 V going through those cables.
I also have L298N dual bridge DC and stepper motor controller board.
https://cdn.velleman.eu/downloads/25/wpi409a4v01.pdf

source:
https://cdn.velleman.eu/downloads/29/infosheets/vma409-schematic.pdf
Is it possible to use this to drive the linear actuator?

going outside, going inside ... what do these mean?

Basically CW and CCW (clockwise and counter clock wise).

please edit your post ... add information about how everything is connected ... also add the program that you are using ... do not write info in a comment

Your post is missing quite a bit of information (mainly the pinout & current requirement information), but I am going to answer it best I can with what is available.

Is it possible to use this to drive the linear actuator?

Maybe, it would depend on the voltage and current rating of the linear actuator you are using.
If the specs are within range, then yes.
The L298N can operate at a max voltage of 46V and provide a max current of 2A per channel.
The operating voltage of 29V as per your post is within specs of the L298N, the question comes down to the current requirement for the linear actuator.
Connections & Wiring:
Assumption:
The pinout is as follows:

Red - VCC
Blue - Direction 1
White⚪ - Direction 2
Black⚫ - GND

General Connections:

Red - VCC - Connect to VMS on the L298N board & Positive of your Power supply
Black⚫ - GND - Connect to GND & negative of your Power supply

Scenario 1: Actuator requires <2A
In this scenario, you are able to drive the actuator using just one of your output pairs and the connections are straightforward.

Blue - Direction 1 - Connect to 1st pin of Motor A
White⚪ - Direction 2 - Connect to 2nd pin of Motor A

Scenario 2: Actuator requires >2A & <4A
In this scenario, you will need to use both the motor outputs from the L298N to power the actuator to ensure that we are able to provide the required current

Blue - Direction 1 - Connect to 1st pin of Motor A & Motor B
White⚪ - Direction 2 - Connect to 2nd pin of Motor A & Motor B

Controlling the motor using an Arduino:
You can follow the sample code provided in the user manual for this.
Note: In the case of scenario 2, remember  that IN1 & IN3 should be driven the same value and the same goes for IN2 & IN4. If you get this wrong, you can possibly fry your motor driver board.
i.e:
If IN1 is HIGH, then so should IN3
If IN2 is LOW, then so should IN4
or in other words
If IN1 is HIGH and IN3 is LOW you can cause a shortcircuit and destroy your motor driver.