text:
16x2LCD Display serial read extra character
I get extra character (frowning face) when sending a text over the serial monitor(see attached image)

When empty string is sent over the serial monitor, the LCD display still shows the extra character of frowning face.
How do I get rid of the extra character?
I use the tutorial code below and change nothing in the code.
https://www.arduino.cc/en/Tutorial/LibraryExamples/LiquidCrystalSerialDisplay/
#include <LiquidCrystal.h>

    // initialize the library by associating any needed LCD interface pin
    // with the arduino pin number it is connected to
    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // initialize the serial communications:
      Serial.begin(9600);
    }

    void loop() {
      // when characters arrive over the serial port...
      if (Serial.available()) {
        // wait a bit for the entire message to arrive
        delay(100);
        // clear the screen
        lcd.clear();
        // read all the available characters
        while (Serial.available() > 0) {
          // display each character to the LCD
          lcd.write(Serial.read());
        }
      }
    }

Change "Newline" to "No Line Ending", or handle the termination manually (not a bad idea).

I don't see that character in the common character sets for HD44780 type drivers.  What exact display is it? And have you been playing round with character generator ram (custom characters)?

The LCD display acts a bit different to a normal console. For instance, it does not recognize the newline character and uses the corresponding ASCII code (10) like a normal letter. Depending on the letter map of your display (for which there are several variants on the market) this will print a more or less random character. To avoid this, you have to strip the last letter from the input string before sending it to the display.
For the same reason, sending an empty string does nothing, since an empty string sends no letters. To clear individual characters in the display, you have to overwrite them with a space.


text:
Mkr1000 Wifi Configuration
Is there a package similar to esp8266 WifiManager that supports wifi configuration for Arduino mkr1000?
I have searched everywhere and I got nothing

https://github.com/khoih-prog/WiFiManager_NINA_Lite

It shows error "Error compiling for board Arduino MKR1000."

sorry, I read MKR1010 and you have MKR1000. try to ask Khoi Hoang to make the library WiFi101 compatible. it should be simple.

I'll release a new WiFiManager_Generic_Lite, with functionality similar to WiFiManager_NINA_Lite, to provide support specifically to MKR1000 using WiFi101, as well as other generic boards (nRF52, SAMD, SAM-DUE, STM32, Teensy, AVR, etc.) using generic WiFi Shields (AT-command, WiFiNINA, etc.) within several days.
Please hold on,

The new library has just been released : WiFiManager_Generic_Lite in GitHub as well as Platform.io WiFiManager_Generic_Lite in PIO.
The following 2 examples are created specially for you to use and test

MKR1000_WiFi101
MKR1000_WiFi101_MQTT

Please test and post your feedback here. Post issues, certainly many with this new library, on WiFiManager_Generic_Lite issues
Cheers,

Amazing! please let me know

Please check the just released library in the answer.

source: Stack Exchange

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

sort: votes


text:
Trouble with laser sensor
I have trouble with my laser sensor it doesn't work properly. When I connect all pins its doesn't work, when I remove GND and connect just the signal pin and VCC it works but the laser light is dim(I saw the light when I look at the sensor carefully ). Can someone help me?

maybe someone that can read your mind to see what you are working with

Don't disconnect GND, when the other pins are still connected. That can result in parasitic currents running through the signal pin, which can damage the electronics of the sensor.

Please show all your connections in the circuit in your question (Schematic, Wiring diagram or high-resolution in-focus picture of the actual circuit) (your ACTUAL circuit, not the circuit from a tutorial, that you might have followed). Please also include your code in the question (and please format it correctly as code). Also please include a detailed description, what is not working. What did you expect to happen and what actually happened? ("doesn't work properly" is a rather useless as a problem description). You can include all this information in your question by editing it.

What is the module you used to detect laser light is it something like this https://ae01.alicdn.com/kf/HTB1gdUzxh9YBuNjy0Ffq6xIsVXaI.jpg, I think it is this module did you put the white sensor thingy to the female socket properly. (you can put it mistakenly in wrong way too)

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


text:
Arduino Nano Every USB Connection not working
I have two original (designed and assembled in Italy) Arduino Nano Every Boards from a German Web Shop. They came sealed in original packaging. When I try to connect them to my PC, they don't power up.
What I've tried so far:

6 different USB cables
1 Desktop PC with Arch Linux as well as Windows 10, all USB Ports available (front headers, back side motherboard)
1 Laptop PC with Arch Linux
1 Google Pixel 4 XL using a USB-B to -C adapter

No combination of the USB cables with any of the aforementioned USB Ports / Machines / Operating Systems allow the Arduino Nano Every Boards to boot up (no LEDs flashing).
I tried powering the boards using a 9V battery block on the V_in and GND pins, which works. I also tried powering the boards using a 9V battery block and then connecting the USB, but the aforementioned machines / operating systems do not recognize a new device connected via USB, despite the boards being powered (LEDs flashing).
I also triple-checked the physical connection of the USB cables on both ends to be sure they are inserted properly. I can use the aforementioned USB cables, USB ports, machines, and operating systems to charge other devices or transfer data with other devices (like, e.g., smartphones, e-book readers, USB flash memory sticks, external hard drives, ...).
What should I try next to get the Arduino Nano Every working?
Please let me know which extra information I should provide. Thanks!
Note: As far as I can see, using lsusb on Linux should always list connected USB devices, regardless of the groups my user's in. Nevertheless, I also loaded the cdc_acm module and added SUBSYSTEMS=="usb-serial", TAG+="uaccess" to a udev rule located at /etc/udev/rules.d/01-ttyusb.rules, and reloaded the udev rules, to no avail.

try to install the megaAVR boards package in IDE. it installs drivers too

thanks @Juraj, afaik the kernel module cdc_acm drives devices which support the Communication Device Class Abstract Control Model interface already. Apart from this, since the Arduino Nano Every boards I have do not even start, driver issues are of low probability imho.

Just to be really certain, in the case that you are USB-powering the boards, does the power LED light solidly?

Regarding Juraj's comment, I believe it is significant with respect to your Windows 10 testing, which I'm guessing is all he intended to related to. My memory that Windows requires the Arduino "driver" in some (all?) cases despite being a CDC-ACM interface. There's no driver proper in it though; no .sys file. It's just an .INF file that associates a built-in CDC-ACM .sys driver to the VID:PID/interface of the Arduino. It's just not entirely automatic in Windows as it is in Linux. That said, it need only enumerate on USB (even without "drivers") to at least list in some way in Device Manager.

Nope, there's no sign of life at all from the boards if USB is connected as described.

On the underside of the board there are test points for the D+ and D- signals near the USB connector and D12. I would voltage test these to GND while powered by VIN and take note of what voltages appear on them. Then unpower the board an continuity test each to the host end of a USB cable.

I've ordered an Arduino Nano (not "Every") from a different web shop now, and it powers up as soon as I connect to USB. Since the Arduino Nano uses mini-USB (the Arduino Nano Every uses micro-USB), I'm using a different cable from the ones I tried on the two Arduino Nano Every boards I have. But given that I tried multiple cables that also work with other devices, I'm confident now that the two boards I have are just broken. I've had bad luck.

These types of questions often requires considerable trouble shooting until the cause is found.  In order to make this useful to as many people as possible, let us compile a list of actions. (Add a comment if any have additional actions to try and I'll add them to the list.)

"...powering the boards using a 9V battery block on the V_in and GND pins..."

Confirm the 9V supply is connected to VIN. An internal voltage regulator will then provide the necessary 5V and 3V3 to the rest of the Nano-Every. Consider if 9V was accidentally connected to either the 5V or 3V3 pins, parts of the Nano-Every my be damaged.

"using lsusb on Linux should always list connected USB devices"

Yes, it should. If "lsusb" is typed before and after plugging in the Nano Every there should be an additional USB device listed.  If there is no change, there may be something physically wrong (bad cable or incorrect cable (i.e. charging only), bad Nano or burnt out part).
Also, "lsusb" normally does not require root privileges. But consider trying "sudo lsubs" to confirm all USB devices are seen.
Here is an example output of "lsusb" run when an Nano-Every was connected to a Ubuntu computer:
$ lsusb
...
Bus 001 Device 004: ID 2341:0058 Arduino SA Arduino Nano Every

"I also loaded the cdc_acm module ..."

Inspecting a Ubuntu system that can successfully program a Nano-Every, I see no package with the words cdc_acm in it installed.
(I'm going to have to look into the above. While Ubuntu's package manager does manage cdc-acm.ko, cdc-acm.ko exists.)

"...and added SUBSYSTEMS=="usb-serial", TAG+="uaccess" to a udev rule located at /etc/udev/rules.d/01-ttyusb.rules"

Be aware that adding a udev rule with a low value such as "01*" is likely to be obscured by any udev rule with a higher number should a match be found. Most developers add udev rules which start with a high number such as "99*" to mitigate this problem.
This said, it is unlikely a modification to udev rules is necessary. Most if not all Linux distributions will handle a USB/CDC type of peripheral adequately with out modifications. Plugging in a Nano-Every into the above mentioned Ubuntu computer generates a new device at /dev/ttyACM0.

"I tried powering the boards using a 9V battery"

Avoid using PP3 type 9 Volt batteries. They can be problematic when their lower current capacity has been reached.  At which point their output voltage may drop. Leading to unexpected results. If such a battery is necessary, pay close attention to current needs adding up all the expected maximum currents. In brief, lower powered processor on Arduino boards built using an LDO (Low DropOut regulator) have the best chance of working as expected. Other Arduino boards may not work as well and high current components such as a motor, solenoid or relay will likely not work.

you write: "there may be something physically wrong (bad cable or incorrect cable (i.e. charging only), bad Nano or burnt out part)."
Yes, exactly, that's why I tried 2 different arduino nano every boards using 5 different USB cables on 3 different machines using 3 different operating systems, where all of the mentioned items actually work apart from the 2 arduino nano every boards.

the cdc_acm is a kernel module that drives devices which support the
Communication Device Class Abstract Control Model interface (look into ls -l /lib/modules/$(uname -r), see also https://www.kernelconfig.io/config_usb_acm or https://www.keil.com/pack/doc/mw/USB/html/group__usbh__cdcacm_functions.html

I made a somewhat generic list of things to try so others might benefit too. I saw where you tried several cables. I wanted to ask if they were identical (perhaps all charging only) or from different manufactures. I see cdc-acm.ko now. I used "sudo dpkg -l | grep cdc | grep acm" which shows no such package on Ubuntu. I like @KIIV's idea of checking the 5V and 3V3 while supplying power through USB and also after switching to your 9V battery at VIN. That should tell us if the Nano-Every's regulators and power diode is working. Also, avoid using low current PP3 9V batteries.

It's some regression in linux core and 1200baud touch doesn't work properly (it seems it's used switching between updi mode and serial link).
I started using script mentioned in https://github.com/arduino/ArduinoCore-megaavr/issues/124 and i was able to upload it in most cases (but better than mostly failing) when I execute it few seconds before the upload.
For example curiosity nano board with Atmega4809 works perfectly as it's emulating debugger+serial+mass storage (but needs correct VID/PID in udev rules or connecting storage)
Mentioned script:
#!/usr/bin/python3
#   Run this script to reset the Arduino Nano Every
#   eg. sudo python3 mcu_reset.py
#
# Note: You must install pyserial first; i.e. sudo pip3 pyserial

import serial
import os, sys
# total arguments
n = len(sys.argv)
if n >= 2:
    port = sys.argv[1]
else:
    port = '/dev/ttyACM0'

print("Port: {}".format(port))

#re-enable hupcl temporarily (necessary for arduino reset using serial port)
os.system('sudo /bin/stty -F {} hupcl'.format(port))

try:
    #perform Arduino Nano Every reset "handshake"
    ser = serial.Serial()
    ser.baudrate = 1200
    ser.port = port
    ser.open()
    ser.close()

except serial.SerialException:
    print("Error: serial.SerialException")
    exit()

Thanks for your answer! Unfortunately, if the Board doesn't even turn on, isn't recognized by lsusb, and the USB to serial chip on the board doesn't run - how should setting a baudrate on that serial port help?

And it won't turn on even on USB charger? How about using 5V pin (with 5V input)? If first doesn't work and second works (which probably does as Vin is going through 5V too), then the protection diode between Vusb and +5V might be reversed or destroyed or the USB connector is somehow damaged

Maybe also check 3V3, it's powering the com chip Nano Every Schematics


text:
Does the MKR WIFI 1010 support the arduino mouse and keyboard controller?
I am working on a project right now that needs to connect to my computer via bluetooth and access the arduino mouse and keyboard library. In my research, I've found that only the Leonardo, Due, and Micro can emulate cursor movements, but they need to have additional hardware like the HC05. I would like to keep the amount of hardware I use to a minimum, but I understand if there is no way around it. Is there any way to use the MKR WIFI 1010 like a Leonardo, or would I need to get one of the aforementioned boards and then get a bluetooth module hooked up?
PS this is my first dive into bluetooth, so any additional resources to aid me in my journey would be much appreciated.

the USB magic is in the microcontroller ... compare the boards by microcontroller

Yes, the Arduino SAMD boards are supported by the Arduino Keyboard and Mouse library.
Nano 33 IoT is a smaler alternative to MKR 1010.
But the MKR1010 or the Nano33 IoT with original NINA firmware doesn't yet support classic Bluetooth like the HC-05 module. The ArduinoBLE library and the NINA firmware support only BLE which is different.
But there is a simple way to replace the NINA firmware with the ESP32 Arduino basic Bluetooth sketch SerialToSerialBT and then use it from the SAMD. This way the NINA module will be degraded to something like a HC-05.


text:
What is the baud rate for Wiegand?
I am attempting to develop an Arduino project that can identify the bit format of a card (26-bit being the most common but not the only one).
This a library sets the serial to be 9600 baud.
https://github.com/paulo-raca/YetAnotherArduinoWiegandLibrary
This documentation says the data bit width is about 100us and the "inter pulse" or the time between the data bit is 20-100us.
https://docs.tibbo.com/taiko/ser_wiegand_mode
I don't understand how these match up? Also, Wiegand isn't even really serial. It uses two inputs - One input is for the on bits and another input is for the off bits.

The library does never use anything regarding Serial. The examples use Serial as interaction way, to show the results to the user. Bit that has nothing to do with the Wiegand RFID reader

Just tested my HID multiCLASS SE RP40 920P with an oscilloscope.
Time between pulses: ~ 2 ms

Pulse duration: ~ 40 us

Measured a few different events, they seemed very consistent.

Wiegand doesn't have a baud rate as such. It's an edge-based input protocol where it looks for HIGH to LOW transitions on two different input lines.
There are certain timing requirements, in that you can't send data faster than the receiver is capable of receiving and pulses have to be wide enough for the receiver to read, and there is a minimum time for the gap between messages, but other than that there is no defined baud rate.


text:
How to connect SIM7100A to Arduino?
I've been searching for how to connect a SIM7100A module to an Arduino (Uno or Mega), but I haven't been able to find any posts anywhere, nor videos nor any kind of documentation that shows how to do it. Does anyone here know how to connect it so I can send simple AT commands to the module from the Arduino? (I just want to make GET requests and get GPS coordinates)

user guide https://m.media-amazon.com/images/I/91alo3EgWaL.pdf

I would expect connect power, ground, TX and RX. Just like any other MODEM.

Got it to work, in part thanks to the documentation that @Juraj posted.
My pinout is the following, in case anyone needs it:
SIM7100A -> Arduino Mega
SUPPLY -> 5V (the SIM7100A's SUPPLY pin powers the actual board, it's different from the VDD pin which is only for the Serial communication)
GND (both lower & upper) -> GND
VDD -> 3.3V
TXD -> RXD2
RXD -> voltage divider (5V to 3.3V) -> TXD2
Once the module is powered (the PWR LED is on), you gotta press the module's reset button for about 3 seconds and then wait for the NET and STA LEDs to turn on, then you can start sending AT commands to it.
I don't know if this will be the case for everyone, but for me, the serial communication through the SIM's USB debug port is with 9600 bauds, but the communication through the TXD and RXD pins is with 115200 bauds.


text:
How can I understand which arduino I need to run some code?
I want to build this project (but any other project would give me the same uncertainty):
https://github.com/ltpitt/arduino-n64-controller-library
But I cannot understand which arduino I can buy that will be compatible and also very small / easy to program / cheap.
There are countless possibilities but I cannot understand how can I match available code and compatible hardware.

Code written for an Uno will run as well on a Nano or a standalone atmega328P, if that's your question ? ? ? My concern were rather about the 3.3V signal level. Did not dive too deep into the underlying instructable, though.

I'd need a very small solution that can work with 5v or 3.3v (it will end inside a Nintendo 64).
Would this be ok for this code? https://www.kiwi-electronics.nl/beetle-arduino-leonardo

In this case, the description on Github says specifically that it is compatible with the Uno:

Based on the work in
  http://www.instructables.com/id/Use-an-Arduino-with-an-N64-controller/
  here comes a comfortable library for usage with e.g. Arduino Uno.

If you know in advance that you intend to write a very large body of code, of which this library is only a part, you can anticipate needing an Arduino with more memory at some point, but an Uno will get you a long way there. And, with all due respect, the fact that you're asking this question also suggests that an Uno will be more than adequate.
Genuine Italian Unos just barely exceed U$D 20 and Uno clones are about 2/3 of that price. Some of the clones may not be quite up to quality of the genuine boards, but reputable board makers' products are usually quite good. The best advice I can offer would be to buy a genuine Uno for your first board, both for the most likely best experience starting out, as well as to support the folks who did the upfront work and released the design as open source. Then maybe branch out to other board-makers' products for price, or especially, for added features (assuming those are useful to you) that some of them have engineered into their versions of the product.
Update:

My final goal is to put it into a Nintendo 64 so its size is really
  important. Something like this could be ok?
  kiwi-electronics.nl/beetle-arduino-leonardo

The Beetle's processor, AtMega32U4, has a similar memory complement as the Uno's AtMega328. In fact it has a little bit more RAM than the Uno. It should be quite doable to compile it for the Beetle.

My final goal is to put it into a Nintendo 64 so its size is really important.
Something like this could be ok?
https://www.kiwi-electronics.nl/beetle-arduino-leonardo


text:
SIM800L is unresponsive to AT commands
SIMM800L connected to Arduino UNO doesn't respond to AT command.
The serial monitor stops at
"initializing..."
the LED blinks every 3 seconds
VDD --> connected to 5v of the Arduino uno
    #include <SoftwareSerial.h>

//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

VDD --> connected to 5v of the Arduino uno ... you have to connect the GND and data lines also

Please use a separate power supply for the GSM module. Powering from Arduino board's VCC pin is not going to work.

I have worked a lot with SIM800L recently and usually people do the same mistakes working with it:

SIM800L expects to be supplied with 4V, not 5V.
It requires up to 2A of current, which can't be provided by Arduino powered from USB.
Arduino works with 5V logic level, but SIM800L with 3.3V. So you need to use a level converter or at least to connect RX pin of SIM800L through a resistive divider - two resistors 5K and 10K.
GND pin of Arduino must be connected to GND pin of SIM800L.

Each of these points can be the reason why your SIM800L isn't responding. Please make sure that all these requirements are satisfied, otherwise you can even burn your GSM module.

Thank you for your generous advice. I will try.


text:
Fastest Communication from NodeMCU to Arduino Nano
For one of my projects, I need to transmit data from NodeMCU to my Arduino Nano, in real time, I used S-Bus, but it quite unsatisfies me, as, slight latency is taking place.
I am transmitting a JSON file, with 4 signed 16 bit integeres.
Now,I need to know, what is the fastest and most reliable way to transmit data from NodeMCU to an Arduino Nano. Any detailed description, or even suggestion will be very much helpful. Thanks in advance !

what does the Nano do, what the NodeMcu can't do by itself?

What do you mean with "slight latency" exactly? And what S Bus library did you use? As the library, that I have found uses UART underneath, so with interface did you use at which baud rate?and do you really need to transmit JSON? using a binary protocol wiuld be way faster

If it comes to speed and reliability you have to choose an interface that is handled in hardware on both sides. For the arduino nano you have the following options (nodeMCU supports all of them):

UART:

not very fast (order of 10kbit/s), but it's full-duplex (asynchronous communication in both directions)
implementation is trivial due to Serial.h
long distance (order of meters)

I2C:

not very fast either (order of 100kbit/s), but not full-duplex
implementation is straight forward because both slave and master are implemented in arduino library
only over short distance (order of cm)

SPI:

quite fast (>1Mbit/s), full-duplex
implementation might require some experience (as far as I know, slave mode is not supported by SPI.h)
long distance (order of meters)

Which of those is the best option still depends on your specific requirements, but personally I like SPI very much because it is very fast and stable.

SPI is full duplex. All of those protocols can reach into the megabits-per-second (with the exception of UART if using SoftwareSerial.h which has an upper limit of about 9600 baud).

@Majenko you're right about SPI being full duplex, I will edit my answer. But I doubt that you are able to run either UART or I2C in the order of Mbit/s reliably on an atmega328. Also SPI might work at >10Mbit/s, I just made conservative estimations

Sure you can run it reliably at Mbaud. Why wouldn't you be able to? The fact that it's an 8-bit MCU doesn't mean that the hardware peripherals are slow too. It's more a question of if you can process the data you have received fast enough for Mbaud to make any real-world sense. As long as the baud rate error percentage at both ends of the connection are within tolerable amounts (which can just mean selecting the right baud rate to run at) you can go into the 1-4Mbaud range. The 16MHz clock speed limits your upper end more than anything else.


text:
Sending AT Command for sms to arduinoShield
i have a Arduino GSMShield and I want to send SMS.
When the module try to connecting to the network, it print AT+CREG?
Dont know why cause there's no serial.println for this
int8_t answer;
int onModulePin= 2;
char aux_str[30];

//Change here your data
const char pin[]="";
//const char phone_number[]=" number OK";
const char sms_text[]="Test-Arduino-Hello World";

void setup(){

  pinMode(onModulePin, OUTPUT);
  Serial.begin(115200);

  Serial.println("Starting..");

//  power_on();

  delay(3000);

  //sets the PIN code
  sprintf(aux_str, "AT+CPIN=%s", pin);
  sendATcommand(aux_str, "OK", 2000);

  delay(3000);

  Serial.println("Connecting to the network..");

  while( (sendATcommand("AT+CGREG?", "+CREG= 0,1", 500) ||
    sendATcommand("AT+CGREG?", "+CREG: 0,5", 500)) == 0 );

  Serial.print("Setting SMS mode..");
  sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
  Serial.println("Sending SMS");

  sprintf(aux_str,"AT+CMGS=\"%s\"", phone_number);
  answer = sendATcommand(aux_str, ">", 2000);    // send the SMS number
  if (answer == 1)
  {
    Serial.println(sms_text);
    Serial.write(0x1A);
    answer = sendATcommand("", "OK", 20000);
    if (answer == 1)
    {
      Serial.print("Sent ");
    }
    else
    {
      Serial.print("error ");
    }
  }
  else
  {
    Serial.print("error ");
    Serial.println(answer, DEC);
  }

}

void loop(){

}

void power_on(){

  uint8_t answer=0;
  Serial.println("2/2..");

  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    // power on pulse
    Serial.println("2*3..");
    digitalWrite(onModulePin,HIGH);
    delay(3000);
    digitalWrite(onModulePin,LOW);

    // waits for an answer from the module
    while(answer == 0){     // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
        Serial.println("3*2..");

    }
  }

}

int8_t sendATcommand(const char* ATcommand, const char* expected_answer, unsigned int timeout){

  uint8_t x=0,  answer=0;
  char response[100];
  unsigned long previous;

  memset(response, '\0', 100);    // Initialice the string

  delay(100);

  while( Serial.available() > 0) Serial.read();    // Clean the input buffer

  Serial.println(ATcommand);    // Send the AT command

    x = 0;
  previous = millis();

  // this loop waits for the answer
  do{
    // if there are data in the UART input buffer, reads it and checks for the answer
    if(Serial.available() != 0){
      response[x] = Serial.read();
      x++;
      // check if the desired answer is in the response of the module
      if (strstr(response, expected_answer) != NULL)
      {
        answer = 1;
      }
    }
    // Waits for the answer with time out
  }
  while((answer == 0) && ((millis() - previous) < timeout));

  return answer;
}


text:
Arduino ESP32-S3 MSC FW+Files
I want both, a Config file on the MSC and also FW Update via USB.
Right now I can choose on a Hold Button which should be done.
But it shows always two Drives instead of one.
One Drive is empty and the other one is with a file.
What do I need to change, that only one Drive is shown?
#if ARDUINO_USB_MODE
#warning This sketch should be used when USB is in OTG mode
void setup() {}
void loop() {}
#else
#include "USB.h"
#include "FirmwareMSC.h"
#include "USBMSC.h"
#include "FFat.h"
#include "FS.h"
#if !ARDUINO_USB_MSC_ON_BOOT
FirmwareMSC MSC_Update;
// USB Mass Storage Class (MSC) object
USBMSC msc;
#endif
#if ARDUINO_USB_CDC_ON_BOOT
#define HWSerial Serial0
#define USBSerial Serial
#else
#define HWSerial Serial
USBCDC USBSerial;
#endif
#endif

// Block size of flash memory (in bytes) (4KB)
#define BLOCK_SIZE 4096

// Flash memory object
EspClass _flash;

// Partition information object
const esp_partition_t* Partition;

void listDir(fs::FS& fs, const char* dirname, int numTabs = 0);

const esp_partition_t* partition() {
  // Return the first FAT partition found (should be the only one)
  return esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, NULL);
}

static int32_t onWrite(uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) {
  //Serial.println("Write lba: " + String(lba) + " offset: " + String(offset) + " bufsize: " + String(bufsize));

  // Erase block before writing as to not leave any garbage
  _flash.partitionEraseRange(Partition, offset + (lba * BLOCK_SIZE), bufsize);

  // Write data to flash memory in blocks from buffer
  _flash.partitionWrite(Partition, offset + (lba * BLOCK_SIZE), (uint32_t*)buffer, bufsize);

  return bufsize;
}

static int32_t onRead(uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) {
  //Serial.println("Read lba: " + String(lba) + " offset: " + String(offset) + " bufsize: " + String(bufsize));

  // Read data from flash memory in blocks and store in buffer
  _flash.partitionRead(Partition, offset + (lba * BLOCK_SIZE), (uint32_t*)buffer, bufsize);

  return bufsize;
}

static bool onStartStop(uint8_t power_condition, bool start, bool load_eject) {
  return true;
}

static void usbEventCallback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
  if (event_base == ARDUINO_USB_EVENTS) {
    arduino_usb_event_data_t * data = (arduino_usb_event_data_t*)event_data;
    switch (event_id) {
      case ARDUINO_USB_STARTED_EVENT:
        HWSerial.println("USB PLUGGED");
        break;
      case ARDUINO_USB_STOPPED_EVENT:
        HWSerial.println("USB UNPLUGGED");
        break;
      case ARDUINO_USB_SUSPEND_EVENT:
        HWSerial.printf("USB SUSPENDED: remote_wakeup_en: %u\n", data->suspend.remote_wakeup_en);
        break;
      case ARDUINO_USB_RESUME_EVENT:
        HWSerial.println("USB RESUMED");
        break;

      default:
        break;
    }
  } else if (event_base == ARDUINO_FIRMWARE_MSC_EVENTS) {
    arduino_firmware_msc_event_data_t * data = (arduino_firmware_msc_event_data_t*)event_data;
    switch (event_id) {
      case ARDUINO_FIRMWARE_MSC_START_EVENT:
        HWSerial.println("MSC Update Start");
        break;
      case ARDUINO_FIRMWARE_MSC_WRITE_EVENT:
        //HWSerial.printf("MSC Update Write %u bytes at offset %u\n", data->write.size, data->write.offset);
        HWSerial.print(".");
        break;
      case ARDUINO_FIRMWARE_MSC_END_EVENT:
        HWSerial.printf("\nMSC Update End: %u bytes\n", data->end.size);
        break;
      case ARDUINO_FIRMWARE_MSC_ERROR_EVENT:
        HWSerial.printf("MSC Update ERROR! Progress: %u bytes\n", data->error.size);
        break;
      case ARDUINO_FIRMWARE_MSC_POWER_EVENT:
        HWSerial.printf("MSC Update Power: power: %u, start: %u, eject: %u", data->power.power_condition, data->power.start, data->power.load_eject);
        break;

      default:
        break;
    }
  }
}

void setup() {
  HWSerial.begin(115200);
  HWSerial.setDebugOutput(true);

  Serial.begin(115200);

  Serial.println("Starting Serial");

  Serial.println("Initializing FFat");

  pinMode(0, INPUT);
  pinMode(17, OUTPUT);
  digitalWrite(17, LOW);
  delay(3000);

  // False for the msc mode and True for internal filesystem mode
  // Since both cannot write to the same table at the same time
  if (digitalRead(0)) {

    // begin(true) will format on fail
    if (!FFat.begin()) {
      Serial.println("Mount Failed, formatting...");

      // If mount fails, format the partition (Feels cleaner than FFat.begin(true))
      if (FFat.format(FFAT_WIPE_FULL)) {
        Serial.println("Format Success");
      } else {
        Serial.println("Format Failed");
      }
    } else {
      Serial.println("fat success");
    }

    Serial.println("Listing before");

    listDir(FFat, "/");

    if (!FFat.exists("/config.json")) {
      Serial.println("Creating file");
      // Create a file | use F("...") on file paths or it creates weird problems (idk why)
      File f = FFat.open(F("/config.json"), FILE_WRITE, true);

      // Write to file (using F("...") here just to be safe)
      f.println(F("{\n  \"r\": 255,\n  \"g\": 0,\n  \"b\": 0,\n  \"w\": 0,\n  \"offset\": 0\n}"));

      // Close and flush file (Not sure if flush is needed, but there to be safe)
      f.flush();
      f.close();

      Serial.println("Listing After");

      // Print directory contents
      listDir(FFat, "/");
    }
  } else {
    digitalWrite(17, HIGH);
    delay(3000);
    Serial.println("Initializing MSC");
    // Initialize USB metadata and callbacks for MSC (Mass Storage Class)
    if (digitalRead(0)) {
      Serial.println("Getting partition info");
      // Get partition information
      Partition = partition();
      msc.vendorID("ESP32");
      msc.productID("USB_MSC");
      msc.productRevision("1.0");
      msc.onRead(onRead);
      msc.onWrite(onWrite);
      msc.onStartStop(onStartStop);
      msc.mediaPresent(true);
      msc.begin(Partition->size / BLOCK_SIZE, BLOCK_SIZE);
      digitalWrite(17, HIGH);
    } else {
      MSC_Update.onEvent(usbEventCallback);
      MSC_Update.begin();
      digitalWrite(17, LOW);
    }

    USBSerial.begin();
    Serial.println("Initializing USB");

    USB.begin();

    Serial.println("Printing flash size");

    //Print flash size
    char buff[50];
    sprintf(buff, "Flash Size: %d", Partition->size);
    Serial.println(buff);
  }
}

void loop() {
  delay(5000);
}

void listDir(fs::FS& fs, const char* dirname, int numTabs) {
  File dir = fs.open(F(dirname));

  if (!dir) {
    Serial.print("Failed to open directory: ");
    Serial.println(dirname);
    return;
  }
  if (!dir.isDirectory()) {
    Serial.println("Not a directory");
    return;
  }

  while (true) {
    File file =  dir.openNextFile();
    if (!file) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(file.name());
    if (file.isDirectory()) {
      Serial.println("/");
      // Ugly string concatenation to get the full path
      listDir(fs, ((std::string)"/" + (std::string)file.name()).c_str(), numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t\tSize: ");
      Serial.println(file.size(), DEC);
    }
    file.close();
  }
}


text:
HC-05 bluetooth not working
i connect HC-05 to L293d Driver shield ( vcc to + / Gnd to - / rxd to 1 / txd to 0) but the HC-05 keep flashing red and blue light what does that mean?

Frequency of the blinking?

What is your main controller? Arduino UNO?

The red status LED on the HC-05, has three states:

Rapid Flashing - Looking to pair but unpaired

Slow flashing with a period of around 2 seconds - Paired

Slow double flashes - in AT command mode.


text:
Using an A4988 stepper motor driver for a low current (15mA) stepper motor
I have a BKA30DR5 stepper motor that operates at 15mA. I want to drive it using an A4988 stepper motor module. I've previously driven stepper motors that use much higher currents (around 1A) successfully with these modules so I figured I'd use it again.
I set the reference voltage on the module according to this method, combined with the information on this page. The current sense resistors on the board read R100 so my formula for calculation the reference voltage is 0.015A * 8 * 0.1 Ohms = 0.012V. That's such a low voltage that I have trouble setting it using the trim pot: I have to make minuscule adjustments once I get below the 0.02V range and even then it just goes from 0.02V to 0.005V seemingly at random. I guess the trim pot becomes inaccurate at that very very low range.
How do I get the module to provide the correct reference voltage to the motor? I guess the motor uses so little power that I could technically skip the module entirely and connect it directly to the pins on the Arduino but I'm not sure if that's safe for the arduino considering back EMF. Perhaps it's also possible to set the module to a higher reference voltage and then use a separate resistor to drop the voltage to the correct amount but I'm not sure if that even works with stepper motors, nor where between the module and the motor the resistor(s?) should be connected.
Any ideas?

Is your motor currently not running at all, or is it stuttering?

I have not hooked it up yet for fear of destroying it.


text:
Can't get serial port's attention once sketch is running
This sketch is supposed to listen for a single character sent to the serial port, as a means of starting and stopping data collection (which in this example is mocked by printing some register values).  It reacts to the first character sent (g), and the while loop begins executing.  But it doesn't react to a subsequent s character, it seems I can't get Arduino's attention.
Perhaps this is related to this answer but I'm not sure.  If that's the problem, I could use some general suggestions about how to work around the limitations.  If it's something else, well obviously I need a suggestion for that as well!
// Listen to the Serial Port for Instructions and Print Register Values

volatile boolean start = false;  // flag to start register inspection; global

void setup() {
  Serial.begin(9600);
  if (Serial) {
    Serial.println("Arduino listening...");
    Serial.println("Enter g or s at any time");  // g = go, s = stop
  }
}

void loop() {
  unsigned char data;
  if (Serial.available()) {
    data = Serial.read();
    Serial.println(data); // only for troubleshooting
    if (data == 'g') {
      start = true;
    }
    else  if (data == 's') {
      start = false;
    }
  }

  while (start) {
    // print the values of some ADC registers
    Serial.print("ADMUX  register: ");
    print_bin(ADMUX);
    Serial.print("ADCSRA register: ");
    print_bin(ADCSRA);
    Serial.println(" ");
    delay(1000);
  }
}

void print_bin(byte aByte) {
  for (int8_t aBit = 7; aBit >= 0; aBit--) {
    if (aBit == 3) {
      Serial.print(" ");
    }
    Serial.print(bitRead(aByte, aBit) ? '1' : '0');
  }
  Serial.println(" ");
}

Environment:
Version: 2.3.0
Date: 2024-02-07T13:40:21.377Z
CLI Version: 0.35.2

There is nothing in your while (start) { loop that would allow start to become false.
  while (start) {
    // print the values of some ADC registers
    Serial.print("ADMUX  register: ");
    print_bin(ADMUX);
    Serial.print("ADCSRA register: ");
    print_bin(ADCSRA);
    Serial.println(" ");
    delay(1000);
  }

...and so your loop continues while data is piling up in Serial's input buffer.
loop() is already a functional loop. Changing while (start) { to if (start) { seems to be what you're looking for.
void loop() { // <-- existing loop
  unsigned char data;
  if (Serial.available()) {
    // stuff that can change start
  }

  if (start) {
    // stuff that happens if start is true
  }
}

You may want to look at the blink without delay example for handling your delay(1000) differently.

Dang, I set up a loop inside a loop with no escape from the inner loop once it was going!  Thanks for the second set of eyes!  Just couldn't see that for some reason.

And thanks for the link to the blink nuances.  I don't actually need that delay in there, but I need to keep learning about Arduino blocking, interrupts etc.  Many details are not readily apparent when one is already learning a lot of new stuff.


text:
How to extract hex file from working MKR Zero
I have an Arduino MKR Zero which has working code on it, but I've lost the source. Is there a way that I can download the hex file from it, and then how can I upload it to a second so that I then have 2 working boards?
Thanks.

The Arduino MKR Zero appears to use the "Arm® Cortex®-M0 32-bit SAMD21" processor from Microchip. Usually to read everything in a processor's memory for copying to another requires the OEM's hardware and software tools. Providing the original programmer did not activate any type of "do not allow reading" feature in the processor. I'm posting as a comment as someone may know a less expensive/easier way to use the embedded Arduino firmware to read the processors program memory.

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". -- Without the same hardware, I refrain to write an actual answer. However, read the documentation of the tool that the IDE uses to upload the compiled sketch. I'm pretty sure it can download the binary. You might need to use the command line. -- If you succeed, please write an own answer and mark it.


text:
Arduino Mega 2560 time delays counting between events on different pins
I am wondering how I can precisely count time delays between rise events happening on 4 different lines/pins using Input Capture of Arduino Mega 2560. How can I synchronize timer/counters? Appreciate your help and suggestions.

precisely count time delays ... please define precisely

You can't. At least not without modifying the hardware.
The ATmega2560 microcontroller at the hearth of the Arduino Mega has
four input capture units, wired to the input capture pins ICP[1345].
Unfortunately, only two of those pins are routed on the Arduino board.
The table below list the four ICP pins, with their pin numbers on the
TQFP package and on the Arduino board:
   pin     package  Arduino
───────────────────────────
ICP1/PD4     47        --
ICP3/PE7      9        --
ICP4/PL0     35        49
ICP5/PL1     36        48

Unless you manage to solder wires to the missing pins, you won't be able
to use the four input capture units.
As for the synchronization, you have two options:

If you are using the prescaler (i.e. a prescaler factor larger than
one), you should use its “prescaler reset” feature with the TSM bit
(Timer/Counter Synchronization Mode) enabled. This will let you
start the four timers simultaneouly when you clear the TSM bit. See
the MCU datasheet for details.

If you are not using the prescaler, you can just start the four
timers in quick succession, with interrupts disabled. They won't
start quite at the same time, but you can compensate for this when
setting their initial values.

As an example of the second option, the following function starts the
four timers without prescaler and counting in sync:
void init_timers() {
    // Clear the timer configurations.
    TCCR1A = 0; TCCR1B = 0;
    TCCR3A = 0; TCCR3B = 0;
    TCCR4A = 0; TCCR4B = 0;
    TCCR5A = 0; TCCR5B = 0;

    // Set the initial values.
    TCNT1 = 0;
    TCNT3 = 2;
    TCNT4 = 4;
    TCNT5 = 6;

    // Start the timers.
    noInterrupts();
    TCCR1B = _BV(CS10);
    TCCR3B = _BV(CS30);
    TCCR4B = _BV(CS40);
    TCCR5B = _BV(CS50);
    interrupts();
}

The section that starts the timers compiles to this assembly:
cli              ; noInterrupts();
ldi r24, 0x01    ; r24 = _BV(CS10)
sts TCCR1B, r24  ; TCCR1B = r24
sts TCCR3B, r24  ; TCCR3B = r24
sts TCCR4B, r24  ; TCCR4B = r24
sts TCCR5B, r24  ; TCCR5B = r24
sei              ; interrupts();

As the sts instruction completes in two clock cycles, this delay will
compensate for the offset in the initial timer values.
Now, if you don't care about microsecond-level accuracy, you can forget
about the timers and use external interrupts (or pin change interrupts)
and record the times with micros().


text:
How to know if a tof VL53L0x sensor is dead or not
I bought a bunch of VL530X time-of-flight sensors on Aliexpress. They seemed to work fine. Then I connected two of them on the same Arduino Uno board to test with the Adafruit example "dual". During rewiring I may have used the 5v power pin of the Arduino instead of the 3.3v (I can't remember).
Now the sensors won't boot. They fail during setup with error -6 which is documented as "RANGE ERROR".
Yet, scanning for either of them does find a sensor at the default address 0x29.
How can one know if they're dead or if they can somehow be revived?
The Uno works fine with any other VL53L0x, just not those two. I could certainly just trash the ones that won't boot but I would be interested in a procedure to know for sure; it would be very useful when going into production.
The last answer on this thread an ST forum points to the I2C bus, but I don't understand what is being recommended.

If others work and these don't, and the wiring and code is the same then yes, they are dead. What about them has died? Impossible to tell. It's basically one chip on a board. Maybe the laser diode has burned out. You could try inspecting it with your mobile phone camera which may be able to see the infra-red light - try it with a good one first and compare it. Not much else you can do beside that.

Thank you. What is confusing to me is that they respond to scanning. I was hoping there would exist some probing software that would be able to diagnose the problem further...


text:
Problem communicating Using Nrf24l01+pa+lna, I am receiving 00 Hex
I am trying to build a wireless switch. At one end, I have Arduino Uno connected to Nrf24l01+pa+lna module. While at the other end there is Arduino Nano connected to Nrf24l01+pa+lna and a relay. I send char '1' or '0' through Nrf24l01 attached to Arduino Uno. Nrf24l01 attached to  Arduino Nano  receives this char and turns on or off the relay connected to Pin D3 of Arduino Nano. The my Arduino Nano replies back as '1' or '0'. Uno receives it and displays it on serial monitor.
At start the communication sometimes worked and sometimes didn't. Then I connected a 10uF capacitor to the both Nrf24l01 modules. Now I am receiving 00 Hex and relay is also not responding. Can any one help. Code is attached.
// Arduino Uno Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte addresses[][6] = {"00001", "00002"};

char serialChar;
char motorChar;

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(addresses[1]); // 00002
  radio.openReadingPipe(1, addresses[0]); // 00001
  radio.setPALevel(RF24_PA_MIN);
}

void loop() {
    radio.stopListening();
    if (Serial.available() > 0) {
      serialChar = Serial.read();
      radio.write(&serialChar, sizeof(serialChar));

      delay(5);
      radio.startListening();
      while (!radio.available());
      radio.read(&motorChar, sizeof(motorChar));
      Serial.print(motorChar);
    }
}

//Arduino Nano Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte addresses[][6] = {"00001", "00002"};
char command;
int relayPin = 3;

void setup() {
  radio.begin();
  radio.openWritingPipe(addresses[0]); // 00001
  radio.openReadingPipe(1, addresses[1]); // 00002
  radio.setPALevel(RF24_PA_LOW);

  pinMode(relayPin,OUTPUT);
  digitalWrite(relayPin, HIGH); // Relay is Now Off
}

void loop() {
    delay(5);
    char state = '0'; // switch is off
    radio.startListening();

    if (radio.available()) {
      radio.read(&command, sizeof(command));
      if(command == '1'){
        digitalWrite(relayPin,LOW); // Relay is Now On
        state = command;
        delay(5);
        radio.stopListening();
        radio.write(&state, sizeof(state));
      }
      else if (command == '0'){
        digitalWrite(relayPin, HIGH); // Relay is Now Off
        state = command;
        delay(5);
        radio.stopListening();
        radio.write(&state, sizeof(state));
      }
      else{
        delay(5);
        radio.stopListening();
        radio.write(&state, sizeof(state));
      }

    }
}

00 hex and 0 are the same number

Your radio receiver is not listening most of the time due to radio.stopListening();

Today i turned my Project on again. Now i am receiving nothing . That's too frustrating. I have working on this project since a month :(


text:
How to make car turn 90 degrees?
I have an elegoo car model and am trying to make it turn 90 degrees whenever it gets to a 90 degree turn. This model has line tracing and it works fine on curved surfaces but doesn't work so on 90 degree turns.
    /Line Tracking IO define
#define LT_R !digitalRead(10)//connected to pin 10. Value is inverted
#define LT_M !digitalRead(4)
#define LT_L !digitalRead(2)

#define ENA 5//input to enable motor A. Controls speed
#define ENB 6//input to enable motor B
#define IN1 7//Control spinning direction of motor A. If one of them is high motor spin(an OR gate)
#define IN2 8//Same motor A
#define IN3 9//3 and 4 are for motor B
#define IN4 11

#define carSpeed 100

void forward(){ //car goes forward
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("go forward!");
}

void back(){ //car goes backwards
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("go back!");
}

void left(){ //goes left
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("go left!");
}

void right(){ //goes right
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("go right!");
}

void stop(){ //power is shut off
   digitalWrite(ENA, LOW);
   digitalWrite(ENB, LOW);
   Serial.println("Stop!");
}

void setup(){
  Serial.begin(9600);
  pinMode(LT_R,INPUT);//takes input from all the sensors
  pinMode(LT_M,INPUT);
  pinMode(LT_L,INPUT);
}

void loop() {

  if(LT_M){
    forward();
    while(LT_M);
  }
  else if(LT_R) {
    right();
    while(LT_R);
  }
  else if(LT_L) {
    left();
    while(LT_L);
  }

  else if (LT_M && LT_R && !LT_L) {
  delay(500);
  right();
  }

  else if (LT_L && LT_R && !LT_R) {
   delay(500);
   left();
    }

Your code is not complete. Sometime you use pins ENA and ENB with digitalWrite and sometimes with analogWrite. #define LT_R !digitalRead(10) is a macro definition: So, what is the meaning of pinMode(LT_R,INPUT); ;-)?  I wonder why parts of this program work.

PeterPaulKiefer is right with the pinMode statements. That will only configure either pin 0 or 1 as input. It cannot work as you wanted. Most likely you are profiting here from the fact, that at startup all the pins are already configured as inputs.

First: Your code as 2 problems:

As stated in the comments by PeterPaulKiefer, when you use
  pinMode(LT_R,INPUT);

That is not working as intended by you. LT_R is defined at the top as
  #define LT_R !digitalRead(10)

Thus the compiler will see
  pinMode(!digitalRead(10), INPUT);

digitalRead() will return zero or one, thus you are configuring pin 0 or pin 1 here (depending on the state of the sensor at startup). Instead you need to directly use the pin number (10) or use another define for the pin number itself. Your code only works, because all the pins are configured as INPUT (tristate) at startup of the microcontroller, so that they don't break something with a wrong signal. You got lucky there.

The last two else if statements are never executed:
  else if (LT_M && LT_R && !LT_L) {
      delay(500);
      right();
  }
  else if (LT_L && LT_R && !LT_R) {
      delay(500);
      left();
  }

The conditions here will first evaluate LT_M (in the first statement) and LT_L (in the second statement) respectively. Only if these are true, the rest of the expression will be evaluated. But you already checked for both of them being true above. When they are, the following else if statements don't get executed (thats the logic of if else statements). And if they are false, the code will also not be executed.
When you get to a 90° right corner, the middle and right sensor will trigger. Currently this will lead to the robot just keeping going forward.

So you need to change your code to actually check every every possible combination of the sensor states.
Also keep in mind, that a sharp corner needs way more turning, than a curve. Depending on the width of the line are the distance between your sensors, you might or might not be able to distinguish between those two cases. You should analyze, which sensor states you would have in which situations, write that down and then write code for every state. You could also put all sensor states into one single number, so that it is easier to check for it in the code. Something like this:
byte all_states = digitalRead(2) + 2*digitalRead(4) + 4*digitalRead(10);

Each combination will give you a unique number to work with. Effectively this stores the states of the sensors in one bit of the number each. Bit 0 is for pin 2, bit 1 is for pin 4 and bit 2 is for pin 10. You can also write this with bitwise operators:
byte all_states = digitalRead(2) | (digitalRead(4)<<1) | (digitalRead(10)<<2);

For example: If the right sensor is triggered, but not the others, you would get a binary number 0b00000100, which is decimal 4. If the left and the middle sensor are triggered, but not the right one, this results in 0b00000011, which is decimal 3. Then you could check with a switch statement:
switch(all_states){
    case 0: //No sensors triggered
        break;
    case 1: // Left sensor triggered
        break;
    case 2: // middle sensor triggerd
        break;
    case 3: // middle and left sensor triggered
        break;
    ...
}

You see how it works. The code for each case then goes inbetween of each case and break line.


text:
How to stop my 16*2 lcd blink?
Here I wrote code for my weighting scale measurement. In which I added an on/off switch for my LCD display. But in defined delay time my LCD is a blink and I do not want it. I want my LCD switch on/off work on 1000 delay time effectively.
How I can do this. please guide and edit my code.
#include "HX711.h"
#include <LiquidCrystal_I2C.h>

HX711 scale(4, 5);//(DT, SCK)
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int buttonPin = 2;
int buttonState = 0;

float calibration_factor = -55;
float units;
float ounces;
float in_kg;

void setup()
{
  //  Serial.begin(9600);
  lcd.init();
  lcd.noDisplay();
  lcd.noBacklight();

  lcd.setCursor(0, 0);
  lcd.print("Calculate Weight");
  lcd.setCursor(0, 1);
  lcd.print("Loading...      ");
  delay(3000);

  scale.set_scale(calibration_factor);
  scale.tare();

}

void loop()
{
  units = scale.get_units(), 10;
  if (units < 0)
  {
    units = 0.00;
  }
  ounces = units * 0.035274;
  in_kg = units / 1000;

  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH)
  {
    lcd.setCursor(0, 1);
    lcd.print("Reading: ");
    lcd.print(in_kg);
    lcd.print("kg");

    lcd.backlight();

    // Display the text on the LCD.
    lcd.display();

    delay(3000);
    lcd.noDisplay();
    lcd.noBacklight();

  }

}

If this is the same question / project as your earlier arduino.stackexchange post you should delete this post and edit / change your earlier post.

@st2000 I deleted the previous question. please help me with this.

I am not sure what you are asking.  It appears the code will display the weight  value for 3 seconds and then turn off the back-light and blank the LCD.  And it sounds like you would like to change that from 3 seconds to 1 second.  Then all you have to do is change delay(3000) to delay(1000).

Don't use lcd.backlight() and lcd.noBacklight(), don't use lcd.noDisplay() every time your program runs the main loop() function. Set those things on once and leave them set.

@Dougie but I want to implement an on/off display and backlight through the switch on running device. SO how I do this?

You may need to clarify whether you're talking about an on/off that holds position or a momentary push button.  The latter meaning: push to turn on, push to turn off.


text:
Arduino - Function -> return Cstr instead of string
I have following function for my Arduino:
String readLine() {
  String received = "";
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n' or ch == '\r') {
      if (ch == '\r')
      {
        //get rid of the \n
        myFile.read();
      }
      return String(received);
    } else {
      received += ch;
    }
  }
  myFile.close();
  hasFile = false;
  return received;
}

This function is used to return a line from a text file on a SD card. Since I do have to do quite some things on the returned string, I would like to have it as cstr instead of string to increase performance. But I am not able to convert this function to one that returns a Cstr. I tried this but it does not work:
char* readLine() {
  char* received = "";
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n' or ch == '\r') {
      if (ch == '\r')
      {
        //get rid of the \n
        myFile.read();
      }
      return received;
    } else {
      received += ch;
    }
  }
  return received;
}

Currently I am converting it after the function returns it, by using c_str(). It works, but I dont like it and would like to return a Cstr in the first place.
How can this be done?
Thank you!

You cannot work with c-strings like with Strings. You need to use the standard c-string functions (like sprintf(), strcpy() and siblings) or directly access the char array.
This gives the following problems with your code:

See this line:
  char* received = "";

Here you create a pointer to a constant empty string. But this will NOT create a buffer, where you can put data. If you want to define a buffer to put the data in, you need to define an array:
  char received[30] = "";

where 30 is the size of the array and thus the buffer has space for 29 characters (30 minus the one character, that is needed for the terminating null character). Now you could use a counter variable to save the current position in the buffer and set the array elements to the received character:
  int position = 0;
  ...
  received[position] = ch;
  position++;

Then, when you reached the end of the buffer or you received end of line, you would end the data in the buffer with the null character:
  if (ch == '\n' || ch == '\r' || position == 29) {
      if (ch == '\r')
      {
          //get rid of the \n
          myFile.read();
      }
      received[position] = '\0';

Now you have the second problem: When defining a variable inside the function, it will become invalid, when you exit the function. You try to return a pointer to char, which will point to a non-valid memory location. Thus you cannot simply return an array, that was created inside the function (outside of dynamic allocation). Here commonly an external buffer is provided to the function by reference as a pointer. The function will then write into that buffer and does not need to return it.
  //defining the array outside of the function, for example at global scope
  #define BUFFER_SIZE  30
  char received[BUFFER_SIZE] = "";
  ...
  void readLine(char *buffer, int size) {
      ...
      // Here you can use buffer as a simple char array
      buffer[position] = ch;
  }

Here I also provide the size of the array as parameter, so that the function can make sure not to exceed that (because that will give you bad and difficult to troubleshoot problems). Then, when the function has run, the read data is now in the received character array. This way you don't need to use multiple buffers and also don't need to copy data between buffers.

One way is passing external buffer to readLine() to fill:
size_t readLine(char * buff, size_t maxChars) {
  size_t pos = 0; // current position in buffer
  while (file.myFileAvalable()) {
    buff[pos] = file.read();
    if (buff[pos] == '\n' || buff[pos] == '\r') {
      buff[pos] = '\0';   // terminate string
      break;              // end the loop
    }
    if (++pos == maxChars-1) { // don't forget about nul terminal character
      buff[pos] = '\0';
      break;              // end the loop
    }
  }
  return pos; // return number of read characters (0 nothing was read)
}

/// ...

char ssid[25] = {0}; // create buffer to store at most 24 characters + \0
char pass[25] = {0}; // it'll also fill buffers by zeroes

readLine(ssid, sizeof(ssid)-1);  // it'd be better to check how many characters was read
readLine(pass, sizeof(pass)-1);  // same here

WiFi.begin(ssid, pass);
/// ... But it looks much worst than String, however it's much more efficient, as using += for Strings is quite heap unfriendly

Big NO-NO is doing something like:
char* readLine() {
  char buff[50] = {0};
  // ... fill ...
  return buff;           // NO!!!! buffer doesn't exist after the return - you've got dangling pointer
}
// ...
char * ssid = readLine(); // dangling pointer after that...
char * pass = readLine(); // now the ssid location was overwritten for sure

Another NO-NO:
char* readLine() {
  static char buff[50] = {0}; // one buffer for all calls, it won't get destroyed after the end... but
  // ... fill ...
  return buff;           // ok, buffer exists after the return,...
}
// ...
char * ssid = readLine(); //
char * pass = readLine(); // but surprise surprise, ssid and pass points to the same buffer and therefore the same data...


text:
Explanation of code found online
i found following code online, to read the value of a touch sensor... i am having difficulties understanding how the 2 second timeout on the marked line works..
 if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {
touch_sensor_value is the value read from the touch input.. and the rest?? i dont see any comparison with anything in the parenthesis, i cant figure out how this if condition is working...
#define TOUCH_timeSeconds 2
uint64_t now = millis();
unsigned long lastTrigger_TOUCH = 0;
bool startTimer_TOUCH = false;
bool buttonIsPressed = false;

int touch_sensor_value = 0;
//Mux control pins
int s0 = 26;
int s1 = 27;
int s2 = 14;
int s3 = 12;
//State array
int currentState ;
//Mux in “SIG” pin
int SIG_pin = 33; //is touch sensor
void setup()
{
pinMode(s0, OUTPUT);
pinMode(s1, OUTPUT);
pinMode(s2, OUTPUT);
pinMode(s3, OUTPUT);

digitalWrite(s0, LOW);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);

Serial.begin(115200);
Serial.println(“Multiplexing 1 Touch sensor ESP32 using CD7HC4067 MUX”);

}

void loop() {

for (int i = 0; i < 16; i ++) {
currentState = readMux(i);
touch_sensor_value = touchRead(T9);

if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {    <-----!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);
buttonIsPressed = false;
startTimer_TOUCH = false;
return;
}

//

}

// delay(1000);
}

int readMux(int channel) {
int controlPin[] = {s0, s1, s2, s3};

int muxChannel[16][4] = {
{0, 0, 0, 0}, //channel 0
{1, 0, 0, 0}, //channel 1
{0, 1, 0, 0}, //channel 2
{1, 1, 0, 0}, //channel 3
{0, 0, 1, 0}, //channel 4
{1, 0, 1, 0}, //channel 5
{0, 1, 1, 0}, //channel 6
{1, 1, 1, 0}, //channel 7
{0, 0, 0, 1}, //channel 8
{1, 0, 0, 1}, //channel 9
{0, 1, 0, 1}, //channel 10
{1, 1, 0, 1}, //channel 11
{0, 0, 1, 1}, //channel 12
{1, 0, 1, 1}, //channel 13
{0, 1, 1, 1}, //channel 14
{1, 1, 1, 1} //channel 15
};

//loop through the 4 sig
for (int i = 0; i < 4; i ++) {
digitalWrite(controlPin[i], muxChannel[channel][i]);
}

//read the value at the SIG pin
int val = analogRead(SIG_pin);

//return the value
return val;
}

Does that code even compile? there is no operator between touch_sensor_value and (TOUCH_timeSeconds * 1000). Thus this would be handles as a function call, but touch_sensor_value is not a function, but a variable.

Link to the code?

@EdgarBonet https://microcontrollerslab.com/esp32-touch-sensor-button-example/ it's down below in the comments...

@chrisl thats actually what i am wondering too...

The comment form of a blog is not an appropriate place to publish source
code, as the content-management system (Wordpress here) quite often does
some destructive transformations. For example, here:
Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);

Wordpress tried to be “helpful” and replaced the ASCII quotes (") with
typographic quotes (“ and ”), which makes the line non-compilable.
As for the line you are asking about:
if ((touch_sensor_value  (TOUCH_timeSeconds * 1000)))

it is likely missing a less-than sign (<), as those are often stripped
from user-generated content for security reasons. I don't know why some
of those signs went through the filter, maybe it has something to do
with the white space surrounding them, but this is pure guess.
Given that the code has been destructively mangled, your options are
either to guess from the context, or post a comment asking for
clarification.

Thank you.. a < sign wouldnt make much sense, since touch_sensor_value holds the value of the sensor itself, and the part in parentehsis is a time...  there must be more missing... I'll try to figure it out.. thank you


text:
What components can be connected to pins 0/1 (RX/TX) without preventing uploading of code?
For a robot project I am using an Arduino Uno, and am running out of pins. The simplest solution would be to use digital pins 0/1. I know this means that I won't be able to use Serial communication (which is fine), but I also know that these pins are also used when uploading code to the board, and connecting components to these pins can interfere with the upload.
Are there certain types of components/interfaces that can be connected to these pins that won't interfere with the upload (without having to disconnect them every time I want to upload)?
In my case, I can choose between either using these pins to drive inputs for an L298N motor driver (TTL inputs), or to read quadrature motor encoder signals. My guess would be that the latter won't work, as these signals may be high and interfere (and I don't know whether applying a voltage to the encoder outputs would cause damage - I have no datasheets for them).
However maybe the TTL inputs of the L298N would be fine? Or do I have no choice but to either have a switch to disconnect the when uploading or find some other way to reduce pin usage (or go for a bigger Arduino)?

a two position dip switch or four header pins with two jumpers ... https://duckduckgo.com/?q=dip+switch&iax=images&ia=images

This is a general electronic problem, not specific to pins 0/1 of the Arduino.
The basic rule is:

An input can only accept one signal

But

One signal can go to many inputs

In other words any INPUT pin can only accept a signal from one place, but an OUTPUT pin can send its signal to many places at once.
The Arduino's serial connection has two signals - one input (RX) and one output (TX).  The input pin (RX) can only get its signal from one place, and when programming that "one place" needs to be the USB to UART converter's TX pin.  So anything connected to that pin that "sends a signal" will confuse everything and communication will fail.
Similarly the USB to UART converter's RX pin can only receive a signal from one place - in this case the Arduino's TX pin - connecting anything to this pin that could output a signal would confuse things and break communication.
So to round that up: you should be fine connecting anything that only receives a signal of some form (i.e., anything that is an INPUT, such as an RX pin or some form of control input like your motor controller) to either of those pins, but do not connect anything that can send a signal.
There is one caveat though: whatever you connect will receive the serial communication used while programming. That could have unintended consequences, like a motor spinning when you program the board.

Thanks, this is largely what thought. However, I would assume that some inputs may cause loading on the pin that would interfere? Such as an input with a pull up/down resistor will hold the voltage at a certain level, preventing correct operation?

And unwanted inputs to the motor drivers should be fine - when programming I wouldn't have the motors powered, and even they were these inputs would only be the direction controls - the pwm input should still be 0.

@Rustony The idea of a pullup or pulldown resistor is to provide a steady state when no logic signal is being applied. Any logic signal (such as the serial communication from the PC) should happily override a pullup or pulldown resistor.


text:
Directly synthesising an OOK modulated LF signal using a CSV file
I'm looking to transmit some data (CSV files) from a measurement instrument underground to a receiver on the surface. I've learned that in order to penetrate the limestone, low frequencies have to be used (around 80-130kHz). There are various methods to achieve this including ground-spike antennas that use the earth between two electrodes to help form a large antenna by injecting current into it, and magentic loop antenna pairs that essentially work as an inductor by transmitting and receiving the magnetic (H) component of the RF transmission rather than the low power E field component.
With that put aside, I've noticed that there aren't any existing RF modules that transmit at these frequencies. Because of that I've considered the posibility of directly synthesising a modulated signal using an Arduino (UNO or Nano). As far as I understand it I need a direct digital synthesis (DDS) IC to generate a reference frequency. From there I understand the Arduino can be used to calculate a waveform that simulates the modulation of that carrier in the mentioned frequency range. I've identified that on-off keying (OOK) would be a suitable modulation method due to its simplicity and resistance to noise.
This is where I need some help. How do I take a CSV file, use its contents to OOK modulate a carrier wave and then directly synthesise this waveform using Arduino? Are there libraries that already exist to enable this? If so, how would I use them? I don't have extensive programming knowledge so I'd appreciate any help I can get.

I've noticed that there aren't any existing RF modules that transmit at these frequencies. -- because of licensing. You're not allowed to in most places unless you have that frequency band allocated to you by the regulatory body for your area.

what hardware are you using? ... a library is useless if you have nothing for the library to control

You can just use raw Serial data for OOK control - that way it does all the start/stop framing for you.

@Majenko how can I do this? Do I mix the serial data with the carrier by analogue means at the output? Or am I missing some theory an experienced Arduino user has?

Serial will give you a digital on/off signal. Use that as the data input to your modulator circuit.


text:
Rotating Servo Motor using Arduino
Using arduino, I'm trying to rotate a 360 servo that will move clockwise 5 seconds,pause and counterclockwise for 5 seconds and then completely stop. However, my servo just continuously keeps on rotating in one direction. Any suggestions will be helpful

Please post your code and circuit, otherwise we can't really help you.

you have not put your code here so i can not understand it properly.From what i understand you must have put your code for rotating the servo motor 5 times in void loop. Don't do that put loop for rotating servo 5 time in setup.
void loop run continuously so it must be rotating 5 time then again 5 time and so on.


text:
Trouble using bluetooth module with the ESP32s2 feather board
I am trying to use an ESP32-S2 feather board with a separate bluetooth module, the Adafruit BLuefruit LE UART Friend. I previously used this bluetooth module with the Feather M0 Adalogger through UART without experiencing any major problems. Now, the bluetooth module does not even get past its begin function. In fact, in order for my program to even compile, I have to change the UART header and cpp files in the nRF51 library by commenting out Software Serial code (although, I don't actually use software serial) because the esp32 core does not have that library. Is this a matter of cores (esp32 as opposed to samd or avr) or something else entirely?

SAMD cores don't have SoftwareSerial. the Adafruit_BluefruitLE_nRF51 library has #define SOFTWARE_SERIAL_AVAILABLE   ( ! (defined (_VARIANT_ARDUINO_DUE_X_) || defined (ARDUINO_ARCH_SAMD) || defined (ARDUINO_STM32_FEATHER)) )


text:
Can't test for equality with string received from bluetooth module
I am trying to keep the program within a loop until the user inputs "ok" on the Bluefruit Connect App. I use the readString() function on the bluetooth object (ble) to read from it. Before this loop, my String command variable is initialized to be empty. Here is my code:
while(!command.equalsIgnoreCase("ok"))
{
  while(ble.available())
    command = ble.readString()
}

I have confirmed that I can receive data as I can output the command variable to the Serial monitor.
Why does the condition for this loop always return true (i.e. why is the String command variable never equal to the string literal "ok", while ignoring case)?

output the length of the command variable to serial monitor ... it may not be what you expect ... always do that when you're debugging code

@jsotola Wow you are right. When I send the string "ok" it says the length is 3. Is that the newline character being sent with it, or something else? How would I go about removing that extra character in the string?

this may help ... https://majenko.co.uk/blog/reading-serial-arduino

@jsotola It's working now!  Thank you so much!


text:
Serial.available is giving data even input data is not coming
Dear friends I have written a code to identify the caller and send a reply SMS to them using sim 800L and pro mini. My program is to identifying the caller number but continuously sending the SMS in an infinite loop. I am not getting what is the reason, kindly help me, thanks in advance. Code is attached
#include <SoftwareSerial.h>
SoftwareSerial Serial1(4,3);
String a;
String CellNumtemp;
String CellNum;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.println("AT");
  delay(1000);
  Serial1.println("AT+CSMP=17,167,0,0");
  delay(1000);
  Serial1.println("AT+CLIP=1");
  delay(1000);
   }

void loop(){
   if (Serial1.available() > 0){
   String a = Serial1.readString();
   String  CellNumtemp = a.substring(a.indexOf("+91"));
    CellNum = CellNumtemp.substring(0,13);
     Serial1.println("ATH");
     delay(500);
     Serial.println(CellNum);
     delay(500);
    if (a.indexOf("+91") >= 0){
        sendSMS();
       }
     }
  CellNum = "\0";
}

void sendSMS(){  // Function that sends SMS
     Serial1.println("AT+CMGF=1\r");
     delay(1000);
     Serial1.print("AT+CMGS=");
     Serial1.print("\"");
     Serial1.print(CellNum);
     Serial1.print("\"");
     Serial1.println("\r"); // to send SMS
     delay(1000);
     Serial1.println("Happy to see your call. I am good");
      delay(1000);
     Serial1.println((char)26);
     delay(1000);
     Serial1.println();
     delay(5000);
     Serial1.flush();
     delay(2000);
    }

what do you see in the serial monitor? ... use more Serial.println` statements to debug the code ... display the value of variables to see if the values are what you expect


text:
Weird SoftwareSerial behaviour with Arduino nano when multiple SoftwareSerial objects are configured
So I have been stuck with this for quite some days now and am really unable to put my finger on what's wrong here. Any help would be great. Try not to list down the disadvantages of SoftwareSerial, I know about them. Is this issue happening cause of it?
What I am trying to achieve? Two Arduino (Nanos) are connected to each other and are trying to communicate with each other via SoftwareSerial UART (multiple Arduinos are connected to multiple Arduinos but for the sake of keeping the code minimalistic, assume one-to-one communication).
Code for Arduino 1:
#include <SoftwareSerial.h>

String val = "4";

SoftwareSerial a(6, 7); // rx, tx
SoftwareSerial b(8, 9); // rx, tx
SoftwareSerial c(10, 11); // rx, tx
SoftwareSerial d(12, 13); // rx, tx

String a_s, b_s, c_s, d_s;

void setup() {
  a.begin(9600);
  b.begin(9600);
  c.begin(9600);
  d.begin(9600);
  Serial.begin(9600);
  a_s = "";
  b_s = "";
  c_s = "";
  d_s = "";
}

void loop() {
  delay(100);

  d.print(val);

  if(d_s == "") {
    if(d_s == "" && d.available()) {
      char rd = d.read();
      Serial.print("ddddddddddd ");
      Serial.println(rd);
      d_s = rd;
    }
  }
}

Code for Arduino 2:
#include <SoftwareSerial.h>

String val = "5";

SoftwareSerial a(6, 7); // rx, tx
SoftwareSerial b(8, 9); // rx, tx
SoftwareSerial c(10, 11); // rx, tx
SoftwareSerial d(12, 13); // rx, tx

String a_s, b_s, c_s, d_s;

void setup() {
  a.begin(9600);
  b.begin(9600);
  c.begin(9600);
  d.begin(9600);
  Serial.begin(9600);
  a_s = "";
  b_s = "";
  c_s = "";
  d_s = "";
}

void loop() {
  delay(100);

  b.print(val);

  if(b_s == "") {
    if(b.available()) {
      char rd = b.read();
      Serial.print("bbbbbbbbbbbb ");
      Serial.println(rd);
      b_s = rd;
    }
  }
}

Actual and Expected output for Arduino 1:
ddddddddddd 5
Actual output for Arduino 2: (no output!!)

Expected output for Arduino 2:
bbbbbbbbbbbb 4
While debugging, I realized if I comment out c.begin(9600) and d.begin(9600) from the code for Arduino 2, the actual output is the same as the expected output.
//   c.begin(9600);
//   d.begin(9600);

Ohh and yes, the connections are as follows:

ard1
ard2

GND
GND

D12
D9

D13
D8

Both the Arduinos are connected (and hence powered) via individual cables to the same laptop.
Is there something I am missing out on? I know SotfwareSerial has its downsides but is this something SoftwareSerial is causing? If yes, why is the actual output of Arduino 1 is same as the expected output? Shouldn't it have the same effect on both the Arduinos?
TIA!

Is one of the downsides of SoftwareSerial that you know about the fact that only one SoftwareSerial can be set to receive data at a time?
You have to select one and only one instance to receive data using the .listen() method.
If you want to be able to receive from multiple devices at once you will have to use either hardware UARTs or a single SoftwareSerial and a "bus" infrastructure (RS485 or similar).


text:
4 Digit 7 segment display flickering
I am attempting to make an Arduino counter using a 4 digit 7 segment display. The problem I am encountering is the display flickers. I am using an Arduino Uno and 5641AS digit display (so common cathode). Here is my program:
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
    Serial.println("The value of buttonPress is:  ");
    Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}

I suspect this issue has to do with sevseg.refreshDisplay(), I have tried moving it in the program with no avail. My wiring is correct, as the program displays the correct digits. Thank you!

It's probably the spamming of the serial that's slowing everything down.

remove the serial code and the button code ... display 1234 only ... does it still flicker

Thank you so much Majenko and jsotola!! Running the serial monitor output fixes it

With the help of Majenko and jsotola in the comments, I've got it fixed! It was the text I was displaying in the Serial Monitor that was slowing the display down. Here is the updated program that works:
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
// THE NEXT TWO LINES HAVE BEEN COMMENTED OUT FOR IT TO WORK
   // Serial.println("The value of buttonPress is:  ");
   // Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}

I'm leaving the program modifications here in case anyone else gets the same problem.


text:
Error Outputting Values Arduino Serial.print
I am experimenting with the following program I found online (with slight modifications):
int x;
void setup() {
 Serial.begin(9600);
 Serial.setTimeout(1);
}
void loop() {
 while (!Serial.available());
 x = Serial.readString().toInt();
 int y = x + 1;
 Serial.print(y);
}

I am encountering an error in Serial monitor output; if I input 1, I get 21 printed. I think what's happening is that every digit in a number gets incremented by 1, and then 1 is put at the end for some reason. For example, if I input 234, my output is 3451. I think the error lies with the line  x = Serial.readString().toInt();, but am unsure how to fix this. Thank you!

Why such a short timeout?

@EdgarBonet thank you for pointing this out! I'm not sure why the tutorial did this, but changing the timeout to 100 ms seems to fix this error!

There's two problems here.
First, you don't enter "234", you enter "2" followed by "3" and finally "4". Your really small timeout doesn't give the digits enough time to arrive.
Second, your line ending is being received and interpreted as "not a number" which is returned as 0 by .toInt().
What you need to do is:

Don't set a short timeout - you can remove that line entirely.
Use .readStringUntil('\n') to read up until your line ending in one go.

This worked, thank you for explaining everything too! If I remove the timeout entirely, there is notable input lag, so I just increased timeout to 100. Is there any downside to doing this?

Yes, you get a lag. Use the readStringUntil('\n') and the timeout is not used, so you get no lag.

Thanks - tried it and it works awesome.


text:
How "fast" could GPS data be refreshed while moving and does it depend on the mcu?
I'm using Nano Every and SIM33EAU GPS module for my project and today I went riding shotgun to test how it works when moving on the road. I am using u8g2 library and one of the things that I have printed on the screen is gps.course.deg - which is as the name suggest, course of the GPS module's movement in degrees.
Next to my Arduino device I had a phone with some compass app, and the course was somewhat correct while we were moving at normal traffic speed, but the update rate was vastly different and I don't know why. The only "delay" in the sketch I have is this;
  if (gps.location.isUpdated())
  {
    Serial.print(F("Lat Lon = "));
    Serial.print(gps.location.lat(), 6);
    Serial.print(", ");
    Serial.println(gps.location.lng(), 6);
  }

  else if (millis() - last > 500)
  ...

I wasn't able to check the Serial Monitor as I didn't have a laptop, so only reading from GPS module was what was being printed on the small OLED screen. So is the lagging update something on the GPS module side and how it works, or is it perhaps OLED not being able to refresh?

why are you asking for people to guess about your problem? ... this site is for providing answers, not guesses, so please ask a clear  answerable question and include all information that you have

GPS modules deliver position updates in very different frequencies, depending on model and configuration (where changeable). Cheaper modules only provide an update every 1 second, while better ones have 5 or 10 Hz position update. Check the documentation for your module to get that information.
Additionally, it is of course possible to "cheat", by calculating an extrapolation, using the last position, direction and speed. Since speed and direction don't typically change very quickly, that works quite well and can give position updates at arbitrary rates.

thanks @PMF I figured there had to be some internal limit, for some reason I thought all the consumer level GPS modules like the one I have are "50Hz" ... obviously completely wrong. So the mobile phone cheats, or do they put top class gps modules in there?

@Varonne I believe they cheat, but I can't tell you for sure. A "real" frequency of 5 or 10Hz is realistic even for decently priced modules. Downside probably is that they would use more power, which is also always a problem in cell phones. A top class GPS module that is used in professional navigation equipment is $15000 or so.


text:
Single LED controlled by two pushbuttons - one of which acts like a toggle switch
Trying to control this LED with those 2 pushbuttons - one button that starts a short flashing sequence, another pushbutton acts like a toggle switch, one press bulb is on, another press bulb is off.
If I switch the LED on and then push the flashing button, the on-off flashing starts but then the LED is shut off because off is the last state of the flashing sequence. How do I make the led turn to original state?
#include <ezButton.h>

const int flashing_pin = 2;
const int switch_pin = 3;
const int led_pin = 8;

ezButton button(switch_pin);

int ledState = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(led_pin, OUTPUT);
  pinMode(switch_pin,INPUT_PULLUP);
  pinMode(flashing_pin,INPUT_PULLUP);
  button.setDebounceTime(50);
}

void loop() {
  button.loop();

  if(button.isPressed()) {
    Serial.println("Press");

    ledState = !ledState;

    digitalWrite(led_pin, ledState);
  }

  if( digitalRead(flashing_pin) == LOW )   {
    doFlash(4);
  }
}

void doFlash(uint8_t number_of_times)  {
  while(  number_of_times-- > 0 ) {
    digitalWrite(led_pin,HIGH);
    delay(250);
    digitalWrite(led_pin,LOW);
    delay(250);
  }

}

To explain what I want in short;

if LED is off - flashing sequence works like "ON OFF ON OFF"
if LED is on - flashing sequence works like "OFF ON OFF ON"

digitalWrite(led_pin,HIGH); is hardwired ... digitalWrite(led_pin,!ledstate); is opposite to current state

I got it to work! But I'm confused by the loop state, in my original code there's a rule to doFlash(4); and delay 250 - but when using !ledstate, the 4 flashes are no longer 4 time (ON-OFF) cycles, it's half of it, and the 250 delay is double the time, it's half a second....so in order to get the desired "frequency" 4 flashes in 2 seconds, I need to put doFlash 8 and delay 125....can't figure out why :D but it works

My flash part of the code is this now;
void doFlash(uint8_t number_of_times)  {
while(  number_of_times-- > 0 ) {
ledState = !ledState;
digitalWrite(led_pin, ledState);
delay(125);
digitalWrite(led_pin, ledState);
delay(125);
}

i guess is that you have not looked at what you wrote very closely

ledState = !ledState does not belong in the blink code

I'll fix that - but it does work this way as I intended. But if that's bad practice in coding I'll revise it, I'm learning.

the 4 flashes are no longer 4 time (ON-OFF) cycles ... how is that the way you intended?

Oh - what I meant is that after I altered the code, the sequencing was correct and at a rate intended. But when I get the time I'll try with the fixed values for loop.


text:
Making pushbutton behave as a toggle switch with ezButton - do I have to use ledstate with =! operator
I'm using ezbutton to make a pushbutton act like a toggle switch, first press doing permanent on, second press doing permanent off. I'm just trying to understand the basic coding. This project is just a testbed for what I'm planning to do later - wiring vehicle toggle switches to Arduino and feeding the output signal to mosfet that will control the load state. So I'm trying to get the code as nice and tidy as I possible can. In the code below, I would like to know if ledState will be applicable when this sketch will control a mosfet instead of a test led, and I've seen comments saying "ledState = !ledState;" is not optimal - but being a beginner I'm not sure what this means, and is there a better more sound way to address it. Thanks!
#include <ezButton.h>

// ---
// Declaration
// ---

const int button1  = 9;
const int led1     = 4;
int ledState = LOW;

ezButton button(button1);

// ---
// Setup
// ---

void setup()
{

  pinMode(led1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  button.setDebounceTime(50);

}

// ***
// Main Loop
// ***
void loop()
{

  button.loop();

  if (button.isPressed()) {
    ledState = !ledState;
    digitalWrite(led1, ledState);
  }

}

what comments? if a button press should change the state from true to false and from false to true then this does it right.

Thanks @Juraj I'm just trying to understand the code that I managed to merge together from various examples I found, and as for ledState I haven't found explanation for it on Arduino's official reference pages, so I didn't know what did it do exactly

if : it works + you understand how it works , then it's find ;
ledstate = !ledstate ; //  is short and efficient to "flip flap" the boolean value

please take a coding course

@Varonne, does this code really toggle the ledState on then off with each button press?  I am thinking when you press the button the ledState will be switching on and off and on and off again and again as quickly as the processor will execute the code.  Then randomly stay on or off depending on when you release the button.

@st2000 it does work exactly as intended, with pushbutton it works as "first push = permanent on, second push permanent off" and doesn't do any random behavior.

Thanks, I'll have to try the button class.  I didn't know it contained a state machine.  I just though it de-bounced switches.

I've been looking through the source code for ezButton.c
The function isPressed() is something of a misnomer and is only meaningful for a push-to-make button on the low side of a pull-up resistor. It actually detects falling edges of the signal, so it should be called isFallingEdge(), but the code itself is good.
Similarly for isReleased() which detects rising edges of the signal, so should be called isRisingEdge().
The constructor defaults to INPUT_PULLUP which may (or may not) be what you want for your buttons and toggle switches, so it's something to bear in mind especially for low-side push-to-break buttons or high-side push-to-make buttons which will generate rising edges when pressed and falling edges when released thus reversing the meanings of isPressed() and isReleased(), hence why they really should be called isFallingEdge() and isRisingEdge().
The algorithm in ezButton::loop() could be optimised a bit by getting rid of previousSteadyState and nesting the final if statement within the second if statement.
Other than that, it's quite a good algorithm that makes use of hysteresis to reset the debounce timer.
For comparison you could take a look at my algorithm in this simple debouncer for Arduino that simply detects rising edges, falling edges or both edges without regard to whether a button was pressed or released, and can be used in a polling loop or with interrupts. Here's the essence of the algorithm:
    bool input_state = digitalRead(INPUT_PIN);
    unsigned long current_ms = millis();

    edge = rise = fall = false;

    // Hysteresis:
    //   If there is no change, reset the debounce timer.
    //   Else, compare the time difference with the debounce delay.
    if (input_state == output_state)
    {
      last_ms = current_ms;
    }
    else if ((current_ms - last_ms) >= DEBOUNCE_DELAY_ms)
    {
      // Successfully debounced, so update the outputs.
      rise = input_state && !output_state;
      fall = !input_state && output_state;
      edge = rise || fall;
      output_state = input_state;
    }

And ledState = !ledState; simple toggles the value of ledState which is what you write to your LED with digitalWrite(led1, ledState); each time a falling edge is detected in the input signal.

Thanks for the insight @tim ! I'll be honest I'm struggling with this because I'm completely new to electronics and in the past month I've introduced myself to crimping, soldering, Arduino, connectors, all the things, and it's bit overwhelming, but I'll try to comprehend :D


text:
Alternative to GPS location being calculated by radius around a point
Hopefully the thread title isn't confusing - I'm trying to find out how would it be possible to make a different way of proximity warning with GPS.
Default/simplest way is by forming a radius around a goal waypoint, so the proximity criteria will get triggered when you're "inside" the circle. I know about geofencing but that does seem very demanding and complex, so I'd like to ask if something like shown in this pic would be achievable.
So instead of proximity criteria being a radius around a waypoint, forming a circular geofence so to speak, would it be possible to create a half-circle like this, at a specific angle.

What are you trying to accomplish? I mean, I understand your question, but I'm curious as to why, simply because GPS isn't really all that accurate (however, I don't know how big your semicircle is).

Also, this isn't really an Arduino question, it's a geometry question.

Let

(x, y) be the Cartesian coordinates of the vector going from the
waypoint to your position

radius be the radius of the circle

theta be the orientation of the straight line, in radians.

You can then build a unit vector normal to the straight line:
n = (cos(θ+π/2), sin(θ+π/2)) = (−sin θ, cos θ)
You are on the colored side of the line if the scalar product of n
with (x, y) is positive.
In code:
bool is_inside(float x, float y)
{
    float product = - x * sin(theta) + y * cos(theta);
    float r2 = x * x + y * y;
    return r2 <= radius * radius && product >= 0;
}

Thank you so much for showing the way! But one thing crossed my mind, as I'm moving the "half circle geofence" should remain within the same angle, not relative to me but to some constant, I'm thinking "north"...which means this gets more complex and closer to actual vehicle navigation? Because one thing to make this work correctly as well, is to have the target destination have a reference "north" so that the geofence always faces the proper direction. Which makes me think, is it possible to assign such constant, and make this half geofence face in a destined compass derived direction?

@Varonne: If you want theta to be a constant, just keep it constant. There is no reason it should be more complex than this.