text:
GPRS SIM900 and GPS NEO-6M don't work together
I'm trying to get GPS coordinates and send them to my API through the GPRS SIM900 and GPS NEO-6M shields.
In setup(), I first start the GPRS shield and call the function that connects to the internet. Then in loop(), I start to capture GPS coordinates and finally I send to my API, but my code doesn't work with this logic. I'd like to connect once and get GPS coordinates and send them to the API many times making a tracking.
The app stops if I run the code. connectToInternet() in setup() and getGpsPosition() in loop(). The SIM900 shield connects but the NEO6-M shield does not display the coordinates. The GPS only captures the coordinates if I do not connect to the internet.
Could someone help me? Following is my code and printout of the response to AT commands.
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <inetGSM.h>

static const int RXPin = 4, TXPin = 3;
InetGSM inet;
TinyGPSPlus gps;
SoftwareSerial serialGps(RXPin, TXPin);
char msg[50];
boolean started = false;
const char* dataCoord = "";

void setup() {
  // Serial connection.
  Serial.begin(19200);
  Serial.print(F("------------------------------------------------- \r\n"));
  Serial.println(F("Starting App Tracking Arduino"));
  Serial.print(F("------------------------------------------------- \r\n"));
  // Turn on GPRS
  powerUpGprs();
  // Start configuration of shield SIM900 with baudrate.
  if (gsm.begin(2400)) {
    Serial.println(F("\nstatus=READY"));
    started = true;
  } else Serial.println(F("\nstatus=IDLE"));
  if (started)
    connectToInternet();
  // Start configuration of shield GPS NEO-6M with baudrate.
  serialGps.begin(9600);
}

void loop() {
  // This sketch displays information every time a new sentence is correctly encoded.
  while (serialGps.available() > 0)
    if (gps.encode(serialGps.read())) getGpsPosition();
}

/**
  Power up
*/
void powerUpGprs() {
  pinMode(9, OUTPUT);
  delay(100);
  digitalWrite(9, HIGH);
  Serial.println(F("\nPower Up SIM900!"));
}

/**
  Connect to Internet via GSM
*/
void connectToInternet() {
  Serial.print(F("\r\n"));
  Serial.print(F("------------------------------------------------- \r\n"));
  Serial.print(F(" CONNECT TO INTERNET \r\n"));
  Serial.print(F("------------------------------------------------- \r\n"));
  //GPRS attach, put in order APN, username and password.
  if (inet.attachGPRS("zap.vivo.com.br", "vivo", "vivo"))
    Serial.println(F("status=ATTACHED"));
  else
    Serial.println(F("status=ERROR"));
  delay(1000);
  //Read IP address.
  gsm.SimpleWriteln("AT+CIFSR");
}

/**
  Get GPS position
*/
void getGpsPosition() {
  Serial.print(F("\r\n\r\n"));
  Serial.print(F("------------------------------------------------- \r\n"));
  Serial.print(F(" GET POSITON \r\n"));
  Serial.print(F("------------------------------------------------- \r\n"));
  // geolocation
  TinyGPSDate &d = gps.date;
  TinyGPSTime &t = gps.time;
  char* timestamp;
  if (!d.isValid()) {
    timestamp = "00/00/0000 00:00:00";
  } else {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d",
      d.day(), d.month(), d.year(),
      t.hour(), t.minute(), t.second());
    timestamp = sz;
  }
  String position = String("");
  position.concat(String("timestamp=") + String(timestamp));
  position.concat(String("&latitude=") + String(gps.location.lat(), 6));
  position.concat(String("&longitude=") + String(gps.location.lng(), 6));
  position.concat(String("&altitude=") + String(gps.altitude.meters()));
  position.concat(String("&speed=") + String(gps.speed.kmph()));
  Serial.println(dataCoord);
  send2Api();
}

/**
  Send To API, The function inet.httpPOST(),
  this is submit method POST via http request
*/
void send2Api() {
  Serial.print(F("\r\n\r\n"));
  Serial.print(F("------------------------------------------------- \r\n"));
  Serial.print(F(" SEND TO API\r\n"));
  Serial.print(F("------------------------------------------------- \r\n"));
  // Read until serial buffer is emapty.
  gsm.WhileSimpleRead();
  // TCP Client HTTP, send a POST request to the server and save the reply.
  int numdata = inet.httpPOST("api.myapp.com.br", 80, "/geolocations ", dataCoord, msg, 100);
  // Print the results.
  Serial.print(F("\nNumber of data received: "));
  Serial.println(numdata);
  Serial.print(F("\nData received: "));
  Serial.println(msg);
};

If I connect to internet the GPS does not display the coordinates.

But if I don't connect to internet the GPS displays the coordinates.

I solved.... my solution https://github.com/robsonfagundes/Arduino-GprsSIM900andGpsNEO-6M
I made example to help other developers who are facing the same problem or a similar problem with Gprs SIM900 and Gps NEO-6M working together.

Good day sir. It is possible that when send a location to mobile phone there's a link to google map so that i can find where's the vehicle.? What is the code for that?

@Cymon here https://github.com/robsonfagundes/arduino-gprs-sim-900-gps-neo-6m

and... here https://www.cooking-hacks.com/projects/arduino-realtime-gps-gprs-vehicle-tracking

You are using 2 SoftwareSerial instances and you're losing bytes when you aren't listening to the other port. Also your inetGSM library uses pins 3 for RX with the SIM900 and in your Arduino sketch, pin 3 is also the Arduino TX pin to the GPS module. Therefore, anything sent by the Arduino over pin 3 is received by both modules. Confusion.

Use the GPS module with another pair of pins, maybe, 7 for RX and 8 for TX. Connect the GPS TX to 7 and its RX to 8.
Try adding: gsm._cell.listen(); right before this line:
// Read until serial buffer is empty.
gsm.WhileSimpleRead();
Also add serialGps.listen(); right before this line:
// Print the results.
Serial.print(F("\nNumber of data received: "));

Refer to this answer for more details.

@RobsonFagundes Its in the library u're using. Have you tried it yet? Did it compile?

@RobsonFagundes what error did you get? Does everything work now? Any improvements?

@RobsonFagundes provide a link to your library. Are there any improvements?

here it is Library SIMCom SIM900

Let us continue this discussion in chat.


text:
Powering a 12v lock with batteries, via WiFi, and with low energy consumption
I'm a complete newbie in anything related to electronics, software or hardware; yet with a couple of friends we're going ahead with an interesting project related to automation through wireless devices: more or less IoT but involving electric locks.
The case scenario: there's a room without any power outlets. It has a regular door. We want to be able to open this door through the internet, with a lock that lies inside the room, on the other side of the door; all this, given we:

Can't make any modifications to the door's structure.
Can't drill or make holes or whatever so as to get a power cable to
the inside of the room.
But we can glue certain pieces behind the door, this is, inside
the room that hasn't any power outlets.

We've planned, so far, to use an Arduino Uno; enhance it with WiFi features (i.e. a module or shield) so as to bypass the limitation of not being able to connect an ethernet cable; and glue a solenoid or lock to the inside of the doors, so that it acts as a second lock that can only be unlocked through the internet, accessed via Arduino.
Our ideal scenario would be opening this door remotely, from our home, even if this door is a hundred blocks away. If someone wants to get in, they should ask for our permission, as we don't control the built-in handle, but we do control a latch fixed on the inside.
All this setup should be powered with a long-lasting battery: we can't plug anything, and we can't risk getting our batteries depleted fast, because we'll never be able to open the door once again. We need these batteries to last long enough so as to be able to change them in a prudent time window; a back-up battery system should also work well.
Standard solenoid locks are 12v. Arduino powers 5v devices, not 12v ones, as far as my understanding goes.
We should open this door only 5 times a day. That's it; the remaining time in between, the whole device setup can well stay 'dormant', in low-energy consumption mode, only to 'wake up' when we give the order: "Arduino, please tell the solenoid to open".
We haven't specified which battery we would use; ideally, the most cost-efficient option. If it lasts 3 months and costs, say, 20 dollars -- well, we would love that.
I've done this really inaccurate, schematic drawing to illustrate our idea and research. I know there's many details missing but I wanted to prove our point:

(The Arduino should be positioned on the wall and not on the door! My bad.)
I hope I'm clear enough up to now.
The questions, then, are:
I've done some research, and I've seen that Arduino can be enhanced so that it consumes the minimum possible energy so as to remain 'aware', but not in full-power mode, which in our case would be unnecessary.

So, can we make Arduino super efficient in terms of power consumption, even if we attach WiFi functions, which, as far as I'm concerned, really takes on battery life? So that we can make Arduino run for months before replacing the battery?
Arduino can send only 5v; but the solenoid powers on 12v; then, getting a second battery to power our solenoid sounds straightforward, except that as far as my knowledge goes, this battery should last next to nothing (maybe I'm wrong here). And we want it to last for months -- if not, our door will remain sealed forever! Can I make the solenoid dependant on the Arduino, so that it's part of the "almost-no-battery-consumption" scheme, and battery lasts, as I would really like, some months? We would be talking of only one battery to power the whole set-up, instead of two that I guess that we'll need.

I'm a newbie, but can't Arduino power 12v through a relay or a transistor? Can't post links.
To clarify: Getting two batteries for our complete setup (one for the Arduino, one for the solenoid), if these two batteries both last, is not a problem; but it would be catastrophic to make a battery last long enough while the other depletes in 48 hours. The solenoid needs to get electricity a modest 5 times a day; that's why I believe we can make it super efficient.
With our friends, we've so far programmed Arduino to open a solenoid from the Internet. The solenoid we've used was 220v because we had it in stock; it won't be what we need for our project. It was just a trial. On top of this, the Arduino has no WiFi module, just an Ethernet shield.

There's a remaining problem to solve, which is: what would happen if the Arduino fails? The door would be sealed 'forever'. We'll tackle that issue afterwards.
TL;DR: we'd love to open a lock via WiFi: the lock and Arduino should run solely on batteries that last more than 48 hours: a couple of months would be ideal! Can we work this out?
Thank you very much for your help, opinions, and time. I hope my question is up to the standards.

How to change the batteries when they go flat: Turn the handle and push. Then glue everything back on again.

"we can't risk getting our batteries depleted fast, because we'll never be able to open the door once again." It should go without saying that this is overall a very bad idea... entirely apart from the comparatively high power consumption of wifi.

Its a shame that noone likes your question, since you have obviously put some work into asking it. However, you've asked a very general question (or actually several distinct questions) relating to a system design which isn't really thought through. Each of the following ought to be addressed individually: Comms-physical, comms-protocol, power consumption, battery capacity/technology, mechanical security, encryption, failsafe, EMC, fire/electrical safety. Some of these you can maybe answer, and for an educational project they may not matter. As presented, your project has many possible flaws.

What kind of lock do you have? Mine for example has a knob to lock/unlock the door. I could simply add a small motor to the knob to unlock it using an Arduino while still being able to use a regular key (in case of low battery or no internet connection ).

Wifi uses s lot of power (relatively). You could make the Arduino only connect to wifi every minute or so to check some web api, but in your case that would probably be unacceptable (having to wait up to a minute for the lock to open). You could have a wifi base station on a location that does have wall power, an use a different wireless module, or wire to connect to the Arduino on the door.

You can instead use Low consumption bluetooth like the kwikset kevo does

[I'm coming in late but since this question got reposted, here goes:]
If this not to be just a Proof of Concept, but to be actually installed, you really have to address the several points of failure (Arduino, Arduino power, solenoid, solenoid power) that could lock you out of the room forever ("ever" being the time needed to fetch and apply destructive tools :).
Assuming it's a POC, here are a few more ideas:

You need 12v for the solenoid. You can take your 5v from the same source using an efficient regulator. Advantage: one fewer point of failure (power source), and the Arduino could monitor the 12v source and send an alert if/when it starts to sag (which would only be useful if there's some head-room between its charged voltage and the minimum needed to drive the solenoid).
If you use Bluetooth LE on the Arduino instead of WiFi, but place another Arduino outside the door, somewhere with power (locked into the wall, the ceiling, or an adjacent room), the outer Arduino with "unlimited" power could talk BTLE to the inside Arduino. Advantage: Lower power consumption by the inside Arduino (unless step 1. makes it unnecessary). Disadvantage: More equipment (second Arduino); more complex system has additional ways to fail, though not necessarily to lock you out; possible additional point of vulnerability to intrusion.
Is that a steel door? If not, an inductive charging coil on the inside of it might let you temporarily apply an inductive charger from outside to provide power - or charge a small battery or even a capacitor - enough to unlock the door. Advantage: One less point of failure (loss of 12v). Disadvantage: More equipment; applicability depends on door material and thickness.

As far as the 12V motor is concerned, you can construct a decent H-bridge to shift polarity. I am assuming you are using a linear actuator or servo. Use a mechanical relay with 2 channels. Wire GND to NO1 and NO2, VCC (12V) to NC1 and NC2, and pull VOUT  to motor from COM1 and COM2 - IIRC - and in your code track state of when each channel is on or off... It will short out if both relay channels are ON simultaneously, so that must not be possible.
Mechanical relays are slower to switch than transistors (can haul 230VAC/30VDC/10A with no voltage drop), but if you want a transistor H-bridge use the rather old TIP120 NPN Darlington (0.6-0.7V voltage drop per transistor), or MOSFETs. At least the TIP120s require heatsinking for >=0.5A, but can drive 5-6A upto 60V, which is plenty.
As far as the wifi bit goes, I don't have enough experience. I would use a GET request to a web server/page and read what state the lock should be in at short intervals... no more than 5 seconds. A simple '1' or '0' in a text file will do. To output state, heartbeat (is the Arduino OK right now, or is something wrong?) and other stuff from the Arduino, use POST requests. You should use a simple database for this... PostgreSQL is my favourite, but you may want something simpler.
If you need precise timekeeping for events like open at 9.00 am, use a DS3231. Be careful to conserve SRAM, the Uno has only 2KB. There are guides on arduino.cc to help you with that (PROGMEM for immutable variables and the F macro for static strings). This is a good method, hope it helps.

And if you are making a lock, glue is not your friend. I'm going to assume you know that.

This is not the place to answer all the questions and design options that you have, but, to give you a starting point, you need to look at very low power arduino-compatible boards.
My suggestion is to use an ESP8266 module which can be programmed as an Arduino (have a look at here). The module is quite low power, and it may run for some days with AA batteries. You can use a 12V power source for both the module and the solenoid (you need a voltage regulator). The solenoid will only be activated when needed, so the rest of the time it won't consume any power.
The whole project is not a simple one. I would definitely suggest you to go step by step.
Good luck.

source: Stack Exchange

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

sort: votes


text:
How can the Arduino check if it is connected to a PC and the PC is on?
I have been searching around the Internet to find if there is a way to check whether an Arduino is connected to a PC or not.
For example: if my PC is turned on, the Arduino will listen to any serial commands it receives, BUT if my PC is turned off, the Arduino will receive some random characters.
How can the Arduino check if it is connected to PC and the PC is on?

Read How does this code line detect if a serial interface is connected?. If it doesn't provide a satisfactory answer, update your question to reflect your additional requirements.

You'd have to write some application on your PC, that for example, sends "PONG" when it receives "PING". You could then "ping" the PC every now and then, to check if it responds (thus is connected/on).

Alternatively, you could check the 5V USB line, that would indicatie that your PC is on (usually). But that only works if you normally run it off the barrel jack. (So doesn't really apply to Nano, but you could make an alternative circuit.) You could maybe measure resistance on the data lines, but I'm not sure if that's safe/possible.

Have you checked if the USB ports on your PC will remain powered if the PC is off?

if my PC is turned off, the Arduino will have some predetermined patterns. - what do you mean?

Is it a desktop PC or laptop?

As suggested by Paul & Gerben, you could check the 5V USB line to see if it has a voltage or not.
I am assuming from your question that the Arduino is not powered from the USB line. I am also assuming that the USB port is not powered when the PC is turned off.
All you have to do is connect VUSB to a digital input through a resistor like so:

Alternatively, you could have the computer send a pre-determined message telling the Arduino that its alive.
If the Arduino receives this message then it lights up the LED on pin 13. If the Arduino hasn't received the "I'm alive" message for a while (ie. a timeout) it then turns off the LED.
A simple PC program could be written to automate this task.

jumper reset -> ground and rx -> tx (with power disconnected)
connect power, open serial monitor in arduino ide and type anything in and input. if the serial monitor echoes what you typed in, then your connection is good and you should look elsewhere for problems.
Found this solution on the arduino.cc community site.

How does your suggestion enable the arduino to establish if it is connected and what portion of the code to run, as requested in the original post?

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

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


text:
ESP32 S3 Same code works on Serial1 but NOT on Serial0 for RS485 module
I have designed a test board to understand ESP32-S3 working pins. I am using USB interface D+, D- for programing so Serial0 is free to use.
This is my test circuit for testing an RS485 converter. For the test, I am using an MD02 temperature and humidity sensor. Also for the converter I am using this module

This code is not working on Serial0 despite Rx and Tx LEDs are blinking on the RS485 converter.
#include <HardwareSerial.h>

void setup() {
  // put your setup code here, to run once:
  Serial0.begin(9600, SERIAL_8N2, 44, 43);
  Serial.begin(115200);
}

void loop() {
  Serial0.write("READ");
  delay(3000);
  Serial.print("Temp ve NEM: ");
  while (Serial0.available() > 0) {
    Serial.print(char(Serial0.read()));
  }
  Serial.println(".");
}

This is working
#include <HardwareSerial.h>

void setup() {
  // put your setup code here, to run once:
  Serial1.begin(9600, SERIAL_8N2, 18, 17);
  Serial.begin(115200);
}

void loop() {
  Serial1.write("READ");
  delay(3000);
  Serial.print("Temp ve NEM: ");
  while (Serial1.available() > 0) {
    Serial.print(char(Serial1.read()));
  }
  Serial.println(".");
}

What should I do differently for Serial0 and RS485?, because the 6M NEO GPS module is working properly on Serial0.

There are RX0 and TX1 on the PCB. Are these actually the right pins?

Yes, RX0 and TX1 names comes from arduino nano. But this 44 and 43 pins of esp32 s3. Also same code working with gps modules as i said.

You might want to use your oscilloscope to look for differences. "READ" should be easily detectable, and you can look for the reply. Compare baudrate and UART protocol.

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


text:
How to fix HC05 burning even after while using voltage regulator?
I'm using two circuits for my wireless head mouse project, one of them is a transmitter circuit with Arduino Pro Micro, HC05 Bluetooth module, Elechouse Voice Recognition Module V3.1, GY-521 module based on the MPU6050 sensor. The receiver circuit (Arduino Pro Micro + HC05 Bluetooth) will receive the sensor readings from the transmitter circuit. Both modules were powered by USB from the laptop initially. They worked fine. To make the transmitter circuit completely detached from the laptop, I used a 9V battery, and a voltage regulator of 5V. The receiver circuit was still c. I should mention that I was using voltage dividers for both of the transmitter, and receiver circuit's HC05 Bluetooth modules.
onnected to the laptop USB.
.
After using the voltage regulator, the module was working fine but suddenly the HC-05 burnt, led stopped working. Transmission failed. HC05 of the receiver module also burnt after 2 minutes. Why did this happen? What's the solution?
Circuit connection:
Hc05 connection same for transmitter & receiver circuit
HC05 Tx -> Arduino Rx
Hc 05 rx -> 2k ohm -> gnd
Hc05 rx -> 1k ohm -> hc05 tx
Hc05 vcc -> arduino 5v
Hc05 gnd -> arduino gnd
Voice Recognition Module tx -> arduino 8
Rx -> Arduino 9
Vcc- 5v
Gnd - gnd
Mpu6050 sda - Arduino 2
Scl- Arduino 3
Vcc - 5V
Gnd- Gnd
Voltage regulator connection:
The connection was 9V battery +ve to input, -ve to ground, output to Arduino 5V

Can you provide a schematic?

Please show a schematic. Where exactly did you use voltage dividers?

@StarCat I added the schematic in the question. Have a look. The receiver circuit only has the Arduino and the HC05 nothing special there. So, did not draw that one.

have you checked the power supply voltage at HC-05? ... your schematic shows a circuit that provides no power to the components

Are you absolutely sure every module is connected to the same ground? It looks like the ground of your voltage regulator is not connected to the rest of the circuit.

@StarCat , sorry. made a slight error in drawing the schematic. every gnd is connected to the Arduino GND pin in the circuit is connected to the Arduino Pro Micro Gnd. Even the voltage regulator. Then, the 9V battery's ground is connected to the Arduino GND also/

@jsotola, I haven't checked the power supply voltage at the HC-05 as my multimeter is broken. -_-

I've updated the schematic

Your voltage divider pins are backwards the HC05 RX pin needs the divider, not the TX pin.   Its tx would be 3.3v out and the arduino pin wouldn't care it would still work.
Most likely while you were testing before the HC05 was probably already slowly dying.
the HC05 has a very basic 3.3v regulator on board but only a little over 5V input can fry things.
I have always put 75-100ohm in series with the 5V in just in case.
Your circuit is basically good but the the RX/TX pins on the HC05 need reversing.
Analog V. regulators are fairly crude and will vary voltage some.
5.000v accuracy is never dead on. I have seen as high as 5.7V out and that would not be good.
Also the HC05 RX pin is receiving a 5V signal back, sourcing thru the HC05 chip.
Even the Arduino help site warns against 5V if it can be avoided.
from Arduino's site
https://create.arduino.cc/projecthub/electropeak/getting-started-with-hc-05-bluetooth-module-arduino-e0ca81
Sending Data to Arduino via Bluetooth
HC05 module has an internal 3.3v regulator and that is why you can connect it to 5v voltage. But we strongly recommend 3.3V voltage, since the logic of HC05 serial communication pins is 3.3V. Supplying 5V to the module can cause damage to the module.

You said "I should mention that I was using voltage dividers for both of the transmitter, and receiver circuit's HC05 Bluetooth modules."
Voltage dividers are not a good way to lower voltage for power components. The voltage output will vary based on load, and they also dissipate the excess voltage as heat, so you need high current resistors.
Post a schematic of your system with the specific batteries, regulators etc that you are using.

I added the schematic in the question.


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

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

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

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

(Google Bard Answer)

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

Edit: avr-objdump of eeprom section

Prints on Sketch
Without prints
Prints both on Library and Sketch

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void loop(){}

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

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

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

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

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

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

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

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

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

...

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

...

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

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

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

const long MAGIC_ID = 'Nick';

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

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

  // see if EEPROM initialised

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

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

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

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

  // add to counter
  myCounter++;

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

  Serial.println ("Done.");

} // end of setup

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

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

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


text:
How fast is flash reading compared to SRAM?
I'm working on a project that will eventually scale to 864 LEDs on WS2815 LED strips (three rows of 288 LEDs). I'm currently running it on an Arduino Uno with a single test strip of 144 LEDs.
FastLED stores its data in 3-byte structs, so I obviously cannot simply hold all of the data in SRAM and work with it directly (at least not without upgrading to a controller with more memory). I'm going to use a Raspberry Pi to send the Arduino data, one section at a time. To further save memory, I want to implement an RGB color lookup table in flash, then instead of
CRGB pixels[PIXEL_COUNT];

taking up over 2KiB of memory 800+ values, or
CRGB pixels[PIXEL_BUFFER_COUNT];

with a buffer of 288 RGB values consuming most of my working memory (864 bytes), I would have
CRGB *pixels[PIXEL_BUFFER_COUNT];

Where each pointer would reference a location in a PROGMEM 256-entry table of CRGB values. This is a more manageable 576 bytes in SRAM.
I realize FastLED does not work this way. There's a  lot of work ahead of me if I do this, but before I get started, my question:

Will I run into issues with reading the actual data from flash memory while sending to the LED strips? As currently implemented in FastLED, RGB data is in SRAM, but each pointer dereference will require reading from flash. Is the subsequent delay enough that it will cause an issue with sending data to the strips?

On an Arduino Uno, or other AVR-based Arduino, reading a byte from RAM
takes 2 CPU cycles. Reading it from flash takes 3 cycles. So flash vs.
RAM is not such a high overhead. However, if you store a LUT in flash,
and the color indexes in RAM, then each pixel would require:

2 cycles for reading the color index from RAM
3 × 3 cycles for reading the RGB values from flash.

That's a total of 11 cycles, vs. 6 cycles it would take to read the RGB
values from RAM, as is done in the stock FastLED library.
It sounds bad, but it could be that the precise timing is not such a big
issue. I don't know the WS2815, but if they are similar to the WS2812,
then you don't need to be anywhere as precise with the timings as the
datasheet suggests. C.f. the blog post NeoPixels Revealed: How to (not
need to) generate precisely timed signals.
Edit: there will be a few more cycles needed for the pointer
arithmetic. I estimate something around 7 cycles. At low level, the code
for getting a color should look roughly like this:
uint8_t *pixel = ...;
uint8_t index = *pixel;            // read from RAM: 2 cycles
uint8_t pgm_p;                     // pointer to flash
pgm_p = &pgm_lut + 3 * index;      // pointer arithmetic: ≥ 7 cycles
struct CRGB color;
color.r = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.g = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.b = pgm_read_byte(pgm_p);    // read from flash: 3 cycles

The WS2815 is basically a 12V WS2812B. Thank you for the detailed breakdown.

Your edit is also very helpful. With the NeoPixels Revealed article and some buffering, I might be able to pull this off. Since my LEDs will be displaying a gradient of the palette to an extent, I can read the nearest CRGB values into SRAM and just move the pointer ahead as needed when I find an index I don't have locally.

Because flash is on a different data bus to SRAM there is extra shuffling around needed internally in the CPU to get the data to where it needs to be.  This uses a special "LPM" instruction (Load Program Memory), which takes an extra clock cycle to operate. On top of that the only way of using it is through the Z "index" register - there's no kind of immediate or offset loads.  So it can be a little clunky to work with.  All that is masked by the provided C functions, of course.
The upshot is that yes, it is somewhat slower reading from flash.  How much slower, though, is impossible to say.  Best case scenario: each access will take 1 more clock cycle. Worst case: well, it's impossible to know.  That somewhat depends on both how you implement your reading of the CLUT and how the compiler batches things together.
I would suggest that you will need to employ the use of an oscilloscope and just try it out.  Implement your changes, then manually adjust the delays and timing to get the output waveform just right.

Exactly what I needed to know. Thanks.

Can always use a '1284P based board with 16K SRAM, lots of room to store patterns, etc. for quick access.

@CrossRoads I’ve looked at larger boards but am enjoying the challenge of this. Storing my data in 32bit blocks is also (probably, I have not benchmarked) speeding things up.


text:
How to use the pushbutton without using if, else
I want to let the led blink for 3 seconds then 2 seconds then one second using the button one time and without using if/else
void setup() {
    // put your setup code here, to run once:
    pinMode(5, INPUT);
    pinMode(6, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    digitalRead(5, HIGH);
    digitalWrite(6, HIGH);
    delay(3000);
    digitalWrite(6, LOW);
    digitalWrite(6, HIGH);
    delay(2000);
    digitalWrite(6, LOW);
    digitalWrite(6, HIGH);
    delay(1000);
}

Why don't you want to use if/else? Or is this a school assignment?

it is a school assignment actually

switch case is your friend ;)

Switch is an alternative to if --- unless are you at the "interrupts" section of your class...

digitalRead() returns either LOW (which is a macro equivalent to 0) or HIGH (which is 1).

I can think of a dozen ways to write what you want.  None of them are very good, the best method would use an if statement.  The problem is that the teacher probably wants you to use some skill that you just learned and we don't know what that is.  I could write you a great program that doesn't use an if statement, but if it isn't what your teacher is looking for then you probably still wont' get credit for the assignment and you'll make it readily apparent that you have people on the internet doing your homework for you, which if your teacher is any good at all get you kicked out of class.

@GMc delay doesn't work when put inside interrupt method, because itself it uses interrupts to increase the millis timer counter. The only way of writing this logic with interrupts is to set a flag in global scope and then use if to test for that flag in loop method. So interrupts are not the good solution to this homework. Unless maybe make button press interrupt to setup timer interrupt? That seems really awful..

@FilipFranik I agree and did not advocate that. You definitely don't want to include any lengthy operations in an interrupt service routine. My comment was more of a suggestion that switch is an obvious alternative to using an if - but it is also possible that the OP was at the "interrupts" section of their class and thus would require a completely different approach to the serial code as posted in the question - and as you suggest, definitely should not be using delay. Hopefully that was also taught in the class... I should perhaps in hindsight been more clear in my original comment.

was that a 'cut-and-pasto' with 'digitalRead(5, HIGH);'?  The digitalRead() function only takes one argument, not 2.

And, while I'm on the subject, some comments about good coding style.  Try to avoid using 'magic numbers' in your code.  Statements like 'digitalWrite(6,HIGH)' should be replaced by something like 'digitalWrite(LED_PIN, HIGH), where LED_PIN is defined before setup() with something like '#define LED_PIN 6' or 'const int LED_PIN = 6;' (which one you use here is more a matter of style than anything else).  Also explanatory comments should be used liberally; they will tend to make you think about what it is you are trying to do and will help reviewers like us to understand your intent.

As the required operation is finite and short, you can just hard code the sequence.

Ternary operator maybe helpful. [Reference]

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

You could you simple inversion of boolean variable to set state of LED.
const int LedPin = 5;
bool ledState = true;

// in your loop

// bool will be transformed from true to 1 (HIGH)
digitalWrite(LedPin, (int)ledState);
// invert LED state to be false
ledState = !ledState;
// false -> 0 (LOW)
digitalWrite(LedPin, (int)ledState);


text:
Alerting the ATMega32u4 that it's plugged into a computer (via USB)
I need help in writing some code that will allow for the ATMega32u4 to be aware of when it's plugged into a USB port. I'm not really familiar with the ATMega32 or with it's function in Arduino, so I'm lost in the dark on this one.
Update:
So in my circuit, the uC will be powered by Lithium Ion Batteries. On my PCB, their is a battery charging circuit that is powered through a USB C cable. My goal is to implement some type of firmware that can differentiate when the board is plugged into a wall outlet and a USB port on a computer. The reason for this is because I don't want the batteries to charge when the USB C cable is plugged into a laptop.
Second Update: Added pictures of the ATMega32 along with the charging circuit mentioned. I'll be the 5V voltage from USBC to charge the batteries. I'll have the data lines on the USB C cable connected so I can program the microcontroller through a USB cable. My goal here is for the microcontroller to recognize when it's connected to a computer. When this happens, I'll talk to the battery charging IC and tell it to not charge.

Updated my post, but the ATMega32 will be powered by Lithium Ion Batteries. They will be changed through a USB C connector that has the data pins connected.

you could try something like this ... if(Serial) { ledon() } else { ledoff() } ... see if the LED changes state when USB cable is plugged and unplugged

Here is the documentation link to jsotolas comment: https://www.arduino.cc/reference/en/language/functions/communication/serial/ifserial/

I'm not sure you can get the best answer to this without details (schematic, etc) on the board itself.

@timemage Added schematic part of the mC and charging IC

You should get to know more about your charging IC (it is quite a powerful chip if not over-kill), read the datasheet, it has more than one pins that provide the indication on whether the power source is an USB or a charging port, it also has the capability to cut off the charging when the charging current is below the threshold, so in summary, once you understand it, what you are trying to do may not necessary.

@hcheung The problem with that is I don't believe that the charging current input will always be 500mA. If connecting to a laptop with a USB C port, then that port has the potential to output up to 3A (which I don't want since I don't want the gloves to charge while connect to the laptop). I'm just trying to understand if the uC can tell when it is plugged into a USB port via the data lines.

did you try what jsotola suggested?

@Juraj I did a test, and found that just checking to see if there is any activity on UDFNUML works for my application from Shreyas's answer. Having the MCU respond if there is activity is fine for my firmware

doesn't the bool operator on Serial do it better?

https://github.com/arduino/ArduinoCore-avr/blob/8f8df161ebf3d8bc595d226c3d3a9125383042a5/cores/arduino/CDC.cpp#L245

I imagine (haven't really tried it) this would work, with some minor adaptation to match your code structure.
//  VBUS or counting frames
//  Any frame counting?
u8 USBConnected()
{
    u8 f = UDFNUML;
    delay(3);
    return f != UDFNUML;
}

The method reads the UDFNUML - usb data frame number lower (byte) register, waits 3 milliseconds, which would be sufficient time get at least 1 more USB frame if the device was really connected to a USB host, reads the register again and checks if it some USB activity had happened.
Personally, I am not a big fan of busy wait delays like that because the CPU could be better utilized doing something useful in that period (3 milliseconds on a 16Mhz CPU = 48000 clocks ~= 48000 instructions)
I'd probably use 1 millisecond timer to sample the register and keep track of the USB status
An alternative would be to use the bool USBDevice_::configured() method
which is implemented like so
bool USBDevice_::configured()
{
    return _usbConfiguration;
}

//  Endpoint 0 interrupt
ISR(USB_COM_vect)
{
  //    ... snip ...
        else if (SET_CONFIGURATION == r)
        {
            if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT))
            {
                InitEndpoints();
                _usbConfiguration = setup.wValueL;
            } else
                ok = false;
  // ... snip ....
}

Hopefully one of the two approaches work for you...


text:
Analog Comparator works on Nano, but not working on Pro Mini 3.3v
I've coded an analog comparator to work on Nano, but the same code does not work on a brand new Pro Mini 3.3v 8MHz. The serial monitor just outputs the triggered interrupt continuously. Lines orange and yellow have the potentiometer.

The code is:
#define INDICATOR_PIN 8

volatile boolean triggered;
volatile boolean rising;
volatile byte acsr_value;

ISR (ANALOG_COMP_vect) {
  if (triggered) return;           // For testing purposes, ignore the interrupt if we haven't reported the last one yet.
                                   // This also effects some crude debouncing.
  cli();
  acsr_value = ACSR;
  rising = (acsr_value & bit(ACO)) > 0;
  triggered = true;
  sei();
}

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

  pinMode(INDICATOR_PIN, OUTPUT);
  digitalWrite(INDICATOR_PIN, LOW);

  ADCSRB = ADCSRB & ! bit(ACME);   // disable Analog Comparator Multiplexer Enable
  ACSR =  bit(ACI)                 // clear Analog Comparator Interrupt Flag
        | bit(ACIE)                // set Analog Comparator Interrupt Enable
        | bit(ACIS1) | bit(ACIS0)  // select rising edge: ACIS1/ACIS0 Analog Comparator Interrupt Mode Select
        ;
}

void loop() {
  if (triggered) show_what_happened();
}

// just give an indication via Serial and LED that we handled an interrupt...
void show_what_happened() {
  digitalWrite(INDICATOR_PIN, HIGH);

  Serial.print ("Triggered! ACSR=");
  Serial.print (acsr_value, BIN);
  if (rising)
    Serial.println (" RISING EDGE (as expected)");
  else
    Serial.println (" FALLING EDGE .. wtf, didn't ask for this, but every so often one slips thru. Maybe a sync issue reading ACSR.");

  triggered = false;

  delay(100);
  digitalWrite(INDICATOR_PIN, LOW);
}

Why does it work well on Nano? I've read all the related sections in the datasheet and tested several ACSR configurations.
I'm seeing the voltage levels changes on a DSO, and it works as expected in the Nano.
I'd like to add that when loading the code to the board, it either prints nothing, or prints continuously RISING FALLING edge. Sometimes, when a connect the serial monitor, it just stops flashing the led. It is definitely an erratic behavior.
What am I doing wrong?

Could you tell us the exact board models/ microcontrollers?

Yes. It's an Arduino Pro Mini 3.3v 8Mhz board. Atmega328p.

Ok, just in case (ISR names and such). Are you using this circuit? Because it sets AIN1 to a reference of 2.5V. Just thnking out loud, but internally in a 3.3v board, that might be too high.

I edited the question with the schematics. I assure you that at first, the level of AIN0 is fewer that AIN1, and then when I move the potentiometer, the level surpass AIN1, moment when I expect it to trigger the interruption, but this does not happen. I'm starting to think that there must be some kind of limitation in the Arduino Pro Mini board.

There's no limitation - the signals go straight from the header pins to the TQFP pins on both boards.  The only difference is AREF - 5V on the Nano, 3.3V on the Promini you are using. What level signal are you sending in, and comparing against?

The level signals will be the same proportion for any AREF. The relevant thing is that I move the potentiometer and AIN0 surpass AIN1, which is happening, I see it in the DSO.

No, that's not what @CrossRoads meant. AIN0 can surpass AIN1, but if the level isn't within 3.3V range, this won't work. Analog comparator works based on the AREF voltage. Nano's AREF is 5v. Pro Mini 3.3v 8Mhz 's AREF is 3.3V. So check the voltage level of AINs.

The FTDI is set to work with 3.3v and is feeding the Pro Mini with this voltage.

Do you have a proper schematic? I can't tell from the image you posted what values of resistors you used.

The circuit next to the FT232 (set to 3.3v) is a voltage devider with a 2 * 10K in series and 3 * 470K in parallel. Midpoint is the reference to D7. The variable reference is a voltage devider between a 10K and a potentiometer that goes from 23K to 150K. The schematic a posted is made with the autoroute of Fritzing, so don't take it as perfect. It's just to give the idea.

Ok, but is your Fritzing image correct? Because it looks like your voltage divider is connected to RXI !! instead of 3.3V.

If your voltage on pin D6 and D7 are really close, you will get trigger continiously. So, check the voltage on those two pins.

The delta range is: minimum 2.32v, average 2.52v and maximum is 3.12v . Please, check in your breadboard that the continuous triggering is because these 200mv downwards and 600mv upwards is not enough delta to keep comparator at ease. I mean, "really close" is not specified in the 328 datasheet, at least, I didn't find it.


text:
How to calibrate Arduino DUE analog readings?
I am having a problem with the analog readings on my Due. On pin A4 and A5 I am measuring voltages:
double vcc = 3.288  // taken on pin 75 (ADVREF) ;
analogReadResolution(12);
result = analogRead(A4) * (vcc / 4095);   // result = 0.47+- 0.01      actual reading = 0.429
result = analogRead(A5) * (vcc / 4095);   // result = 0.49+- 0.01      actual reading = 0.555

As you may see I could not simply offset the value because both have very different offset: one is positive and the other is negative. The reading is off by 0.05v, which is inaccurate for a 12-bit ADC that offers 0.000805v resolution, almost a 1000x inaccuracy.
Is there any way to calibrate analogRead further without using additional external components on the pin?


text:
How many I2C lines does the Arduino Due have?
According to the Arduino pin Mapping
20  PB12    SDA 3   6
21  PB13    SCL 3   6
70  PA17    SDA1    3   6
71  PA18    SCL2    15  9

The first one seems pretty obvious, the second one though is confusing. They have different labels. I also do not see other SDA or SCL in the table. So is this a typo?

According to the Wire library documentation https://forum.arduino.cc/index.php?topic=132130.0:

The Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to
  the AREF pin and the additional one is on pins 20 and 21.

And the table:
Arduino Due: 20 (SDA), 21 (SCL), SDA1, SCL1
So it seems in your table SCL2 should be SCL1.

It would seem that arduino has a typo in their documentation

Fully agree on that, note that my link is also from Arduino itself, and it's contradictory with your Arduino link. Probably you can write to them about it.


text:
How to use an external 32kHz crystal for ESP32 S3 with Arduino IDE?
I want to use an external 32kHz crystal for RTC with ESP32 S3, but I didn't see any example or tutorial for Arduino IDE, Even when I asked ChatGPT, it gave me some example but the code gave library errors. I don't understand why there is no RTC example in the Arduino IDE.
I have designed a PCB with this SCH for RTC. But I don't know how I can activate an external 32 KHz crystal with Arduino IDE. Please tell me how.

Has there been any advancements on this ?
Does Arduino Ide support configuring an external crystal for the esp32?

This is not a simple task: you have to recompile the Arduino core with the external RTC enabled.
Basically, you have to properly set the CONFIG_RTC_CLK_SRC option in kconfig file. You should start to read from here, and practising with ESP-IDF configurator.
I successfully completed this operation for the ESP32-S2 few years ago, but the procedure is very similar. Good luck.

From the ESP32-S3 documentation in section 2.4.2:

ESP32-S3 supports an external 32.768 kHz crystal or an external signal (e.g., an oscillator) to act as the RTC
sleep clock. The external RTC clock source is used to improve the timing accuracy and thus reduce the average
power consumption, but will not affect the functionality.

This document also contains a schematic:

... it is assumed that the schematic in the question is that of the ESP32-S3-WROOM module accounting for the differences between the two schematics.
The wording in the document infers there is only a counter to track / control the processor's sleep state.
This is further enforced by this question / answer found in electronics.stackexchange.com:

The ESP32 RTC module only has a timer that runs even in hibernation mode as well as some RAM that it can retain in deep sleep mode...
... There's no "wall clock" or "calendar" in the ESP32 RTC module.

If still interested in implementing a "wall clock" using the ESP32-S3, the same stackexchange question / answer offers the following:

The ESP32 does not have a real time clock - you cannot tell it to wake up at a particular time. It does have a timer that can wake it from deep sleep after a given time.
You can use the deep sleep wake up timer like this:

esp_sleep_enable_timer_wakeup((uint64_t)sleepTimeSeconds * 1000000);
esp_deep_sleep_start();

You set the sleep timer with esp_sleep_enable_timer_wakeup. The time period is in microseconds. With the timer set, the ESP32 will automatically wake up after the set time period.

Code will then have to be written to pull the last time from the ESP32-S3's nonvolatile memory, increment it by 1 second, store it back into nonvolatile memory and put the processor back to sleep for 1 second.


text:
Serial.available() function for Arduino
I want to implement a function in another micro-controller which works like serial.available(). I don't know how it works. I read about Serial.available() in this link.
Whenever I write a string on the terminal, it prints the length of the string. Can anyone tell me how it works?

It reports the difference between the head and the tail of the circular buffer the incoming characters are stored in.
The way serial reception on the Arduino works is:

A character is received into the internal hardware RX buffer (UDRx)
An interrupt is triggered
An interrupt service routine (ISR) is executed
The character in UDRx is read and, if there is room, stored in a circular buffer (_rx_buffer).
The head pointer of _rx_buffer is incremented and wrapped if needed.

When you actually read a character with Serial.read() the following happens:

If the head and tail of rx_buffer are equal, return -1
Get the character at tail from _rx_buffer
Increment tail and wrap if needed
Return the character

So when you use Serial.available() it just returns head - tail (taking into account the wrapping, so the sum is slightly more complex than a simple subtraction).
You should examine the files HardwareSerial.h and HardwareSerial.cpp in the Ardino AVR core software.

i understand till step3

Step three in which block?

The character in UDRx is read and, if there is room, stored in a circular buffer (_rx_buffer).

first block....

You should read the ATMega328P datasheet - the section about the USART.

@Beginner: Everything should be obvious once you understand what a circular buffer is.


text:
Errors when compiling the GSM SMS receive example from the Arduino IDE
I want to receive SMS and check whether the character is 'y' or 'n'. If it is 'y', set a pin to high so that a light glows. I thought I could use the example code given in the Arduino IDE for receiving SMS, but when I compile (without connecting the board, using ctrl+r) it shows the following errors:
Arduino: 1.8.1 (Windows 7), Board: "Arduino/Genuino Uno"

In file included from F:\Arduino\libraries\GSM\src/GSM.h:46:0,
                 from F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:21:
F:\Arduino\libraries\GSM\src/GSM3ShieldV1BandManagement.h:49:125: warning: 'typedef' was ignored in this declaration
 typedef enum GSM3GSMBand {UNDEFINED, EGSM_MODE, DCS_MODE, PCS_MODE, EGSM_DCS_MODE, GSM850_PCS_MODE, GSM850_EGSM_DCS_PCS_MODE};
                                                                                ^
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino: In function 'void setup()':
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:47:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
     if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
                                  ^
Sketch uses 13322 bytes (41%) of program storage space. Maximum is 32256 bytes.
Global variables use 996 bytes (48%) of dynamic memory, leaving 1052 bytes for local variables. Maximum is 2048 bytes.
An error occurred while uploading the sketch
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Please help me rectify the error.
I use a SIM900 GSM board. I connect the tx and rx of the GSM board to the Arduino's tx and rx.

Those are warnings, not errors.  The code should have compiled and be able to flash.

thanks a lot man ... it means a lot to me. i am new to arduino. i will flash it and will let you know :) thanks for your help

Yes they are just warning, but don't assume all warnings should be ignored.  In this case they can be ignored, but you may as well fix them to stop them cluttering the output.
The first one can be fixed by removing the word typedef.
The second one needs you to add .c_str() on the end of the string variable.  Sometimes 'string' classes don't store the data in the same way as a char array.

tx and rx of arduino are connected to the rx and tx of gsm board. ground is also connected. is the problem with the code or the connections?

I modified the example according to my needs. so when i send 'y' to the gsm , i hear that beep sound indicating that message has been received.
But there is no reaction from the arduino. The modified code snippet is as follows:
if (sms.peek() == '#') {
Serial.println("Discarded SMS");
sms.flush();
}
// Read message bytes and print them
while (c = sms.read()) {
Serial.print(c);
if(c=='y'){
digitalWrite(LED_BUILTIN,HIGH);
}
else
digitalWrite(LED_BUILTIN,LOW);
}


text:
Drawing specific RGB on touch screen
I have the Arduino MEGA and an adafruit touch screen 2.8 inches.
My goal is to draw a pixel given a specific RGB
I am using the ILI9341, GFX, and TFT.h libraries to draw and control the touch screen. I noticed the drawPixel function given, in which it takes in three parameters and draws the pixel:
tft.drawPixel(4,4,ILI9341_BLUE);

But, I am trying to draw a pixel with specific a RGB. So instead, the function would ideally need 5 parameters instead of 3, x, y, and then R, G, and B:
tft.idealDrawPixel(5,6,89,234,76);

I tried putting in a number as the third parameter and not ILI9341_COLOR, and the screen just prints blue:
tft.drawPixel(45,67,255);

Is there a function that allows me to draw RGB pixels specifically? Thanks for any help!

As noted in the second paragraph on Adafruit's Graphics Library webpage,

First thing to note is that color is 16-bit, and that includes Red, Green and Blue in a 16-bit variable. The way the color is packed in is the top 5 bits are red, the middle 6 bits are green and the bottom 5 bits are blue.

If you want to specify 8-bit color components, you could write an intermediary routine to translate from that form to the 565 form.  For example:
#define rgbDrawPixel(x,y,r,g,b) drawPixel(x,y,(((r)&0b11111000)<<8)|(((g)&0b11111100)<<3)|(((b)&0b11111000)>>3))

Note, this assumes the TFT library you're using has the same specs as Adafruit's.  That might or might not be; I don't know how to account for a 255 color number showing up as blue rather than white.


text:
Image Breakdown
I've been trying to figure out a way to store an image on the Arduino, and I couldn't figure it out. What I've been trying to do with this image is the following:

Test that the arduino has the image by displaying on a touchscreen (I have the adafruit 2.8 inch touch screen)
Break down the image into an array, in which contains pixel by pixel color RGB color info of the image

int pictureData = [[100,50,0],[176,255,5],...]; // RGB Values within the array
How can I store an image and break it down as shown? Is there no way to do this? I would appreciate any help! Thank you very much!
I am using Arduino IDE for code and I have Arduino Uno/MEGA, which ever is necessary for this task. All info of screen is on adafruit: https://www.adafruit.com/product/376
The below image shows an example of displaying the image:

Please edit your question to include part number and a link to “adafruit 2.8 inch touch screen” and general specs, and image format (jpg, bmp, whatever) and its stored size.  This will reduce the amount of time people spend guessing the display's pixel count and the number of bytes in the image

@JamesWaldby-jwpat7 Thank you for your time. I added it to the question.

I presume you are trying to create a system that has one image stored, and want the image to be available without needing an SD card reader on the system.
If the logic of your program is small enough to fit into about 18KB of flash memory, you can store one 230KB image in flash on a Mega. (230KB+18KB+8KB = 256KB = Mega flash size.  8KB is Mega bootloader size.)  See the PROGMEM page at arduino.cc for examples of declaring and accessing arrays from flash.
If you end up needing lots more flash for the logic of your program, consider compressing the 18 bits of each pixel to 16 bits.  The 230KB figure is 240·320·3.  Each pixel on the display uses six bits per color, stored in three bytes per pixel.  Instead of keeping all the bits, you could clip the blue to its high four bits; ie, save 6-6-4 for RGB in two bytes instead of 6-6-6 in three bytes.  Or could clip two of the colors to their high five bits; eg, save 6-5-5 or 5-6-5.  At two bytes per pixel, an image would take 240·320·2 = 153600 bytes of flash, leaving roughly 94KB for program logic.
In all of these approaches, image data would be brought into RAM row by row or column by column, unpacked, and copied to the RAM buffers in the display.
One could also apply some compression algorithms to the image instead of using BMP format.
If you need more images than one, you could further reduce image quality, for example could save 3-3-2 high bits of color per pixel, or could save only every other pixel in a row or column or both, reducing storage to a half or fourth as much.  Or you could have one reasonably good image stored 6-6-4 at 16 bits per pixel, so about 154KB, plus several monochrome images stored one bit per pixel, or about 10KB each.

Edit 1: Re “how would I take an image and convert it into the RGB array?”, one straightforward approach is to write an image-converter program (that runs on your development system) to read an image file and output C code representing the image data in arrays; that is, to produce C-style arrays printed in ASCII.   Again, this recommendation is predicated on the notion that you are trying to create a system that has one image stored, and want the image to be available without needing an SD card reader on the system.
I recommend writing the image-converter program in Python.  See, for example, the accepted answer at  Convert an image to 2D array in python, to which you would need to add a few lines of code to write out C code to a file, so that you could include that code into a sketch.  Also see  How to get an array from RGB values of a bitmap image? and Working with .bmp files in python 3.
Some C-language examples appear in answers to  How to convert a .bmp image into Byte array using C Program and How to convert an image to WORD (uint16) array?, which are among the first links in a stackexchange search for “convert bmp image to array”.
Wikipedia's BMP file format article shows the layout of BMP files in general.  Using various image-handling libraries (as recommended in SE questions listed above) sidesteps having to deal with low-level BMP details.  However, you may be able to use a simple program or application to produce RGB565 color format files, eg as at Bitmap to RGB565 format on codeguru.com, and then write a simple program to convert that particular form to C-style arrays printed in ASCII.

Thanks, that was very helpful. But how would I take an image and convert it into the RGB array?

@AssafiCohen-Arazi, see edit 1

Note that if you have an image conversion program, you can convert the image to binary PPM, which is a format trivial to parse, or even to XPM, which is actually valid C code.

240 by 320 pixels.  That's 76800 pixels.  In your example it looks like you want 3 bytes per pixel, so that's 230400 bytes.  An Arduino Mega has 8K bytes of SRAM memory.  There's enough room in the memory on the Arduino Mega to hold 0.003% of your image.
Maybe you could store the image on an SD card and put it on the screen little piece by little piece, but that is going to be painfully slow.

Is there still a way to store the data of the image in an array?

And a follow up, how can you transfer the data of the image as the RGB array shown?

Is there still a way to store the data?  Do you really not understand that 230KB is never going to fit into an 8KB space?  Think of it this way, is there any way to put 230 gallons of water in an 8 gallon bucket?

You don't need to load the whole image (230KB) from flash memory (256 KB) into SRAM (8KB). And 8KiB out of 230.4KB is 3.6% not 0.003%.

@Delta_G O meant with the micro SD card so there is enough room, sorry for not explaining.


text:
Connect Arduino Uno RX/TX to 3.3v NEO-M8N gps module
I'd like to connect an M8N gps module to an Arduino Uno. From what I understand

the Arduino pins 0-RX/1-TX work on 5V
the M8N RX/TX work on 3.3v
the sensor-TX sending to the Arduino-RX should work (3.3v is “good enough” to drive the Arduino-RX-pin)
the Arduino-TX sending to the sensor-RX is problematic because of the 5v (could break the sensor)
During USB-programming, the Arduino-RX sensor can be at 5v (so suddenly the current flows in the "wrong direction"- which could break the sensor)
A level-converter could be used to “translate” the voltages in each direction.

Assuming we don’t use a level-convertor

Could we use a schottky-diode (which as I understand blocks current in 1 direction) to block the 5V from the ArduinoRX going into the sensor?
But then the 3.3V from the sensor-TX would pass (correct direction ), but the diode will drop the voltage "a bit more"… is this still enough to drive the arduino RX-pin?
And it works, why not also use a schottky-diode to also protect the Arduino-TX to sensor-RX connection ( just to be safe, since some people were saying one some Arduino they needed to connect RX-RX and TX-TX to get the communication to work.. ? ).

As an alternative to the schottky ( or maybe in addition to it)
- Could we simply take 2 voltage dividers (for one for both RX-TX and TX-RX) ?
We can use a “resistive voltage divider” to lower the Arduino-TX 5v to 3.3 V
- I understand to get from 5V to 3.3V we need “x” and “2 * x” resistors-values, so e.g 1K Ohm and 2K Ohm… but how do I know which values would be appropriate ( I mean, we could also take 10K Ohm and 20K Ohm, would also lead to 5V to 3.3v) but at a different current (Amps)… ?

And what about a voltage-divider with a resistor and a capacitor (see https://en.wikipedia.org/wiki/Voltage_divider, low-pass RC filter)?
What would be appropriate values for that solution for the resistor and capacitor?

Please be patient, electronics-beginner here trying to make sense of this…

Buy some of these, it's a simple hardware solution to your problem then.
https://www.amazon.co.uk/gp/product/B0148BLZGE/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1
I know you said you don't want to use a level converter but it's the simplest way around the problem.
You stated that you're an electronics beginner AS AM I, which is exactly why when I came up against the same problem i just spent the money.
It was only £3.99 for 5 of them and as far as I'm aware you should be able to buy single ones off amazon too, haven't searched but i'd have thought you'd be able to.
Or if you need to do it with resistors you can use this calculator here
http://www.ohmslawcalculator.com/voltage-divider-calculator

I actually already purchased those as that's surely the safest solution for starters. But in the process of figuring out the "magic component needed" the above questions arose. For the voltage divider, try your link enter 5v, 100Ohm, 200Ohm -> 3.3v... But if you enter 5v 1000Ohm, 2000Ohm you also have 3.3v... so there must be something "missing"... And the other part which worries me is the occasional 5v on the RX pin.

In the Arduino forums related to 5v to 3.3v we have this link here, http://forum.arduino.cc/index.php?topic=16846.0 someone uses 1K8 and 3K3, but here https://forum.arduino.cc/index.php?topic=22570.0 someone suggests using 270R and 470R and either of those end up close to 3.3... So what's the difference (it must be sth with current)... or could we just as well use 10M and 20M resistors and it really doesn't matter?

You can use something along the lines of this:

simulate this circuit – Schematic created using CircuitLab
When the 5V Rx is driven to 5V D1 protects the 3.3V Tx pin.
When the 5V Rx is driven to 0V R1 protects the 3.3V Tx pin from excessive current draw.
When the 5V Tx is driven to 5V D2 protects the 3.3V Rx pin and R2 pulls the pin to 3.3V.
When the 5V Tx is driven to 0V D2 pulls the 3.3V Rx pin to ~0.2 V
Resistor values are rough guidelines, lower values will put more strain on the parts and increase power draw but will also increase the maximum UART speed that will work reliably.

How can it be that RX is driven ... ? It's an 'R' port and as I suggest it stands for Receive. So wouldn't it be that the TX 3v3 port is driving the RX 5V so the RX 5V needs a pull-up? The whole thing does not make any sense this way (for me).

UART Rx ports idle high. This means there is a high probability the Rx pin will contain pullup to 5V. So not actively driven but a passive low strength pull to an excessive voltage. The protection diodes internal to the 3.3V part could probably cope with that, especially if there is a series resistor, but this reduces the strain on the 3.3v part.


text:
Division with big constant number. Ideas to make it more efficient?
Im reading the voltage applied to my microcontroller using the internal voltage reference.
Here the topic is talked, and there are some working examples.
Im NOT using this examples, im using my own library to do this.
In short, works like this:

Microcontroller has fixed internal voltaje reference of 2.048v that can be read
Reading this value with the ADC will give a value from 0-255 (im using 8 bit ADC for efficiency)
Depending on the value read, you can calculate the voltage at the Vcc pin
Math is like this:

Vcc_voltage = ADC_MAX_VALUE * VREF_VOLTAGE / adc_value
Where:

Vcc_voltage: Voltage calculated at the VCC input of the microcontroller
ADC_MAX_VALUE: the maximum value that the ADC could give (CONSTANT: 255 in this case)
VREF_VOLTAGE: voltage of the internal fixed reference (CONSTANT: 2.048v in this case)
adc_value: value read by the ADC at the internal voltage reference (VARIABLE: from 0 to 255)

So the calculation result:
Vcc_voltage = 255 * 2.048 / adc_value
In order not to use floats, I multiply the VREF_VOLTAGE * 1000. New calculation:
Vcc_voltage = 255 * 2048 / adc_value
Or:
Vcc_voltage = 522240 / adc_value
And this is where im stuck. Im running out of flash, and im optimizing every part of the code. At the moment this is a "int32" division with a int16 result".
I think this could be reduced by some "binary trick", some wise programmer advice or approaching the formula from a different point of view.
Any suggestion?

I think the wisest programmer advice would be not to try to optimize this code if it's regarding FLASH (not even SRAM). You might save 1 or a few bytes. I'm sure there are other parts in your code where the gain is bigger, and if not, than this will not help much either. Readability/maintainability is also important which will normally suffer a lot if you are into these kind of optimalizations.


text:
FTDI Unrecognized USB device
I connected my FTDI (FT232RL) to my PC, windows 8.1. And it gave me a notification saying "USB device not recognized". However, I thought that the problem is from the cable that I am using to connect my FTDI with my PC, I tried another cable, same results. I am trying to program an ESP32-CAM, which has no boot loader, nor a way to connect it directly with the PC. However, I tried to upload the program (from arduino IDE) to the FTDI, It has said "Could not open port COM4", I have concluded that if I can only bypass this error, the upload will work fine with no errors. Windows is preventing any communication with this device, because it has not recognized it yet.
I have tried the following:

I reinstalled the FTDI driver using the '.exe' setup file, and installed many version many times.
I replaced the cable with another cable, because I suspected that the cable had an issue, but it made no difference.
I checked the wiring 10 times, nothing suspicious.
I have also tried to choose the driver manually from the device manager tab and downloaded the driver from the FTDI website, still did not work. There was a guide on how to do the "setting the driver up for the FTDI", I followed it, did not work too, but I followed the "Setting up the driver manually" part, there was a step that was not obvious enough for me, he chose a file that contains the driver, but which file exactly? only god knows.

However, I found some videos on the internet that does not require any driver (Linux sometimes work without any driver). Why is that? Why am I getting this? Why does other people are not getting this error? I saw a lot of people suffering from this FTDI chip. There should be a solution.

does the module use a genuine FTDI chip?

I really don't know, how can I even know if it is genuine or not? I bought it from aliexpress.com, most people gave the seller a good feedback for that product.

If it's from a cheap chinese site then it's probably fake.

check the FTDI site ... they may have a program that you can download and use to identify if your device is genuine

Do you have the product link?

@Fahad , https://www.aliexpress.com/item/32645814447.html?spm=a2g0s.9042311.0.0.27424c4dL473Vv , I think it is genuine, most people gave positive feedback.

It is possible that you just got a bad board. You can use this utility software: https://www.ftdichip.com/Support/Utilities.htm#FT_PROG
to configure FTDI ICs. Give this a try. If this can't detect it, well, you will have to order again.

Alright then, nothing worked out for the FTDI chip, I have concluded that my chip is fried. However, I want to answer this question, but there is not a clear solution. So, I am thinking of closing this question.


text:
Single Method for 2 Ultrasonic Sensor is not working as expected
So I have created a method to read and return Ultrasonic Sensor Data. I have 2 Ultrasonic Sensors.
Below is my code.

    // Ultrasonic Pins
    #define T1 2
    #define E2 4
    #define E1 3
    #define T2 5
    // Motor Pins
    #define M1 7
    #define M2 8
    #define M3 9
    #define M4 10
    // Motor Movements Definition
    enum MOTOR
    {
        FORWARD,
        BACKWARD,
        LEFT,
        RIGHT,
        STOP
    };

    long duration1, distance1, duration2, distance2;

    void setup()
    {
        Serial.begin(9600);
        pinMode(E1, INPUT);
        pinMode(E2, INPUT);
        pinMode(T1, OUTPUT);
        pinMode(T2, OUTPUT);
        pinMode(M1, OUTPUT);
        pinMode(M2, OUTPUT);
        pinMode(M3, OUTPUT);
        pinMode(M4, OUTPUT);
        Motor(STOP);
    }

    void loop()
    {

        // If Both Sensors detect object then go in backward Direction
        while (DetectObject(T1,E1,1) < 10 && DetectObject(T2,E2,2) < 10)
        {
            Serial.println("Backward");
            Motor(BACKWARD);
            delay(200);
            Motor(STOP);
            delay(50);
        }
        // If Left Sensor detect object then go in Right Direction
        while (DetectObject(T1,E1,1) < 10 && DetectObject(T2,E2,2) > 10)
        {
            Serial.println("Right");
            Motor(RIGHT);
            delay(200);
            Motor(STOP);
            delay(50);
        }
        // If Right Sensor detect object then go in Left Direction
        while (DetectObject(T1,E1,1) > 10 && DetectObject(T2,E2,2) < 10)
        {
            Serial.println("Left");
            Motor(LEFT);
            delay(200);
            Motor(STOP);
            delay(50);
        }
        // If Both Sensors detect no object then go in Forward Direction
        while (DetectObject(T1,E1,1) > 10 && DetectObject(T2,E2,2) > 10)
        {
            Serial.println("Forward");
            Motor(FORWARD);
            delay(200);
            Motor(STOP);
            delay(50);
        }
    }

    void Motor(MOTOR motor)
    {
        switch (motor)
        {
        case STOP:
            digitalWrite(M1, LOW);
            digitalWrite(M2, LOW);
            digitalWrite(M3, LOW);
            digitalWrite(M4, LOW);
            break;
        case FORWARD:
            digitalWrite(M1, HIGH);
            digitalWrite(M2, LOW);
            digitalWrite(M3, HIGH);
            digitalWrite(M4, LOW);
            break;
        case BACKWARD:
            digitalWrite(M1, LOW);
            digitalWrite(M2, HIGH);
            digitalWrite(M3, LOW);
            digitalWrite(M4, HIGH);
            break;
        case LEFT:
            digitalWrite(M1, HIGH);
            digitalWrite(M2, LOW);
            digitalWrite(M3, LOW);
            digitalWrite(M4, HIGH);
            break;
        case RIGHT:
            digitalWrite(M1, LOW);
            digitalWrite(M2, HIGH);
            digitalWrite(M3, HIGH);
            digitalWrite(M4, LOW);
            break;
        default:
            break;
        }
        delay(100);
    }

    long DetectObject(uint8_t trigPin, uint8_t echoPin, int sensorNo)
    {
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        Serial.print("Distance Sensor");
        Serial.print(sensorNo);
        Serial.print(": ");
        Serial.print(pulseIn(echoPin, HIGH) * 0.034 / 2);
        Serial.println(" cm");
        return pulseIn(echoPin, HIGH) * 0.034 / 2;
    }

I am getting continuously getting Backward in the Serial monitor.
Output of Serial Monitor -
Distance Sensor1: 20 cm
Distance Sensor2: 15 cm
Backward
Distance Sensor1: 17 cm
Distance Sensor2: 21 cm
Backward
Distance Sensor1: 24 cm
Distance Sensor2: 9 cm
Backward

But when I created 2 different methods for each Ultrasonic Sensor. It is working fine.
I want to have a single method for N number of Ultrasonic Sensors.
Thanks in Advance!

@jsotola I have added the output of Serial Monitor.

I think you should try restructuring your loop(). At the start of the loop(), get a value for DetectObject(T1,E1,1) and DetectObject(T2,E2,2) called say Det1 and Det2 respectively. Then change your while statements to if statements, say if (Det1 < 10 && Det2 < 10 ) . . .

@6v6gt Already tried it is not working.

The problem lies in the function, that does the ultrasonic detection. First I would suggest to not do Serial printing between the trigger pulse and pulseIn(), since the Serial transmission might take longer (for example when the buffer is full) and then your reading is garbage. Execute pulseIn() directly after the trigger pulse part and save the result in a local variable, which you can later print and return. If you do that, your problem is also solved.
For understanding what actually happens with your code, I annotated the function with some comments:
long DetectObject(uint8_t trigPin, uint8_t echoPin, int sensorNo)
    {
        // Create Trigger pulse
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);

        // Do some printing
        Serial.print("Distance Sensor");
        Serial.print(sensorNo);
        Serial.print(": ");

        // Read a pulse and print it directly to Serial
        Serial.print(pulseIn(echoPin, HIGH) * 0.034 / 2);
        Serial.println(" cm");

        // Read ANOTHER pulse and return it
        return pulseIn(echoPin, HIGH) * 0.034 / 2;
    }

As you can see, you are trying to read 2 pulses. But there is only one echo pulse. That one pulse is read by the first execution of pulseIn() and you print the result to Serial, so in the Serial Monitor you are seeing the correct value.
After that you are executing pulseIn() again and returning the result. pulseIn() will wait for a pulse to begin (so it can start counting the time). But there is no second pulse on the echo line, so pulseIn() will exit after a timeout (by default 1s). On timeout this function returns zero. So every time you execute this function, it will return zero.
If you then look at the logic in loop(), you can easily see why you are only getting backwards. The code is stuck in the first while loop, because the value returned from the function is always zero, which is smaller than 10.
Here is a pseudo code version of how your function really should work:
execute trigger pulse
execute pulseIn function and save result in local variable
print whatever you want to Serial
return the value of the local variable

Thanks alot. It's working now. Learned something new.


text:
ESP32 HCI command for setting BLE TX Power
Does anyone know if there's an HCI command for setting the TX and the advertising power for BLE on an ESP32?
I have a Nano 33 IoT and a MKR 1010, and it has its power set annoyingly low for advertising and transmission.  The library that I'm using is ArduinoBLE, which uses HCI to communicate with the ESP32.
I believe that espressiv allows the power level to be set using their dev kit, and I know that other vendors (e.g., TexasInstruments) provide extensions to HCI for setting power levels, but I haven't been able to find an HCI command for ESP32 anywhere.
Any ideas on other ways that I could do this other than HCI would be welcome too (e.g., other libraries for BLE that would work with the MKR and Nano series of boards, but would allow setting the power level for advertising and transmission.

Nano 33 BLE doesn't use ESP32. it has a nRF52. do you have Nano 33 IoT?

No, you're right!  I've got a bunch of these things sitting around... I have an IoT and also a MKR1010.  I'll update the post.

on Nano 33 IoT and MKR 1010 the esp32 is controlled by the firmware so if the firmware doesn't have the setting in API, then it is not available

So you're telling me the AndroidBLE library that I'm using, which uses HCI commands to control and interact with BLE subsystem is NOT talking directly to the ESP32?

it is/ the firmware does the setup() with esp_bt_controller SDK functions, but then the esp32 SDK listens for HCI commands on UART.

OK, so that's the point of my question.  I don't think that setting power level is a one time operation (at setup only). For example, their SDK allows you to set transmission power for each connection.  I just need to know the HCI command to set the advertising power level, and I can call it myself as an HCI command through the UART.  Maybe there isn't an HCI command for setting power levels.  I just can't find info on the list of HCI commands supported by the chip anywhere!


text:
MKR GPS Shield Sampling Frequency
I have the MKR 1010 and am working on a circuit that needs realtime GPS positioning.  I bought the MKR GPS Shield, and am using it on the I2C bus (attached via cable to the 1010 board), and am using the Arduino_MKRGPS library in my sketch.
I am attempting VERY basic interaction with the board at the moment, and basically just want to print out the GPS coordinates to the serial.
I am using the GPSLocation sample from the Arduino_MKRGPS library (see here):
  /*
  GPS Location

  This sketch uses the GPS to determine the location of the board
  and prints it to the Serial monitor.

  Circuit:
   - MKR board
   - MKR GPS attached via I2C cable

  This example code is in the public domain.
*/

#include <Arduino_MKRGPS.h>

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

  // If you are using the MKR GPS as shield, change the next line to pass
  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  if (!GPS.begin()) {
    Serial.println("Failed to initialize GPS!");
    while (1);
  }
}

void loop() {
  // check if there is new GPS data available
  if (GPS.available()) {
    // read GPS values
    float latitude   = GPS.latitude();
    float longitude  = GPS.longitude();
    float altitude   = GPS.altitude();
    float speed      = GPS.speed();
    int   satellites = GPS.satellites();

    // print GPS values
    Serial.print("Location: ");
    Serial.print(latitude, 7);
    Serial.print(", ");
    Serial.println(longitude, 7);

    Serial.print("Altitude: ");
    Serial.print(altitude);
    Serial.println("m");

    Serial.print("Ground speed: ");
    Serial.print(speed);
    Serial.println(" km/h");

    Serial.print("Number of satellites: ");
    Serial.println(satellites);

    Serial.println();
  }

  delay(100);
}

What I'm seeing is that the GPS takes on the order of 30-90 secs to initialize, and then only provides new updated coords every 20-30 secs.  This is all with a clear view of the sky.
Is that really what to expect from this module?  I was under the impression that it could provide several samples per second.  Documentation seems to be very lacking for the Arduino_MKRGPS library.  Anyone else have insights or experience with this module?
Thanks!

It seems that the problem with the GPS was caused by my usage of the arduino delay(...) method in my loop.
I'm assuming that by using delay, the connection to the GPS module was being severed, and in effect, every loop was forcing a reconnect and a new download of satellite details.
In summary, when needing high sample frequency interaction with the GPS, using delay in the sketch won't work.
EDIT:
I've done a lot of digging since originally posting this question/answer and wanted to add my findings for others that are struggling to make the MKR GPS module work for higher than 1Hz sample rate use cases.
I had to make the following two changes to the Arduino_MKRGPS library:

increase baud rate of the GPS connection.  In the very last line of GPS.cpp...

GPSClass GPS(Serial1, 460800, serialDDC, 400000, 7);

In GPS.h, make the sendUbx method a public member of the GPS class.  This allows me to send low-level commands to the SAM-M8Q from my sketch.

After this, I can construct low-level messages in my sketch and configure the GPS to my liking.  Here's what I did to increase the sample rate to 3Hz in my sketch's setup method:
  Serial.println("Configuring GPS refresh rate...");

  //  UBX-CFG-RATE (0x06 0x08) Navigation/Measurement Rate Settings
  //  See UBX-13003221 section 32.10.23.1
  byte payload[6];

  memset(payload, 0x00, sizeof(payload));

  uint16_t measRate = 333;    // ms between gps data publish  (min of 100)
  uint16_t navRate  =   1;    // ratio between measurements and nav solution calculations
  uint16_t timeRef  =   1;    // The time system to which measurements are aligned (0: UTC, 1:GPS, ...)

  // write out the unsigned shorts in little-endian form
  payload[0] = measRate & 0xff;
  payload[1] = (measRate >> 8) & 0xff;
  payload[2] = navRate & 0xff;
  payload[3] = (navRate >> 8) & 0xff;
  payload[4] = timeRef & 0xff;
  payload[5] = (timeRef >>8) && 0xff;

  GPS.sendUbx(0x06, 0x08, payload, sizeof(payload));

  Serial.println("  > done");

Hope this helps someone else struggling with higher data rate use cases.  There's still room for improvement, I think, in particular by reducing the number of sentences returned by the GPS.  I haven't been able to get the sample rate higher than 5Hz, while technically the GPS is supposed to be capable of doing 10Hz.  I'm not sure where the bottleneck is.

Can you post your entire code. The delay can cause some problems mainly because the data is streaming into a buffer and it is supposed to be either read or processed almost immediately depending on the buffer size. I checked the library and the I2C example is built over the UART library and it might be acting up. With UART it is usually pretty straightforward and you should be able to see streaming data coming from the GPS multiple times a second

I edited my original post to include the entire sketch.  It's the sample called "GPSLocation" included in the Arduino_MKRGPS library, with the simple addition of the delay statement at the end of the loop.


text:
Arduino Uno board not recognized in IDE. Board is not in device manager!
My arduino uno is not recognized by the Arduino IDE. I'm using 1.8.0, The IDE is not showing the COM. The tool section is showing only COM 1, i.e. the hardware.
I opened Device manager, there is no board for UNO.
Help me please.

Arduino Nano works fine.
I have CH340 driver already installed. My computer do not make any "hardware connected sound". I have 3 arduino IDE versions - 1.8.0, 1.8.9, 1.8.10!.

Bad cable, or power only cable, will show the same thing. Try another one.

If you unplug/plug the USB cable, you might hear the typical "new device" sound. If yes, and there's a unknown usb device appearing,  it's not a real Arduino Uno, and you need an extra usb driver for it.  ( CH340 instead of 16U2 )

Even when I unplug/plug the USB cable, the computer do not make any sound and in addition, it do not even seem to affect the screen at all.(Do not show any change in IDE or Device Manager).

My arduino nano works fine & my computer do have an CH340 driver already for my Nano board.

I had a similar problem with my Arduino. My solution is to unplug it, replug it and do what you need to do before the computer can auto-configure it.
I hope it helps! :)
BTW make sure you are choosing the right board.

I really uninstalled and reinstalled arduino ide because of this problem. I tried replugging my board then too it does not work.

And I also have 3 Arduino IDE versions:- 1.8.0, 1.8.9, 1.8.10

According to https://www.arduino.cc/en/Guide/ArduinoUno, you may need to install a separate driver for the Arduino Uno because it does not have a true USB port. The details are in the link.

My arduino UNO chip says AtMega16u2..A97VB.