text:
Measuring car speed between two points: What sensor to use and how to cover the distance?
PROBLEM
Cars regularly exceed the speed limit in our street
SOLUTION
Measure each car's speed and clearly display the speed to the driver
EXECUTION

Measure the time the car takes to cover a set distance (e.g. 25 meters) to calculate the speed
For this I'd set up two sensors and calculate the difference between the timestamps recorded between the car passing the first and second sensors -> then convert into km/h
Display the result on an LED screen

CHALLENGES & QUESTIONS
A. What sensors should I use here? Photoresistor with laser diode, digital or analog IR sensor, ...
B. How can I best cover the distance between the sensors and connect them to the Arduino? Long wire, wireless, connect two Arduinos, ...
Thanks!

radar is used to measure speed of cars. google found https://www.sierzega.com/en-us/about-us/our-products-services/speed-displays

Thanks @Juraj. I posted a question regarding a 150$ project on an Arduino forum so you send me a link to buy 2000$ ready-made systems... Sorry, not very helpful at all. The point is to build stuff! :-)

@Uralan your post says nothing about a price limit

Okay  that's true.

https://www.eevblog.com/forum/projects/playing-with-cheap-hb100-doppler-radar-module-for-car-speed/

Doppler radar is often used, but may be overkill? Perhaps the best-known DIY radar project is MIT's open courseware. There's a separate paper devoted to the antenna if you want a deep dive.

Why 25meters? If you place the two sensors 1 meter apart, you only need 1ms accuracy to get km/h (assuming a 50km/h speed limit). The Arduino can handle 1ms resolution with ease.
I'd probably go with 3-5 meters, so you don't need your setup to be that precise (i.e. distance and alignment of the two sensors). Lowering the distance also makes it less likely for two cars, from both directions, to simultaneously be inside your sensor area.
For the sensors, the biggest problem is the legal one. Having objects on/near the road could cause some liability issues. The laser solution is probably the least likely to cause this issue. Though I'm unsure about having a display next to the road.
You could go with laser and photo-transistor on one side of the road. And a reflector/mirror on the other side. I'd probably go with an IR laser, so it's invisible. You'd have to shield the photo-transistor as much as possible from ambient light, so a sudden cloud won't trigger it. You probably still need to do some filtering in software.
There are radar modules available, but I think they are pretty expensive.
Another option is a Laser range sensor, like this one from sparkfun

Thanks! Good points! I will probably go for IR laser curious to see how well it'll all work...

You need 3 ir/laser emitters, mirrors and phototransistor sensors to get  the car's direction and some reliability. Good luck with the legal issues.

You can also modulate the laser, similar to how tv remotes modulate the signal, so other IR light sources don't interfere. You could maybe even use IR receivers, instead of phototransistors.I don't have a great solution on how to align the system, so the laserbeam hits the sensor. Maybe some crappy phone camera that doesn't have an IR filter, so you can see where it's pointing.

The alignment issue would be solved by using a corner reflector instead of a mirror. See also Retroreflector.


text:
APDS-9960 detected but not showing output on serial monitor
I just bought an APDS-9960 sensor yesterday and tried it out today using Sparkfun's example from its APDS-9960 lib, and the only thing it printed out was:
"SparkFun APDS-9960 - ProximitySensor" twice then it didn't show any output
Using an Arduino Uno, and wires are connected correctly:
APDS :  Arduino Uno
VCC  :  3.3V
GND  :  GND
SDA  :  A4
SCL  :  SCL
INT  :  D2
I've also tried I2C scanning, and the device address was shown, but SparkFun's example code just didn't work at all.

Using PCB terminals because another sensor will also be integrated into the Arduino Uno.

Code:
/****************************************************************
...
****************************************************************/

#include <Wire.h>
#include <SparkFun_APDS9960.h>

// Global Variables
SparkFun_APDS9960 apds = SparkFun_APDS9960();
uint8_t proximity_data = 0;

void setup() {

  // Initialize Serial port
  Serial.begin(9600);
  Serial.println();
  Serial.println(F("------------------------------------"));
  Serial.println(F("SparkFun APDS-9960 - ProximitySensor"));
  Serial.println(F("------------------------------------"));

  // Initialize APDS-9960 (configure I2C and initial values)
  if ( apds.init() ) {
    Serial.println(F("APDS-9960 initialization complete"));
  } else {
    Serial.println(F("Something went wrong during APDS-9960 init!"));
  }

  // Adjust the Proximity sensor gain
  if ( !apds.setProximityGain(PGAIN_2X) ) {
    Serial.println(F("Something went wrong trying to set PGAIN"));
  }

  // Start running the APDS-9960 proximity sensor (no interrupts)
  if ( apds.enableProximitySensor(false) ) {
    Serial.println(F("Proximity sensor is now running"));
  } else {
    Serial.println(F("Something went wrong during sensor init!"));
  }
}

void loop() {

  // Read the proximity value
  if ( !apds.readProximity(proximity_data) ) {
    Serial.println("Error reading proximity value");
  } else {
    Serial.print("Proximity: ");
    Serial.println(proximity_data);
  }

  // Wait 250 ms before next reading
  delay(250);
}

I've tried putting delay(100); below Serial.begin(9600); as suggested here: https://learn.sparkfun.com/tutorials/apds-9960-rgb-and-gesture-sensor-hookup-guide/discuss and it did not help.
Any help is appreciated!

I cannot see in your image, how exactly the jumper wires are attached to the proximity sensor board. Are you sure, that they have good and stable contact?

the picture shows that it printed more than what you said

Hey @chrisl! Thanks for the comment. The issue went away by itself, somehow, so I'm guessing it's the sensor or the board. Thanks anyways!

source: Stack Exchange

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

sort: votes


text:
How to set the data length for SPI communication in Arduino library?
How can I set the number of bits that need to be transferred in SPI communication from a Slave chip to Master MCU using Arduino SPI Library in a SPI transaction? Let us say I want to read 14-bits data from Slave into my Master Arduino MCU then how would set this 14-bits in the SPI Library?

You don't. You transfer multiples of 8 bits. In general you would transfer 16 and discard or ignore 2.

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


text:
Play sound on top of background music using arduino uno tmrpcm library
We designed a big piano with 15 buttons on it. Every button has a proximity sensor. Whenever users interact with the sensor a specific sound plays for that button. My code is working fine for this purpose but now I want to add background music. Our piano button sound should play on top of that background music. I am using tmrpcm library, and I already added a bg music but when I interact with the sensor, bg music stops and starts from the beginning right after the piano button sound stops. Is there a way to play a sound without interrupting a bg music. Any help will be appreciated.

use two arduinos

Assuming you are using an Arduino Uno, You didn't say. As there are many Arduino platforms these days.
As the tmrpcm library is using the PWM  (Pulse Width Modulator) HW (Hard Ware) to recreate the sound waves from the WAV file on the SDCard, the PWM is not available for creating the sounds from your piano application (you didn't say what piano application you were using).  That said, it is not impossible to re-write both applications to SUM the two wave forms together mathematically before resampling the SUM and writing that sample value to the PWM HW to simulate the SUM of the two wave forms.  However, this is likely not trivial and it is also likely the Arduino Uno processor (an Atmel ATmega328P) will not be powerful enough (perform the math fast enough) to keep up with normal sound playback.
It would likely be much simpler to use 2 Arduino Uno boards and sum the sound from the sound file application and the piano application using analog techniques external from the Arduno Uno boards.

I think a single Uno could be made to do it, but if expediency is an issue, one should just use two Arduino Unos.

Perhaps you are right @GabrielStaples.  But there may be more problems to solve than the OP (or anyone) may want to deal with.  Can the tmrpcm library deal with WAV files of different sampling rates?  If so, then the piano application would have to be adjusted to create the same note at these new sampling rates.  Or the Arduino Uno would have to deal with the differences in sampling rates by re-sampling either the WAV file data or the piano data.

Yeah, it would take a lot of effort no doubt and require a lot of advanced skills and problem-solving. Could be a fun project for those who like to really push the limits of the Arduino, but just a nightmare for those who just want to get the desired results as soon as possible. And if one doesn't have the required skills up-front, and can only work on this nights and weekends, this could be a 3 yr project. I've had many of those: I start something I have no idea how to do, so it has taken me 3 yrs to eventually learn all the pieces and study the datasheet and figure it out.


text:
Use the stepper motor library with the A4988 driver?
I want to use this library: https://www.arduino.cc/en/Reference/Stepper
#include <Stepper.h>

The wiring for my driver is shown here:

https://www.pololu.com/product/1182
From the library, I'm stuck at the motor pins:
#define motorSteps 200
#define motorPin1 2    // STEP pin
#define motorPin2 3    // DIR pin

Stepper myStepper(motorSteps, motorPin1, motorPin2);

Is this library not compatible with this stepper motor driver? Or what needs to be defined for it to work?
More details on the library are here: http://www.tigoe.com/pcomp/code/circuits/motors/stepper-motors
The basic section of my code that works without the library is this:
digitalWrite(stepPin, HIGH);
delay(wait);
digitalWrite(stepPin, LOW);
delay(wait);

Yet, the two-wire circuit part of the library uses motorPin1 and motorPin2 in a way I don't understand:
switch (thisStep) {
  case 0:  // 01
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 1:  // 11
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 2:  // 10
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, LOW);
  break;
  case 3:  // 00
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, LOW);
  break;
}

https://github.com/arduino-libraries/Stepper/blob/master/src/Stepper.cpp
How should motorPin1 and motorPin2 be defined?

That library is not compatible with the A4988. It is intended to do the same job that the A4988 does. You provide a step direction and an instruction to step, and it does the stepping for you.
To use the A4988 you just set a pin HIGH or LOW for the direction, then toggle another pin to make it step. You don't really need a library for that.
However if you do want to abstract it with a library and add lots of cool extra features then you should look at AccelStepper which supports 2-wire drivers like the A4988.


text:
ESP32 Access Point and HTTP Web Server, how to send multiple parameters?
I made this minimal example in order to figure out how to get requests (or whatever they are called) to display in the serial monitor. However, none of the query parameters (in the URL) can be seen in the serial monitor at 115200 baud.
The files are below and here: https://github.com/adamelli/MinimalExamples/tree/main/22-1-25_query_parameters_submitButton
File structure
sketch (folder)

sketch.ino
data (folder)

index.html
selection.html

sketch.ino
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
#include <painlessMesh.h>

const char* ssid = "Wireless Controller";
const char* password = "12345678";

// User stub
void sendMessage() ; // Prototype so PlatformIO doesn't complain

Task taskSendMessage( TASK_SECOND * 1 , TASK_FOREVER, &sendMessage );

void sendMessage() {
  taskSendMessage.setInterval( random( TASK_SECOND * 1, TASK_SECOND * 5 ));
}

AsyncWebServer server(80);

void notFound(AsyncWebServerRequest *request) {
    request->send(404, "text/plain", "Not found");
}
IPAddress IP(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

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

  // Initialize SPIFFS
  if (!SPIFFS.begin(true))
  {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }

  WiFi.softAP(ssid, password);
  delay(500);
  WiFi.softAPConfig(IP, gateway, subnet);
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

// Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(SPIFFS, "/index.html", String(), false );
  });

  // Index.HTML NAVIGATION BUTTIONS ************************************************

  server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(SPIFFS, "/index.html", String(), false);
  });

  server.on("/selection.html", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(SPIFFS, "/selection.html", String(), false );
  });

  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request)
  {

    int paramsNr = request->params();
    Serial.println(paramsNr);

    for (int i = 0; i < paramsNr; i++)
    {
      AsyncWebParameter* p = request->getParam(i);
      Serial.print("Param name: ");
      Serial.println(p->name());

      Serial.print("Param value: ");
      Serial.println(p->value());

      Serial.println("------");
    }

    request->send(200, "text/plain", "message received");
  });

  server.begin();
}

void loop() {}

index.html
<!DOCTYPE html>

Main Menu

<button class="button">Selection</button>

<button class="button">Oblivion</button>

selection.html
<!DOCTYPE html>

<form action="/" method="get">

    Shape Size:

    <select name="size" id="size" style="font-size: 22px;">
      <option value="1"> 1   </option>
      <option value="2"> 1/2 </option>
        </select>

Speed:

    <select name="speed" id="speed" style="font-size: 24px">
      <option value="1">          Slowest </option>
      <option value="2" selected> Regular </option>
    </select>

<button class="submit" name="circle" value="3">Circle</button>

<button class="submit" name="square" value="4">Square</button>

</form>

The data files must be uploaded via "Tools" → "ESP32 Sketch Data Upload".
How is the data (size and speed) viewable in the serial monitor? What needs to change?

Thank you for making a minimal example! So many people won't bother to do it, and it's a huge help in debugging.

You have two handlers for "/":
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(SPIFFS, "/index.html", String(), false );
  });

and
server.on("/", HTTP_GET, [](AsyncWebServerRequest * request)
  {

    int paramsNr = request->params();
    Serial.println(paramsNr);

    for (int i = 0; i < paramsNr; i++)
    {
...

Only one will be called when you load the top level page. You'll need to combine them to both serve index.html and process the parameters being passed to it.

Thanks, but I still do not understand how to change the request body/message. I just want it to return to the main menu index without changing the content of that main index page. In the ino sketch request->send(200, "text/plain", "message received") changes the whole main index page. Yet when I take that request part out, the program does not compile.

@Adam you asked why the parameters are not printed. Well, because the handler in which you print them is never called due to the double definition.

Yes, but the first definition makes the main menu viewable. You mention combining the two. I tried combining them though trial and error edits, but nothing has worked. One of the two pages always either becomes "Not Found" or clears out to be left with "message received." I suppose I can ask another question, but it's going to be pretty much the same.

I think what @romkey say "combine" means that you need to something about the two duplicate routes. Not literally combine them. One easy way to fix the problem is to rename your route that handling the params to server.on("/submit", HTTP_GET, callback_func), and change your selection.html form submission to <form action="/submit" method="get">.

Changing selection.html form submission to <form action="/submit" method="get"> makes the selection.html page "Not Found" (and the params handle was changed)

@hcheung is right. You need to rethink how you are putting together your web page and where you're handling the parameters. You can't have two handlers for the same path ("/"). You can however change what you return depending on the presence or values of parameters. If you change the path to "/submit" then you'll need a handler for "/submit".

@romkey I changed the params handle to that (as I mentioned) and it results in "Not Found" on the selection.html page.

Did you also change the route that handling the params to server.on("/submit", HTTP_GET, [](AsyncWebServerRequest * request)?

@hcheung Yes, I did. Still, it does not work for me. Did you get it to work?


text:
ArduinoJson is not adding string to JsonObject. ArduinoJson broken?
So I've got this code

String GetTimeString(){
    strftime(dateArray, 100, dateFormat, getTimeInfo());
    dateString = String(dateArray);
    Serial.println(dateString);
    return dateString;
}

Being called later like this:
document["Time"] = GetTimeString();

But the resulting object looks like this:

September 12 2020 09:49:04
{"DryBulbTemp":80.762,"WetBulbTemp":72.74606,"Pressure":398.9942,"Humidity":68.32129,"Time":null}

So it behaves this way no matter if I print what comes out of the function immediately before the assignment to the "Time" property.  Is ArduinoJson just broken?

https://arduinojson.org/v6/faq/why-is-the-output-incomplete/

ArduinoJson 6 works with fixed memory allocation.
When you create a JsonDocument, you must specify its memory capacity.
If the capacity is too small, some parts will be missing.
The solution is to increase the capacity of the JsonDocument.
Use the ArduinoJson Assistant to know the memory requirements for your project.

It is not at all logical that the 'Time' Property would persist but not the value.  Nor is the requirement for the allocation to be N+2 whats actually in there.  But sure, downvote my question.

I didn't downvote your question. If you believe ArduinoJson is broken, please open an issue on GitHub. If you want to learn how the library works, please read the documentation.


text:
Arduino code equivalent for python code binascii.unhexlify command
I want to convert a hexadecimal string or an array of bytes to binary data.
For example, if i have a string like
'424D368403'
my output should be like
b'BM6\x84\x03'
The python code binascii.unhexlify('424D368403') gives the correct output.
But, I want to do this in arduino code.
Can someone help me in creating an arduino code / command in getting desired output?

https://arduino.stackexchange.com/a/77974/4143

@Majenko, even if the answer is almost the same, the questions are different. but this question is better. maybe adapt the answer here?


text:
DS3231 rtc.begin() always returning false
I am using Arduino UNO with a RTC DS3231 module.
I have connected SDA & SCL pins of RTC DS3231 with Arduino SDA & SCL pins near AREF pin.
RTC module is having attached battery also.
My code is as below :
#include <RTClib.h>
#include <Wire.h>
RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
};

void setup() {
  Serial.begin(9600);
  Wire.begin();
  delay(3000);
  //rtc.begin();
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
       // Following line sets the RTC with an explicit date & time
    // for example to set January 27 2017 at 12:56 you would call:
    // rtc.adjust(DateTime(2017, 1, 27, 12, 56, 0));
  }
}

void loop() {
  DateTime now = rtc.now();
  Serial.println("Current Date & Time: ");
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.println("Unix Time: ");
    Serial.print("elapsed ");
    Serial.print(now.unixtime());
    Serial.print(" seconds/");
    Serial.print(now.unixtime() / 86400L);
    Serial.println(" days since 1/1/1970");

    // calculate a date which is 7 days & 30 seconds into the future
    DateTime future (now + TimeSpan(7,0,0,30));

    Serial.println("Future Date & Time (Now + 7days & 30s): ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(1000);

}

While running the above command and opening the Serial Monitor, I always get following output:
Couldn't find RTC

Can anyone help me to correct this problem.

Did you connect the DS3231 to VCC and did you connect the DS3231 module's GND to your Arduino's GND? Does the DS3231 module already have pullups on the SDA and SCL lines?

Yes, I did connect DS3231 to VCC and GND with Arduino GND. How will I know if DS3231 module have pullups on SDA and SCL lines.

That should be in the datasheet or the schematics. Other question: did you run an I2C scan sketch or a different library to see if the DS3231 is visible to your Arduino?

Yes, it worked. Actually the problem was in faulty wire in SDA connection. While checking the I2C scan, it showed no I2C devices, then I checked the connections and found SDA connection faulty. After restoration, the RTC module is working fine. Thanks for the support. Though feeling very silly for such mistakes.

Feel free to post a self-answer, so that others don't need to read the whole comments dialog. Congratulations, btw. Simple problems sometimes are the hardest.

No fault is there in code. Rather, it was an faulty connection which prevented RTC module from working. Now, after restoration, the RTC module is working fine.

You can mark you own question as “answered”.


text:
Can FastLED be made faster?
I am using FastLED to drive 16 pixels on an addressable  WS2812B RGB LED strip. My application has extremely tight timing constraints. Specifically, I need to turn the LEDs on and off within less than 1 ms. I tried FastLED but it requires a minimum of 2.5 ms to execute the Show command, regardless of the number of LEDs attached. I analyzed another library and that one has the exact same limitation. In fact, I found a snippet of code that said roughly: "if this operation performs in less than 2500 us, then wait idly until the 2500 us have passed. Apparently this wait is necessary due to timing requirements of WS2812x strips. Does anyone have any advise about other addressable RGB LED strips or libraries that can be turned on and off within 1 ms?

What are you trying to achieve that needs such fast control of addressable LEDs? I suspect you are going about whatever it is the wrong way.

And why do you want to use the WS2812B LEDs for such tight timing. That doesn't seem to be a good choice, considering the 1ms time constraint and the fact, that you only have 16 pixels

I want to make a POV clock (Youtube it). In such clocks LEDs on a rotating arm are lit at precisely timed moments to create the illusion of an analog clock. For that to work, the arm must rotate at >10 revs per sec. For a clock with hands for minutes and seconds I need to divide a full rev into 60 visually distinct sectors. For that, I need to turn the LEDs on and off 60 times during one rev (100 ms).  Thus, I need the Show function to run 60 times in 100 ms. That is why the Show function's "hardwired" duration of exactly 2.5 ms is not fast enough.

I want to use the WS2812B LEDs because of the convenience of needing only one pin for data. If I used 16 individual 5mm RGB LEDs, then I would need 3x 16 = 48 PWM-enabled pins to control the LEDs. In my current attempt with a WS2812 strip I need only 3 wires between the stationary Arduino (or Teensy) and the continuously rotation LEDs, which allows me to use a slip ring to transfer power and data to the LEDs. Others who built POV clocks mounted their Arduino Nanos onto the rotor arm so they only need to transfer power through a slip ring but not a lot of PWM signals.

By default the fastLed is limiting the refresh rate to 400 fps (i.e. 2.5ms).
You can disable that with FastLED.setMaxRefreshRate(0);


text:
Connect and detect multiple arduinos using firmata
i am trying to connect several arduinos to usb ports and have the abillity to define between them.
i added Firmata.attach function on the arduino board. how do i call it from my python script?
thank you
#define BOARD_NAME '1'
void readName() {
      Firmata.sendString(BOARD_NAME);
    }

void setup()
{
  Firmata.attach(READ_NAME, readName);
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);

  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
  Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.attach(SYSTEM_RESET, systemResetCallback);

  // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega,
  // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this:
  // Serial1.begin(57600);
  // Firmata.begin(Serial1);
  // However do not do this if you are using SERIAL_MESSAGE

  Firmata.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101
  }

  systemResetCallback();  // reset to default config
}

with pyfirmata.


text:
Converting from Float to Int yielding weird results. What am I doing wrong?
So I am trying to take GPS data with a Neo 6M gpsmodule (that is what is covered up by the square for privacy sake) and process it by adding/multiplying to get large integers representing the GPS data. This is using Arduino nano. When I try and convert the float numbers to integers, it gives me totally different numbers. 1242895 turns into -2289, and 611194 turns into 21370. I have tried so many things, but am stumped as to what is going on. Is it related to pointing? It's been awhile since I learned about pointers in my C++ class. X and Y are initialized as int global variables.

Please copy and paste your code here instead of posting a screenshot.  A picture of some text is about the most useless thing on the internet.  It can't be copied and edited.  It's hard to read.  Screen readers can't touch it.  Please in the future just copy and paste the text itself.

Covered up for privacy sake? You are sharing the same data below, with only a trivial transformation.

On an Arduino board with the 328 processor, an INT is stored as a 2 byte value, so the max number is 32,767.
You want to use a LONG which is a 4 byte number which has a max of 2,147,483,647.
When the variable you are using is not big enough, the number rolls over, which is why you end up getting a negative number.

I've fixed up the capitalization in your post, but in future please try to make English sentences. They start with a capital letter. This isn't a game chat where you just type in all lower-case.

@NickGammon Wow. Thank you so much.


text:
Is it possible to gather data while the Arduino is being powered with a battery, connect to comp, and then read off the values in Serial Monitor?
I want to do a project where I gather data such as sunlight hours per day, as well as temperature highs/lows. Once I have gathered 24 hours worth of data, I want to hook it up to the computer to read off the values in Serial monitor.
When I try and open the Serial monitor, it restarts the program wiping all the memory.
I tried doing something with PROGMEM, but that didn't seem to help as it is only for constants.
I want to avoid using an LCD to display data if possible.

Are you going to cut power before connecting to the pc? How much data do ypu expect to accumulate within those 24h?  Is there just one value each for sunlight hours, temperature max and temperature min?

It will be powered by the 9V port, so it will not lose power. I am just storing 5 variables. Hours of sunlight, temperature high, temperature low,  humidity high, and humidity low.

The reason you lose your data at the moment is because opening the serial port resets the Arduino. That's how it gets the bootloader going for programming. You will have to disable that to prevent the reset. There's a trace inside a jumper "RESET EN" which you can cut to disable the reset, then bridge the jumper again when you want to reprogram. Or you can add a large capacitor (100uF for example) between RESET and GND to try and negate the reset pulse.

Yes, this is perfectly possible. You will need to write a routine that you can trigger via Serial. For example you will listen on Serial until you get the dump command. Then run a function that spits your variables out to Serial.
You just have to be careful where you save your 5 variables.
If stored in memory (RAM), you should avoid power loss. Therefore I'd suggest a FTDI USB-to-Serial adapter. There you just connect the TX, RX and GND wires and proceed with the Arduino IDE's Serial Monitor.
If stored in EEPROM, you can use the regular USB connector of Arduino.

I will not have any power loss as I am using the 9V barrel jack. Maybe there is a brief power loss once I connect it to the computer and then it switches power sources? EEPROM might be a good option. I am just worried that it will fill up too quickly after awhile.

You should not attempt to power Arduino from Barrel Jack AND USB at once.

Good to know, thank you.

@AustinJohnLippincott it's my understanding that Arduinos include protection circuitry so that you CAN connect both the USB and barrel jack at the same time


text:
How to wire a three-pin on-off-on switch for reading input?
I would like to read the output of an on-off-on switch with my Leonardo board, but I have very little knowledge of electronics and don't know how to wire it up.
This is the switch in question: E-Switch 200MSP4T1B1M1QE
The switch has three pins. Generic three-pin SPDT wiring diagrams I've found suggest that the two outer pins should be connected to separate lights and the middle pin should be connected to the power source. Those lights also have a ground connection.
I don't want to power anything in a literal sense, I only want to have the Leonardo read the output of the switch. The end goal is to have the two ON positions read as separate button presses (eventually using a joystick library, in case that changes how the switch needs to be wired).
My questions are:

Is the above wiring example correct for my use case?
Is the output of the switch considered digital or analog?
Is a wire from the switch to GND not required?

One final note - I'm not using a breadboard, but connecting the wires directly from the switch to the board.

you could use analog input and use only one pin ... https://www.instructables.com/id/Analog-Keypad-Backpack/ ... also google arduino resistor ladder

You talk about wiring a switch to control lights directly. Instead, you want to use your switch to send information to your Arduino.
You link to an SPDT (single pole, double throw) switch. When flipped one way, it connects the center pin to one of the outside pins, and when flipped the other way, it connects the center pin to the other outside pin.
If you want the Leonardo to read the state of the switch as 2 separate switches/button presses, wire the 2 outer pins of the switch to 2 separate digital inputs on the Arduino.
You need to force each input to either ground or +5V when it's not connected to anything, or it will "float" and you'll get semi-random high and low readings.
I suggest setting the Arduino input pins to INPUT_PULLUP mode. That connects the inputs internally through a resistor to +5V. If you don't connect anything to the pin, it reads as HIGH. When the button is pressed/switch is closed, it reads LOW. That might seem a little confusing, but it means you don't need external resistors.
You'd then attach those to pins to the two outer pins of your switch, and attach the center pin to ground (GND).
If you flip the switch one way, it would connect one outer pin to the center pin. That would connect that Arduino pin to ground, and the reading on the pin would drop from HIGH to LOW. Flip the switch the other way and it would connect the other pin to ground, at that other pin would drop from HIGH to LOW.
It is also possible to wire your switches using INPUT mode, not INPUT_PULLUP, and have them read LOW when the switch is open, and HIGH when closed, but to do that you'll need external pull-down resistors. (And wiring it will be a little painful without a breadboard or PC board.)
To answer your questions:

Is the above wiring example correct for my use case?

You don't show a wiring example. You talk about how to wire a switch to switch power to a pair of lights directly, without using a microcontroller. That's not relevant here.

Is the output of the switch considered digital or analog?

It would make sense to use it as a digital input, since you need it to give you 2 states, open and closed.

Is a wire from the switch to GND not required?

You need to connect the center pin to either ground +5V, as discussed above.

See the diagram in Edgar's answer. A picture is worth a thousand words.

This is exactly what I was looking for, thank you! I would say this is the better answer. Not that the diagrams were bad, necessarily, but for someone with little wiring/circuitry experience the diagrams only confused me more.

If you feel this (or Edgar's) answer answers your question you should accept it. (Accepting the first/best answer that answers your question is expected on Stack Exchange sites.)

I suggest this simple circuit:

simulate this circuit – Schematic created using CircuitLab
Set both inputs to INPUT_PULLUP. If the input reads LOW, that means it has been grounded by the switch.

Edit: Per Duncan’s request, here is the alternative circuit with the polarities inverted. With the switch’s common connected to Vcc, the inputs should be set to INPUT_PULLDOWN. However, most Arduinos do not support this mode, for lack of internal pull-downs. Then one has to use external pull-downs instead, and set the pins to INPUT.

simulate this circuit
With this circuit, a pin reads HIGH when it is connected to +5V by the switch.

I didn't notice Duncan C posted an answer just while I was preparing mine. Both answers are the same: one with words, the other with an image.

I haven't used CircuitLab very much. A diagram is soooo much clearer. (voted.) Could you also show the alternate circuit with the switch connected to +5V, with pull-down resistors? Some newbies find LOW  == switch on confusing.

@DuncanC: OK, edited as per your request.

Why not save an input and use the != and == to determine which way the switch is positioned. less code less hardware.

@Gil: I don't understand. Did you notice it's a 3-positions switch? Would you post an answer expanding on your idea?

Gil has a good point. With a SPDT switch, you could wire it to turn on one light as it turns the other one off. If you're just passing info to an Arduino, you could only wire one input, and infer that the state of the other input is the opposite of the first input.

@DuncanC: Not with the 3-position switch the OP linked to: position 1 (left, momentary): terminals 2 and 3 connected, position 2 (center): nothing connected, position 3 (right, momentary): terminals 2 and 1 connected. See the datasheet.

Oh, I didn't realize it was that type of switch. I stand corrected.

Simple No center off was indicated in the drawing and in two of three statements. If it were then two inputs would be needed. This was assumed because I did not properly read his statement: I would like to read the output of an on-off-on switch.  However if you look up his link it is a DPDT no center off stated hence maybe I was correct. The data sheet gives us a lot of choices. Maybe the question needs a bit of clarifying.

Alternative Circuit
For the on-off-on switch, the MSP-3 and MSP-4 operate as follows:

Figure 1 – Operation of MSP-3 and MSP-4 switches.

POS
Connection
MSP-3
MSP-4

1
Terminal 2 to Terminal 3
ON
(ON)

2
Terminal 2 to open circuit
OFF
OFF

3
Terminal 2 to Terminal 1
ON
(ON)

Here is an alternative way to connect the SPDT to the MCU which is useful when running out of pins because it only requires one input pin. It does however require more complicated software to interpret the input e.g., hysteresis and debounce could be implemented with thresholds such as:

> 90% Vcc for > 50 ms means high.
< 10% Vcc for > 50 ms means low.
> 45% Vcc and < 55% Vcc for > 50 ms means OFF.
anywhere in between means no change.

Figure 2 – Connecting SPDT switch to MCU.
Throw vs Stop vs Contact
In normal parlance, a throw describes a physical action that moves a mechanism to a new mechanical stop; and throws are distinct from stops and contacts. As such, a switch is a transducer that converts physical movements (throws) to an electrical signal via a system of mechanical stops and electrical contacts.
From Figure 1, the totals are 2 throws, 3 positions, 2 contacts and 1 pole.
However, matters have been confused by a minority of people erroneously metamorphosing the term “throw” to mean “mechanical stop” or “electrical contact.”  As you can see in this example—as is often the case—the number of throws equals the number of contacts, but that is not always the case. For example, if there were a centre contact for the centre stop, there would be three contacts, but still only two throws. Perhaps the fact that throws and contacts are often equal in number has led some people to conflate and confuse the separate entities. And perhaps that the number of stops can sometimes equal the number of contacts has led some people to conflate and confuse them too. For this kind of switch, the number of throws is always one less than the number of stops.
Matters are not helped by the E-Switch 200MSP4T1B1M1QE datasheet showing an incorrect schematic for the MSP-3, 4 and 5 that omits the centre mechanical stop that should be labelled OFF.
I’ve re-annotated the datasheet, Figure 3, and modified the following prose to comply with the common-sense approach of Figure 1, being mindful that a minority of people use “throw” to mean “contact,” and added the correct schematic for MSP-3, 4 and 5. (The original annotated version and prose was an attempt to use the datasheet’s own erroneous nomenclature and schematic.)

Figure 3 – Annotated datasheet.
MSP-1, 2 and 6 are actually single-throw switches despite what the datasheet implies which conflates its description of its SPST with its SPDT switches (which caused some confusion in the comments about the intent and variety of the switch).
The switch required for the above example is the MSP-3 on-off-on. Or to simulate momentary button presses, the MSP-4 (on)-off-(on). Both of these are single-pole double-throw switches (SPDT), not because they have 2 electrical contacts, but because they have 2 physical throws.
In the context of the erroneous datasheet, throws and contacts are erroneously synonymous. In normal parlance, neither throws nor positions are electrical contacts/terminals/pins (though the datasheet has conflated them as well). However, each mechanical stop does have an associated electrical connection/disconnection that should be explained in the datasheet. Unfortunately, in this case, the table in the datasheet has conflated SPST with SPDT and used the term “NONE” to indicate that a position doesn’t exist for the SPST types (MSP-1, MSP-2, and MSP-6). For MSP-3, 4, and 5, notice how POS 2 doesn’t have an associated contact/terminal/pin in the green schematic, Figure 3.
From experience, the only way to be sure is to buzz out the switch with a multimeter (continuity test). So, keep Figure 1 in your mind and a multimeter in your hand, and you won’t go far wrong.
Conclusions

Throws are physical.
Stops are mechanical.
Contacts are electrical.
Claims such as, “My contact is a throw.” are delusional.
Conclusions can be lyrical.

Phantom Scroll-By Downvoter
This answer has a attracted a phantom downvote with no comment expressing why this is warranted.
Does the phantom think:

the alternative circuit is wrong?
the thresholds are wrong?
the errant use of the English language and dodgy schematics in the datasheet are acceptable?

Bear in mind that the terms “throw,” “stop,” and “contact” (their meanings and usage) are taught by schoolteachers to millions of school children every year; and used by billions of English speakers every day. Is the global education system (which isn’t perfect) wrong on this particular point? On what grounds and exceptional circumstances is a datasheet allowed to use such terms in an inappropriate manner?

Comments are not for extended discussion; this conversation has been moved to chat.


text:
ATMega328p internal comparator problem - ISR(ANALOG_COMP_vect) not firing
After being introduced to this code on github, and exploring electronoobs tutorial I was compelled to try and recreate it with the Arduino Nano, and using the A0-A3 analog comparator inputs. Currently, I am just trying to get the rising edge of the receiver transducer to be recognized in the interrupt. Thus, I think my problem resides in ISR(ANALOG_COMP_vect)
Using an oscilloscope confirms that the ultrasonic transducer is firing every 100 ms, and I can detect the ping with the receiver as a small voltage above GND, which should trigger the ISR interrupt with DIO6 connected to GND... but that is not happening...
Here is my code:
#include  <avr/interrupt.h>

#include  <stdint.h>
#include  <stdlib.h>
#include  <stdio.h>
#include  <stdbool.h>

#include <Arduino.h>
#include  "fastio.h"

#define F_CPU 16000000UL

// pins for TX driver
#define PING0   PB1
#define PING1   PB2

#define LED     DIO13

#ifndef MASK
  #define MASK(m) (1UL << m)
#endif

#define DEBUG 0
#define INTERVAL 100
#define diff(a,b) (((a) >= (b))?((a)-(b)):((b)-(a)))

inline bool ge(uint32_t a, uint32_t b) {
  return ((a - b) & 0x80000000UL) == 0;
}

inline bool lt(uint32_t a, uint32_t b) {
  return ((a - b) & 0x80000000UL) != 0;
}

volatile uint32_t milliseconds = 0;

uint16_t starttime = 0;
volatile uint16_t envelopetime = 0;
volatile uint16_t phasetime = 0;

#define PULSECOUNT_X2 16
volatile uint8_t edges = 0;

void pins_init(void) {
  WRITE(PING0, 0);
  SET_OUTPUT(PING0);

  WRITE(PING1, 0);
  SET_OUTPUT(PING1);

  WRITE(LED, 0);
  SET_OUTPUT(LED);

}

void timer_init(void) {
  // init timers
  GTCCR = MASK(TSM) | MASK(PSRSYNC); // pause clocks

  PRR &= ~MASK(PRTIM1) & ~MASK(PRTIM0) & ~MASK(PRADC); // enable timers 0 and 1 and ADC

  // use timer1 for output waveform generation and analog comparator timing
  TCCR1A = 0;                       // normal mode, no match behaviour
  TCCR1B = MASK(CS10);              // maximum speed (no prescale)

  // use timer0 for our millisecond clock
  TCCR0A = MASK(WGM01);             // CTC mode
  TCCR0B = MASK(CS00) | MASK(CS01); // prescaler=64, ie clock is 250kHz
  OCR0A  = 250;                     // interrupt at 1kHz, ie every 1ms
  TIMSK0 = MASK(OCIE0A);            // interrupt on compare

  // set up analog comparator
  ADCSRA = (0 << ADEN);
  ADCSRB = (1 << ACME);
  ADMUX = 0;
  ACSR |= 0x03;

  GTCCR = 0; // re-enable clocks
}

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

void loop() {
  timer_init();
  sei();
  Serial.println("Start");

  uint32_t pingtime = INTERVAL;

  for (;;) {
    if (ge(milliseconds, pingtime) && (edges == 0)) {
      // note when we should ping next
      pingtime += INTERVAL;

      // start in a millisecond from now to avoid race conditions
      starttime = TCNT1 + (F_CPU / 1000);
      OCR1A = OCR1B = starttime;

      // reset edge counter
      edges = PULSECOUNT_X2;

      // set A and clear B on match
      TCCR1A = MASK(COM1A0) | MASK(COM1A1) | MASK(COM1B1);

      // disable interrupt on comparator
      TIMSK1 &= ~MASK(ICIE1);

      // clear flag in case it triggered during startup
      TIFR1 = MASK(OCF1A);

      // enable interrupt
      TIMSK1 |= MASK(OCIE1A);
    }
    if (phasetime != 0) {
      uint16_t eoff = envelopetime - starttime; // time when Rx signal became loud enough to consider, ie start of envelope
      uint16_t poff = phasetime - starttime;    // time of first zero crossing after envelope, use for calculating phase offset

      //printf_P(PSTR("envelope +%u (%uus) phase +%u (%uus)\n"), eoff, eoff >> 4, poff, poff >> 4);

     Serial.println(eoff);
     //Serial.println(poff);

      // zero so we only print once, process data before this
      phasetime = 0;
    }
  }
}

ISR(TIMER1_COMPA_vect) {
  if (edges == PULSECOUNT_X2) {
    TCCR1B |= MASK(ICES1);   // listen for rising edge
    TIFR1 = MASK(ICF1);      // clear flags in case it triggered during startup
    TIMSK1 |= MASK(ICIE1);   // interrupt on comparator

    TCCR1A = MASK(COM1A0) | MASK(COM1B0); // toggle on match
    //Serial.println("PULSE");
    WRITE(LED, 1);
  }
  else if (edges == 1) {
    TCCR1A = MASK(COM1A1) | MASK(COM1B1); // clear both on match
  }
  else if (edges == 0) {
    //putc('>');

    TIMSK1 &= ~MASK(OCIE1A);   // disable interrupt

    return;
  }
  edges--;
  OCR1A = OCR1B += F_CPU / 80000; // set next timeout
}

ISR (ANALOG_COMP_vect)
  {
  phasetime = ICR1;
  if((ACSR & B00100000)){
    envelopetime = ICR1;      // store timestamp
    WRITE(LED, 0);
    TIMSK1 &= ~MASK(ICIE1);   // disable interrupt on comparator
  }
}

ISR(TIMER0_COMPA_vect) {
  milliseconds++;
}

What's the purpose of ge() and lt()? Why not >= and <? 2. There is a lot going on in this code. Could you reduce this to a minimal example that shows the problem you are facing and nothing more? 3. You don't explain enough how it is supposed to operate. Must we read the full tutorial in order to understand it? 4. Expressions such as ACSR & B00100000 are very hard to decipher. ACSR & MASK(ACO) would be more readable. 5. You may want to use the avr-libc macros such as _BV() (equivalent to your MASK()) and bit_is_set().

ISR(ANALOG_COMP_vect) will never fire if you don't enable the interrupt (bit ACIE in ACSR).

Everything Edgar Bonet said. If I were working on this I'd probably remove MASK for the same reason I wouldn't use _BV. Unless you're making extraordinary use of these, they exist mostly so other people reading the code can have a "WTF?.... oh is that all?" moment. It's difficult to tell if the same thing is happening with ge() and lt().

You have not enabled the comparator interrupt.
Just need to change the line where you set ACSR.
//Comparator interrupt on rising output edge.
ACSR |= (1 << ACIS0) | (1 << ACIS1);

//Enable comparator interrupt
ACSR |= (1 << ACIE)

Can also be achieved with.
ACSR = 0x0B

If you want to change what triggers an interrupt.
Bits 0 and 1 control how an interrupt is fired (Toggle, falling or rising).
//Toggle (Default, only required if another interrupt mode is already selected)
ACSR &= ~(0b11)

//Falling
ACSR &= ~(1 << ACIS0); //Only required if ACIS0 is set
ACSR |= (1 << ACIS1);

//Rising
ACSR |= (1 << ACIS0) | (1 << ACIS1);
//Or
ACSR | = 0x03;

You will also need to enable global interrupts. (Which you have done)
Which can be done by calling...
interrupts(); //Arduino only
sei();        //AVR and Arduino

I see you are calling "sei" in the loop, it only needs to be called once (unless you have disabled them with "cli()," and I believe its not even required at all with Arduino as I think interrupts are already enabled.
The datasheet is your friend. Tutorials are a great way to learn, but if you really want to increase your skill set you should try to break free from tutorials as much as possible by reading the datasheet, and experimenting on your own.
The comparator starts on page 202, and would be a great place to start as its an easy peripheral to get going.


text:
Send large file over BLE with ESP32 Wrover B
I have been able to get a large file to be sent in packages over BLE to a characteristic on my ESP32-Wrover-B module (yay!). However, these files can be large (+300kb) so I need to repackage them after all the file data has been sent (in chunks), to then be stored/written in LittleFS.
I have PSRAM with my module that will allow me to store in a larger space directly, however, from the tutorials I have read, you cannot create a global char* variable for PSRAM.
What would be my best approach here? My basic logic here is to repackage all the chunks that are received via BLE into a char* (or string). Once all data received,  save it as a file in LittleFS.

Use a buffer array to receive the chunk then write to the file once the chunk is received completely.
This is what I utilized for transferring the OTA update file (~1.2MB) over BLE ESP32_BLE_OTA_Arduino


text:
Arduino IDE equivalent to DataView?
I am working on a project with Bluetooth commands between various devices. I would like to try and convert a string to a DataView Object on Arduino, so I can send it over BLE, much like this function written in Javascript:
function str2DV(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  var DV = new DataView(buf);
  return DV;
}

Is this possible with Arduino? I have yet to find a solution....

Have you seen this library? https://github.com/bakercp/BufferUtils

There is no use for a DataView in the Arduino environment. In the
JavaScript language, a string and an array of bytes are two very
different things. That's why you need something like this str2DV()
function to convert between them. In C++, they are one and the same
thing: no need to convert. Sometimes the type uint8_t (also named
byte) is used in preference of char for storing binary data, but you
can just typecast between these types. The typecast typically compiles
to zero machine instructions, as the underlying data representation is
the same.
For example:
extern some_lib_function(const uint8_t *buffer, int buffer_length);

const char *my_message = "Hello, World!\n";
some_lib_function((uint8_t *) my_message, strlen(my_message));

If your string is in the form of a String object, rather than a plain
C-string, then use the c_str() method to get the plain string back:
String my_message = "Hello, World!\n";
some_lib_function((uint8_t *) my_message.c_str(), my_message.length());


text:
arduino robot wont move
I wanted to build an object avoider robot and I am a beginner so I copied a video from youtube and did exactly the same thing and used the same code but when I upload the code the robot won't move at all and it makes a weird sound. i cant I identify if this is a coding problem or hardware problem please tell me what is wrong and what I should do. previously I had made the same robot it moved but the coding was wrong and while adjusting it the minus and plus met at the positive terminal and smoke came I quickly turned it off and this resulted in my batteries getting wasted. do you think that this might be the reason might have added some things extra but they are not connected to the motor driver or Arduino here is the pics of my robot
https://drive.google.com/drive/folders/1t9eYnCt_v4w-IAjYex5wKEFwKv91hnAr?usp=sharing
.here is my code
//ARDUINO OBSTACLE AVOIDING CAR Video - https://youtu.be/h-B42_HXL00//
// Before uploading the code you have to install the necessary library//
//AFMotor Library https://learn.adafruit.com/adafruit-motor-shield/library-install //
//NewPing Library https://github.com/eliteio/Arduino_New_Ping.git //
//Servo Library https://github.com/arduino-libraries/Servo.git //

#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 100
#define MAX_SPEED 150 // sets speed of DC  motors
#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
AF_DCMotor motor3(3, MOTOR34_64KHZ);
AF_DCMotor motor4(4, MOTOR34_64KHZ);
Servo myservo;

boolean goesForward=false;
int distance = 100;
int speedSet = 0;

void setup() {

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL = 0;
 delay(40);

 if(distance<=25)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(200);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }

  else

  {
    turnLeft();
    moveStop();
  }
 }

 else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
}

int lookLeft()
{
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
}

int readPing() {
  delay(100);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
  }

void moveForward() {

 if(!goesForward)
  {
    goesForward=true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
   for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
   {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
   }
  }
}

void moveBackward() {
    goesForward=false;
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
  }
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  }```

forget about obstacle avoidance ... write a simple sketch to move motors forward for 1 second, stop for 1 second, then repeat

I recognize that robot chassis - its the one I started with as well!  I second the commenter's recommendation.  Don't worry about anything beyond getting the motors to move.  In fact, I would recommend you disconnect all but one motor, and replace the wheel from that motor with a piece of tape (so you can see if it is rotating).  That way the robot will be supported by the three non-moving wheels and you can see motor rotation without having the robot run away.

You might also want to consider a different power source, other than the 9V batteries you show in your pics.  These batteries are very poor motor sources as they have relatively low capacity.  If you have a DC power supply, use it instead.  If not, be prepared to change out batteries often.  See my blog site (fpaynter.com) for some additional information on 2 and 4-wheel robots.

Please don't link to Google Drive. Those pictures will disappear, and then people won't understand your question (and perhaps the answer) in the future. You can edit your post and upload the relevant pictures through the editor. Keep the amount of pics minimal though.


text:
Using several Arduinos simultaneously
I'm working on a project where I need to control the light of 5 buttons as well as listen when each button is switched on/off by the user. I would furthermore like to provide feedback on an OLED display. It looks like I'm running out of pins. This https://arduino.stackexchange.com/a/22689/69029 provides several options for that. I would specifically like to explore the option to have several arduinos connected to each other in a master/slave configuration. Where can I learn more about my option to build stuff using several Arduinos connected to each other? I can also forsee scenarios where I could use 3.3V devices as well as 5V devices.

you can find projects on the internet .... this may be useful ... https://www.pjon.org/SoftwareBitBang.php

Thx @jsotola. Those resources make for an interesting read

Among all the options mentioned, using a master/slave should be the last resort, especially when you are new to embedded programming or Arduino, it is not only more complicate but also more expensive to implement.
One potential solution that could free up the precious digital i/o pins that were used by the 5 buttons is using analog input to detect the status of the buttons.

simulate this circuit – Schematic created using CircuitLab
When sw1 is pressed, the voltage at the A0 will be around 0.83v, and when sw5 is pressed, the voltage at the A0 will be 2.5v. You can write a simple switch...case to determine which switch has been pressed.
The only problem of this circuit is that it can't handle more than one button been pressed simultaneously, but that could be solved by double the value of each resistor like 10k, 20k, 30k...
This will free-up 5 digital pins that can be used for control (such as servo, relay, etc.).

Interesting solution @hcheung. At least I'm going to experiment with it just to explore how it it works

Re “When sw5 is pressed, the voltage at the A0 will be around 0.83v, and when sw1 is pressed, the voltage at the A0 will be 2.5v.”: I think you got the switch labels backwards.

@EdgarBonet, oh, yes, you are right. Thanks for pointing out. I have made the correction.

Instead of trying to use multiple Arduino boards, which would be hard, I'd suggest using a bigger Arduino. The mega 2560, for example, has tons of GPIO lines.

I've since learned about the 74HC595. That seems like a handy solution to free up some pins. I gues in combination with the mega 2560 you would have plenty of pins.

Sure, you can use a shift register to set multiple output pins using a single serial line. A shift register wouldn't let you increase the number of input pins however. There are also CMOS multiplexer chips you could use to share a single pin to take multiple digital inputs (or outputs, since CMOS MUX chips allow bidirectional data flow)

I haven't seen this being done much. But that's probably because it isn't the best option in almost all cases.
Having multiple pieces of code, for different boards, that you have to work together. Constantly having to upload to different boards. This sound like a nightmare.
The only use-case I could see is to have each Arduino have a single function that shouldn't change (much) over time, and having it act like just any another sensor IC, or led driver IC.
The best example of this would be some of the SparkFun Qwiic Twist, Quad Relay, and Button board. For these they use an Arduino compatible ATTiny84 IC with custom firmware to expose it's functionality over I2C.
But most of their Qwiic boards use custom ICs, since they are either cheaper, or less work to get working.

I'm currently learning so my experiments are fairly modest right now. However,  I'd like to build my own RC boat with a lot of sensors supporting it and also many servor to make navigable. Since that would be a huge project considering my current experience with the Arduino platform I can already sense that a single microcontroller would not be enough. Perhaps I'm trying to approach this idea from the wrong angle?

I don't feel that's the best solution. I'd probably look into an IC that does the Servo pulse generation for you. That would give you a few extra free pins, and reduce the CPU load on the Arduino.

@Johan-Sundström: About that boat: if you use sensors that have I2C you can use many with just two wires. You can also replace a display and physical buttons with a web interface on your telephone if you use an Arduino with a WiFi module on it. I've done that with a Nano 33 IoT with the WiFi in AP mode and it works.

Hmm interesting, it seems that I have underestimated the power of I2C Thanks for that recommendation @ocrdu


text:
Can SoftwareSerial be used in an ESP01
I am using ESP01 as a microcontroller that retrieves information from Firebase and sends them over serial to an Arduino Uno for other uses. I am not using NODEMcu since it has few analog pins and ESP01 is the only option available for me at this time.
Can the GPIO 0 and GPIO 2 pins available in the ESP01 be used as a serial communication pins when defined with SoftwareSerial library?
I want to keep the serial from the existing TX and RX for debugging and testing.

EspSoftwareSerial

Check your other post I answered it there. The ESP01 has 2 serial channels.

I am also interested in your reply.  Please give a reference to your other post.


text:
How to determine what resistor value to use for LED strip
I'm trying to use an ESP8266 powered by my computer through USB cable to control a WS2812B LED strip. I've read online that you're supposed to put a resistor before the data channel to help prevent noise but I'm struggling to figure out what the resistor value should be.
I've figured out so far that the LED strip will use a MAXIMUM of 25.8W and that the Vin pin that is powering the LED strip is outputting 5V. I also plan on putting a 470uF capacitor across power and ground.

If a chicken-and-a-half lays an egg-and-a-half in a day-and-a-half, how long does it take a grasshopper with one wooden leg to kick all the seeds out of a dill pickle?

I don't know if it does, I was just trying to provide as much information as possible.

@drunkenspider you really need to ask a question ... it is not clear to everyone what the implied question actually is

It seems like people generally just use a resistor around 300 - 500 ohms so I'll just use a 500 ohm resistor. Answer found on another thread. And here as well.

From your second link: NeoPixels (WS2812B) powered by 5v require a 5V data signal. If using a 3.3V microcontroller you must use a logic level shifter such as a 74AHCT125 or 74HCT245. (If you are powering your NeoPixels with 3.7v like from a LiPoly, a 3.3v data signal is OK)

The majority of the time adding a resistor to the data line is completely pointless.  It only has an effect if the Arduino and the first WS2812B chip are connected over a long cable. By "long" I'm talking meters, not centimeters. The length of the strip of LEDs is irrelevant as each LED generates a fresh signal to send to the next LED. It's only the length of cable between the Arduino and the LED strip that matters.
If that is long you can get "ringing" and reflections of the signal through poorly matched impedances. The resistor is there to absorb some of those reflections and reduce the ringing by increasing the impedance of the Arduino's output.
What is a good value? Well, that's hard to say, since it's dependent on the length and type of cable in use. Too low a value and it will do nothing. Too high a value and it will "round off" your signal too much and you'll lose data. A typically chosen value that fits many situations is 220Ω.
But of course for short connections it's irrelevant and you shouldn't add a resistor.

Would a meter be considered too short to put a resistor before the data line?

Depends on the wire.

Strips of LEDs like WS2812Bs need a high current 5V supply, with NO current limiting resistor.
You'll need a very high current regulated 5V supply, and would probably be better off using a separate 5V supply for the Arduino and the LED strip so you don't get large voltage fluctuations in the power to the Arduino as the LEDs turn on and off. If you do you a single power supply for both, you should use a power supply with extra capacity. I'd suggest at least a 30W supply. And yeah, you should probably have a filter capacitor on the 5V rail right at the Arduino.
Edit:
Were you asking about a resistor on the power line, or one on the data pin?

the OP is talking about the data pin, not the power supply pin

How do you know that? The OPs question asks "...what resistor value to use for LED strip" and then all the details provided are about power. Re-reading the question, I still think they are asking about a current limiting resistor. ("Bare" LEDs do need current limiting resistors, so somebody might think that a digital LED strip needs one too.) I'm not familiar with WS2812B LED strips and had to google them. Do they use I2C or some other serial interface? I take it the serial line needs a pull-up resistor?

I've read online that you're supposed to put a resistor before the data channel to help prevent noise but I'm struggling to figure out what the resistor value should be.

Sorry. To clarify, yes I was asking about the resistor for the data channel and not a current limiting resistor.


text:
How to capture the compilaton output to a text file in Windows?
I am trying to capture the verbose output of the compilation to get it into a text file. I am using the IDE 1.8.12 running on Windows 10. I have tried looking for a right mouse button context menu, CTRL-C doesn't work, and finally in desperation, the CMD.exe trick of hitting the Enter key after selecting text.
I also went to the build folder in appdata/local/temp/arduino_build_nnnnn but there's nothing like that there.
There is a topic already about this but it refers to the Linux IDE which can be launched from the command line. It turns out that it's somewhat the same on Windows.

in console window Ctrl+A to select all and Ctrl+C to copy should work. selecting with mouse works too

Yes, of course. In the DOS box, but not the IDE. Thanks.

in the IDE, in the console pane

Whaaat? It works now. Why not before? Anyway, I'm letting the post stand because it's can still be useful to separate the stdout and stderr.

The post Capturing avrdude command in IDE gave me the clue. Under Windows the file
C:\Program Files (x86)\Arduino\arduino_debug.exe
can have its output redirected to files same as a shell command.
In the CMD.exe DOS box, I executed:
C:\Program Files (x86)\Arduino>arduino_debug.exe >\temp\logfile.txt 2>\temp\errfile.txt
and the regular log stuff went to logfile and the errors and warnings went to errfile.
There's enough material in those two files to hurt yourself.


text:
How do I recover a beetle where I loaded a program that was too large and overwrote the bootloader?
I'm doing on-target unit testing for an industrialized application and my test code is too large to fit everything on the board at the same time. I'm using the Sloeber toolset to develop, and I put something on the board that was over 28K, and the programming failed. Now the beetle does not show up as a serial port, and not even when pushing the reset pins, which I've had to do a number of times in the past.
If I overwrote the bootloader, which seems likely, is there a way to recover it? Do I need to reprogram the bootloader on a Beetle board? I haven't found any way to do that with a Beetle...
Thanks!

the upload didn't overwrite the bootloader. see my answer

Yeah, I tried the double reset--that didn't work either. The behavior that happened is that Sloeber failed when it was writing the image and the blue light stayed on. When I reset it, no port came up. When i hit the reset a hundred times, the LED never pulsed and no com port ever showed up in my device manager. I'm pretty sure this is a Sloeber problem with the gcc tools that the Arduino program probably safeguards against.

not hundred times. only but exactly twice to activate the bootloader.

on ATmega32u4 it is not possible to overwrite the bootloader with serial upload

I don't know the Sloeber toolset, but it seems very unlikely, that it really has overwritten the bootloader. When programming via USB, it is actually the bootloader, which writes the program into the flash memory. So that would mean, that the bootloader had overwritten itself, only because a too large program. Not sure, if this is even possible.
Anyway, you can utilize an ICSP/ISP programmer (or another Arduino, if you don't have one) to burn the bootloader onto the chip again. Google for Arduino ISP to get instructions for it, there are plenty of tutorials.
You need to connect the correct pins on the Beetle with the ISP programmer. According to this site, you should find the ICSP pads at the back of the board (the group of 6 pins in 2 rows). Through these pins you can burn the bootloader.
If that doesn't work either, the problem lies somewhere else. As I already stated, overwriting the bootloader because a program is too big for the MCU should not happen and it is highly unlikely, that this is really your problem. You might have damaged something on your board, though we cannot tell that from the description. So you could just try to burn the bootloader and see what happens.

OP doesn't have to flash the bootloader. the bootloader is protected with fuses

Yes, the icsp pads are there, which is how you perform the reset. It seems like the Sloeber toolset, which uses the atmel gcc/g++ tools, somehow causes a problem with the beetle if the file is too large. It definitely fails to write and tell you so, but either way, the beetle becomes completely unresponsive.

on ATmega32u4 it is not possible to overwrite the bootloader with serial uploaad

Use double reset to activate the bootloader. The LED will pulse while it waits for upload.
The board doesn't show up on USB because USB is handled by the sketch on MCU with native USB. If the sketch doesn't run it doesn't handle the USB.
The bootloader is protected by fuses.
(This happen to me with Sloeber a few days ago.)

Yeah, I tried the double reset--that didn't work either. The behavior that happened is that Sloeber failed when it was writing the image and the blue light stayed on. When I reset it, no port came up. When i hit the reset a hundred times, the LED never pulsed and no com port ever showed up in my device manager.


text:
Az Delivery ESP32 DevKitC V2 PIN names/number
i wonder where to find out the PIN names for the Az Delivery ESP32 DevKitC V2.
There is a pin out graphic, but it does not say how the Pin addresses are:
https://cdn.shopify.com/s/files/1/1509/1638/files/ESP_-_32_NodeMCU_Developmentboard_Pinout_Diagram.jpg?4479111012146266271
I thought maybe it's just the number of the GPIOs but that's wrong. In the first example script only PIN 1 was named as the address for the board intern LED.

There are no pin names on the ESP32. GIOx is pin x.

Well there is a GIPIO 0 and 0 is already the board LED, so that's not possible

It's perfectly possible. Connections aren't exclusive. You can have a connection going to both a pin at the edge of the board and to an LED. Look at pin 13 of the Arduino - that goes to a pin on the edge of the board and to the on-board LED.

ESP32 boards don't use "names" for their IO pins. There is a direct 1:1 mapping between the internal "GPIO" number and the pin number.
To do something with pin G21 on the board you use pin number 21. To do something with pin G14 you use pin number 14.
By all accounts that board differs from other ESP32 devkits in that the LED is on GPIO1 rather than the normal GPIO0 that all the other boards use. I suspect that this is the source of your confusion.

To finalize the confusion you need to digitalWrite(1,LOW) and not  digitalWrite(1,HIGH) to turn the LED on. Ooof

@Stack one end of the LED is connected to V+ ... pulling the other end low lights it ... it is not so confusing really ... if it continues to give you problems, then define ON and OFF ... in the end, pulling a pin of a device low, to activate it, is very common practice ... just look at solenoid driver circuits

This "active low" driving method stems from the early days of semiconductors when you would have a low impedance LOW and a high impedance HIGH output - for example RTL where a transistor pulls the output down and a resistor pulls it up. Later when CMOS came on the scene you'd have a low resistance N-channel FET for the LOW and a higher resistance P-channel FET for the HIGH allowing more current to be sunk than could be sourced by an output. These days it's not a problem as the P- and N-channel FETs are much more closely matched - but the hangover is still there in many designers' minds.


text:
board stops working when writing serial
i just started using Arduino IDE for my XMC1100XMC2Go. Information about the microcontroller can be found here: https://github.com/Infineon/XMC-for-Arduino/wiki/XMC-2Go
I now started with my first codes and want to print things on the serial monitor with this code:
*/
/* For on board LEDs */
#include <LED.h>

/* Create an LED object */
LED Led;

//#define SERIAL_DEBUG 1

int p_LED = 5;
int p_Button = 4;
int i_stateButton = 0;

void setup()
{
  Led.Add(LED1);            // Configure the LEDs
  Led.Add(LED2);
  pinMode(p_LED, OUTPUT);
  pinMode(p_Button, INPUT);

  // Set default state of LEDs
  Led.On(LED2);
  Led.Off(LED1);

  digitalWrite(p_LED, LOW);
  Serial.print("Hello World!");

  Serial.begin(9600);
}

void loop()
{
  Serial.write("Hello World!");
  Serial.println(i_stateButton);
  delay(200);
  Led.Toggle (LED2);
  Led.Toggle(LED1);

  i_stateButton = digitalRead(p_Button);
  //digitalToggle(p_LED);
  digitalWrite(p_LED, i_stateButton);
}

I checked under tools that SerialOutput is set to PC (https://github.com/Infineon/XMC-for-Arduino/blob/master/variants/XMC1100/config/XMC1100_XMC2GO/pins_arduino.h#L54)
There are two Ports, COM1 and COM3. I can send new sketches to the microcontroller using COM3. I checked my Serial Monitor and it is set to COM3, too.
Baudrate is for both the same (code and monitor)
Now that i send the above sketch to the microcontroller it stops working. one LED is on and the other is off. But they do no longer change the state. Nothing appears on the monitor.
When i remove the both lines Serial.write("Hello World!");  Serial.println(i_stateButton); and send the sketch, the LEDs start flashing again.
I'm pretty sure it's a kind of configuration problem, but i cannot find out what it is. Does anyone have an idea?

Maybe you should avoid printing to Serial before calling Serial.begin().

serial.begin() is in the setup part. Or does this belong to the loop?

What do you have right before Serial.begin()?

Ouch. Thank you

There was a Serial.print("Hello World!"); before Serial.begin(9600); Thanks @Edgar Bonet

on a normal Arduino it doesn't stop the sketch

@EdgarBonet This sounds like an answer. Perhaps turn your comment into an answer. Stack Exchange will think that this Arduino section has very few answers if you guys keep answering in comments.

In the setup(), you have:
Serial.print("Hello World!");
Serial.begin(9600);

One should avoid printing to the serial port before enabling it with
Serial.begin().


text:
Signal names HiFi
i'm not sure if this is the right address, but maybe you know about it.
I currently integrate bluetooth to my car's radio using a esp32. First i wanted to insert the signal at the d2b cd player, but since i don't know the right communication between the occ and the processor i don't see a solution here (and i don't have a cd player to get the reference signals)
But there is a CC player that i can use. There is a detailed documentation about the radio, too:
https://www.motor-talk.de/forum/aktion/Attachment.html?attachmentId=753560
Page 12 (or 16 of the pdf)
TRK1R, TRK1L, TRK2R TRK2L and PBREF are used for the signals.
CCINS will be GND if there is no CC in the slot and otherwise 5V
CCEJT will be 5V if you press the eject button, otherwise it's GND
But this is not enough, there is a tape monitoring circuit that needs to be tricked.
Can you see from the documentation how to do so?
CCPSE is connected from the processor to the tapedeck, but i don't know what it is good for
CCMOD is connected to the latch 2, UG5V and the tapedeck. It's on 5V while the radio is on.
RELL_R and RELL_F are 5V while idle and otherwise they change their value continuously.
CCMET is connected to the CPU, CC Amplifier and the Tapedeck. It's on 5V if the tapedeck is removed and otherwise always 0V. So i short circuit it with GND to simulate there is a tape deck.
CCLDG is connected to the shiftregister and the tapedeck and i have no idea what it is good for. it's always 0V
CCMOT and LED look like they are both the same from the datasheet. They are 0 in general but when the CC is running they turn 5V.
Maybe some can point me out how to trick the tape monitor
Thanks

They make adapters that fit into the Tape socket (if you have one) and will play when you select the audio tape. That is no longer an option on the newer car radios. Mine has an audio input I can use, and it is a 2009 Flex.

do you have a link?

No  but you can google it


text:
Crash when disabling bluedroid
i have an ESP32 and i want to use deepsleep when it's not used. Before sending it to sleep i clean up everything, so disconnect, deinitialize and disable everything i build before. But i get a crash when i try to disable bluedroid. Does anyone have an idea why this happens?
void bt_deinit() {

    Serial.println("Deinit AVRC");
    if (esp_avrc_ct_deinit() != ESP_OK)
        Serial.write("Failed to deinit avrc");

    Serial.println("Deinit A2DP");
    if (esp_a2d_source_deinit() != ESP_OK)
        Serial.println("Failed to deinit a2dp");

    Serial.println("disable bluedroid");
    if (esp_bluedroid_disable() != ESP_OK)
        Serial.println("Failed to disable bluedroid");

    Serial.println("Deinit bluedroid");
    if (esp_bluedroid_deinit() != ESP_OK)
        Serial.println("Failed to deinit bluedroid");

    Serial.println("Stop BT");
    if (btStop() == false)
        Serial.println("Failed to stop bt");
}

output:
Port closed
Uploading to I/O board
Opening port
Port open
Hello there!
Bluetooth init success
good night
Deinit AVRC
Deinit A2DP
disable bluedroid
/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/queue.c:719 (xQueueGenericSend)- assert failed!
abort() was called at PC 0x4008de6f on core 0

Backtrace: 0x40091918:0x3ffce3b0 0x40091b49:0x3ffce3d0 0x4008de6f:0x3ffce3f0 0x4013bfb6:0x3ffce430 0x4013c5f6:0x3ffce460 0x400fdbe2:0x3ffce480 0x400fdc35:0x3ffce4a0 0x400fe12e:0x3ffce4c0 0x400f6bd9:0x3ffce4e0 0x4008e559:0x3ffce510

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8
Hello there!
Bluetooth init success

it works fine if i just do not deinitialize everything and send him directly to sleep. But this is not the elegant way.

upvote for well presented question ... sadly I do not have the expertise to help you ..... perhaps something has not finished shutting down .... insert a delay before disabling bluedroid .... maybe it is the order of events ..... maybe stop first, then disable .... possibly the reverse order of the startup sequence

decoded backtrace in your question is missing, one of the choices to see stack trace is https://github.com/littleyoda/EspStackTraceDecoder
i dont know exactly if this is your case or not, but calling esp_ble_gap_stop_scanning() before esp_bluedroid_deinit() possibly avoids your crash.


text:
Send message to multiple number
sim.println("AT+CMGS=\"+91xxxxxxxxxx\"\r");
I don't want to write this. I want to write mobile number on serial monitor in Arduino and on that number, i want to send message. how can I do?

I changed the qs for you, hope I made the right corrections!

@SomasundharamSampath Where did you get the information for your edit of the question? Have I missed something here?

@Mehul What exactly is your problem with this? Is it about the serial communication? Or is it about putting together the received number for sending to the GSM module? What have you tried so far? Have you looked at some of the many examples and tutorials about serial communication?

I saw this comment/ answer  https://arduino.stackexchange.com/a/78443/11957

Actually, there are different different number which may don't know every time.
Every time i change number and install on board that is not possible. so i want to make code in which write number and send same message on it.


text:
How can TEENSY Microcontrollers read ASCI Variables from X-PLANE 11
TEENSY Boards have in the USB-MODE "FLIGHTSIM" direct access to the variables = DATAREFS
of X-PLANE 11.
You can use FLIGHTSIMINTEGER and FLIGHTSIMFLOAT but not a varible for CHARs like the ID of a waypoint
for example "IBZ" or "EDDF" .
I need to read the CHARs to use them in the Display of my FlightSimPanel.
ANY IDEA ?

it is unclear what you are asking about ... please edit your post and explain what you are asking ... pretend that we cannot read your mind

Please show the code that you're having problems with. Reading data from flight simulators is not something everyone is familiar with.


text:
Clocking issues while programming ATMEGA32U4-AU via USB bootloader
Hi,
I'm designing a custom board with the ATMEGA32U4, with a GPS receiver and LoRa radio and it is powered from a LiPo battery. Since I'll need to make hundreds of this board later on, I'd like to program them over USB. I started out from the Arduino Pro Micro schematic and I use an 8MHz crystal. I'm able to make use of the factory default USB bootloader and upload Arduino sketches using the dfu-programmer in Linux. My first problem was that the blink example didn't really blink at 0.5Hz rate(delay(1000) wasn't 1sec), but much-much slower. No worries, reduce the delay a little bit. However, when I want to communicate with the GPS, the from the transmitted signal, I can see that the baud rate is not correct. I suspect that the clock settings are not correct. I read that these can be changed with the help of fuses, but as far as I know, they cannot be modified using only USB , I need a programmer for that, which I'd like to avoid.
(Correct me if I'm wrong here)
So my question is, how do I set up the MCU correctly, so that it runs from the 8MHz external or 8MHz internal clock using only USB? Is it even possible?

Off topic: You can measure Vbatt by using it as AREF and measure internal bandgap voltage reference (= switch to the correct adc channel and measure it)

BTW, have you selected correct speed for pro micro board? (eg. 3V3/8MHz?). Also by default there is CKDIV8 fuse set, so if you didn't changed anytning in fuses, it'll be even slower than just half speed

Thanks for the tip regarding the battery voltage!
Yes, I switched to 3v3/8MHz.
In the meantime, I found this: https://www.avrfreaks.net/forum/clock-select-register-instead-fuse-bits
I was able to switch the clock source back to 8MHz and the UART baudrate seems okay now.

Yes, it's possible to change prescaler, but you have to configure it in each program you create.

I'd still try to set the fuses. Using software to select the correct clock source and prescaler seems to me like a workaround, instead of proper solution. Though I can't give a good reason why. It just feels wrong.

The problem is that I do not have a programmer, so I could only set fuses through USB.
Right now I'm able to send and receive data via Serial, but not SoftwareSerial. On SW Serial I can send, but not receive.

I made some more progress. Turns out, I was using SoftwareSerial with the dedicated UART pins, which is wrong. So basically all my problems have been solved. Thank you for your contributions!


text:
Pro micro Wire.endTransmission() does not return
I have an Arduino Pro Micro(blue version) and I'm having trouble using the I2C. To test it, I use the code below and the result is an infinite square wave on SCL and SDA lines and I only get the number 1 on the terminal output. I have pullup resistors on both wires, 2k each.
Since the board uses an ATMEGA32U4, I tried the same code on a bare MCU and the code works as expected. The difference between the two is the bootloader type. The bare PCB is flashed over USB, using the factory bootloader(ATMEGA32U4-AU, QFP44).
By debugging the code, I found out that endTransmission does not return.
Does anyone have an idea, why the I2C is not working as expected on the Pro Micro module?
Thanks!
#include <Wire.h>

void setup() {
  Serial.begin (115200);
  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }
  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  Wire.begin();
}  // end of setup

void loop() {
  byte count = 0;
  for (byte i = 1; i < 120; i++)
  {
    Serial.println(i);
    Wire.beginTransmission (i);
    Wire.endTransmission ();
    delay(10);
  }
}

What do you mean by "infinite square wave"? Does that mean, that both SDA and SCL get continuously pulsed forever, when Wire.endTransmission() blocks?

Yes, and it does not stop. The waveform looks good, signal level is VCC and GND for 1 and 0.

Mhh, strange. Does this also happen, when nothing is connected to the bus?

Yes, it's the same. With and without the pullup resistor.

To be clear, SCL and SDA have nothing at all attached to them but pullup resistors and perhaps your scope?

Yes, that's right.

And nothing is printing on the Serial Monitor? then I guess your microcontroller is broken. Your sketch seems legit to me. And the lines should never just pulse continuously. A common problem is the bus getting stuck, because one line gets stuck at low, but I haven't seen your problem ever. Can you tell us the frequency of the pulses? Just to check

Same thoughts as chrisl.  I suppose I should go a step further and ask: what happens if you have nothing connected to the Pro Micro at all except the USB cable?  No external pullup resistors; the internals that are enabled for Wire.begin() are sufficient for this test.  No scope.  Just the USB cable.  Pro Micro not even attached to a (solderless) breadboard, just the board sitting on something non-conductive.

I just bought a new pro micro and the I2C is working. Maybe the other one is really broken. Strange...
Thanks for the help!

I dunno how useful it would be to anyone, but that seems to technically be the answer for your question.  So you could post it as an answer to your own question.  If you've accepted that it's the answer you can accept it as well, although as I understand it, you'll only be able to do that in a couple of days.

Seems like the module has a defect, since the same code on another board produces the expected output on the I2C lines


text:
Leds become dimmer after they reach a certain brightness, why?
Even if I don't use buttons and I do an automated thing that makes the led brighter(Even the non-rgb one)after sometime it resets itself to a dimmer light, why?*
int Gled = 5;
int Bled = 6;
int Rv;
int Gv;
int Bv;

int b1 = 7;
int b2 = 8;
void setup()
{

  pinMode(b1, INPUT_PULLUP);
  pinMode(b2, INPUT_PULLUP);
  Rv = 0;
  Gv = 0;
  Bv = 0;
  analogWrite(Rled, Rv);
  analogWrite(Gled, Gv);
  analogWrite(Bled, Bv);

}

void loop()
{

  if(digitalRead(b1) == LOW)
  {
    Rv += 10;
    analogWrite(Rled, Rv);
  }
  if(digitalRead(b2) == LOW)
  {
    Gv += 10;
    analogWrite(Gled, Gv);
  }

}

The loop is quite fast, can you imagine how many times it goes into if section, when you press the button? Also you are providing int value into analogWrite, but usual values are 0-255...

The described behavior stems from 2 important facts:

The loop() function will run very fast (microsecond range), while the button presses of a normal human will be rather slow (in the tens or even hundreds of milliseconds). That means, that with only one button press you will enter the corresponding if statement many times, everytime adding 10 to the value. You don't have control how many times exactly the if statement will be entered, so the value, that comes out after your button press is somewhat randomly growing.

While the analogWrite() function takes an int as the value parameter (16 bits on AVR), internally it assigns that value to the corresponding Timer register, which is only 8 bits big. So it can only hold values between 0 and 255 anyway. If you provide a bigger number as a parameter, the higher part will just be cut off. For example: Providing 257 will result in a value of 1 (= 257 % 256 = 257 % 2^8 --> 257 modulo 256). The higher values get wrapped around back into the range of 0 to 255.

So together you have a value, that is growing very fast and somewhat randomly, while the analogWrite() function will only take the lower 8 bit of that value. The outcome is a rather erratic, somewhat random LED brightness, which is difficult to control.
What to do now? That depends on what behavior you want to have exactly:

One button click (press + release) should increase the value of the corresponding LED by 10:

Currently you are checking, if the button is being pressed. Instead you have to look for the transition between not-pressed and pressed, so a HIGH to LOW transition. You can do that by saving the last read value in a variable at the end of the button reading part and comparing this previous value to the newly read value at the start of it. Though that still leaves you with the bounce problem. There are many measurements, that you can do, to debounce the button (you can google that easily), though here I just will suggest using the Bounce2 library. You can find it here on github or in the library manager (I think). It makes it much easier to read buttons reliably. It has good examples to learn how to use it.

The value should rise, while the button is pressed, and stopping to rise, when it is released again:

Here you should limit the rate in which the if statement is entered. You can do this by limiting the execution rate of the loop() function with a simple call to delay(), though that isn't a good coding practice and can limit you, when adding more functions to your code (because it's blocking the execution of other code). Instead you can use the non-blocking coding style involving the millis() function, that you can see in the BlinkWithoutDelay example. You use a timestamp variable to save the last time, when the if statement was executed. The if statement should then check (additionally to the button state), if enough time has passed, meaning if the difference between millis() and the timestamp is high enough. You can change the interval for this comparison to change the rate, in which the value is increased.


text:
Reading Serial String Gives Null Lines with JSSC
I need to send serial data to my Arduino UNO from within a java application. I am using JSSC for this.
I wanted to verify that my data actually arrives correctly to the arduino before going to the next step of my application. For this I tried to just return the string I am sending, however when I send "test", this is what is returned:
t
null
est

I am wondering if this is a problem on the Java side with sending/reading the string, or that it's a problem with sending/reading on the arduino, and how I could possibly fix this.
This is my java code to read the data:
try {
    port.addEventListener(event -> {
        try {
            System.out.println(port.readString());
        } catch (SerialPortException e) {
            e.printStackTrace();
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}

This is my java code to send the data:
try {
    port.writeString("test");
} catch (SerialPortException e) {
    e.printStackTrace();
}

And this is the code on my arduino:
void loop() {
  while (Serial.available() > 0) {
    Serial.print(Serial.readString());
  }
}

I hope someone can help :)

you have to say "over" when using walkie-talkies. or serial. Otherwise, a response of "Yeah, that's a bad idea" could be interpreted as just "yeah" if it cuts out.

This is a common misconception about how serial communication works.
You're "sending" the "string" test. Except you're not.
What you're actually doing is you're placing the string test into the send buffer. Another routine then takes each byte from that send buffer in turn and sends it out through serial.
The Arduino then receives that byte and places it into its internal receive buffer.
You then get around to reading from the serial and you just get whatever is in the receive buffer at that moment in time - however many bytes that happens to be.
Then you "send" those bytes back - except again, you don't. You place those bytes into the internal transmit buffer in the Arduino and another routine takes each byte in turn from that transmit buffer and sends it out through the serial.
Again the Java program gets around to reading from the serial, and all it gets is what happens to be in its receive buffer at the time, however many bytes that may be at the time.
There is no such thing as "a string" or "a line" in serial. All there is is bytes - one after another.
It is up to you to receive those bytes and reconstitute them back into the form you want as each byte happens to arrive.
As it stands you have no way of knowing what that form should be, since you just send four bytes with no meaning attached to them.
It's common to add a "terminator" to a string when sending so that the receiver knows when all the bytes have arrived.  For us humans the simplest to use is a "line feed" or \n character.
Your receiving routine would then receive each character in turn appending it to the target String up until it receives the terminating character, at which point it knows that it has finished receiving this chunk of data and can act on it.
I have a popular blog post all about reading serial on the Arduino here, and the same principle can be applied to any other language.


text:
3v3 ESP one way communication with 5 V Arduino?
Perhaps I'm not fully understanding a difference between logic level and the function of the TX and RX pins? I'm just wondering if an ESP can send, one-way, data to an Arduino. (I found that two-way communication would need a logic level converter.)
ESP32 Datasheet

https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf#page=42

Arduino datasheets do not appear to specify logic level tolerances. It appears from this Arduino Forum post, it would work.
Is it universally assumed that 3v3 will be in tolerance for logic high?

https://learn.sparkfun.com/tutorials/logic-levels/all

Yes, it will work, but only just. It's borderline.
The ESP32 gives out at most 3.3V as a HIGH signal. The Arduino accepts "above 0.6Vcc" as a HIGH signal. That means that it needs to see a voltage that is at least 60% of the voltage on the Vcc pin (5V pin) of the Arduino.
If the Arduino has exactly 5V then 60% of that is 3V. Since 3.3V is higher than 3V it sees it has a HIGH.
However if the Arduino is being powered by a slightly higher voltage than 5V (some USB ports can give out 5.2V and it's still in spec) and if the ESP32 is being powered slightly below 3.3V, then that 0.3v margin of error gets narrower and narrower. Eventually it disappears and HIGH can no longer be detected.
For example if the Arduino has 5.2V and the ESP32 has 3.1V then the Arduino expects at least 3.12V and the ESP32 gives out no more than 3.1V.
So in  most circumstances it does work, but there are factors that can stop it from working. Those factors can be mitigated by using logic level translation.

The factor 0.6 itself is chosen to be on the safe side, too. Nobody assures that 2.6V is never interpreted as HIGH. Your final statement is very correct, though.

@DataFiddler It's not safe to second-guess the datasheet. The values given are the guaranteed values. Sure, it may be lower, but it's not safe to assume that. Different chips from different batches could be different, but they are all guaranteed to be no more than 0.6Vcc. 90% of the time it's fine though and for Arduino usage fine is usually good enough. Personally I only usually work with 3.3V microcontrollers anyway (who really uses 5V these days?!)

Additionally, partly contradicting my yesterday's opinion, the 0.6 is part of a well defined hysteresis functionality: An input pin is either LOW or HIGH:  It switches LOW->HIGH @0.6 Vcc, and switches back HIGH->LOW @ 0.3 Vcc This is a feature one can rely on as well.


text:
Can I power the arduino UNO through the 5V pin while I use USB cable to collect data?
I understand that if the Arduino is powered by Jack or Vin when the USB cable is connected, the internal circuitry would inderdict the USB powering.
But what if I power the arduino througn 5V pin while the USB cable is connected? How does the internal circuit do the choice?
Did I just connect the 5V power supply directly with USB port of the laptop (since the 5V rail directly connects 5V pin and USB port)? Is this allowable? Is this dangerous?
Thank you!

If u use the VIN pin of arduino, You shouldn't have a problem , as arduino selects it required voltage automatically, it's voltage regulator senses the voltage from USB and External source, if the power of the external source is higher than usb, the the power is bypassed to the External power. But don't know if you are using the 5 volt pin to turn on the arduino.
Well everything I said is applicable for UNO boards don't know other ones.
Thanks...