text:
AA alkaline batteries on firebeetle?
I would like to power a dfrobot firebeetle 2 using 3 alkaline batteries. I tried connecting the battery pack to the GND and VCC, but the board does not seem to react. What pins should i connect the leads to?
The firebeetle 2 info page:
https://www.dfrobot.com/product-2195.html

The following is based purely on the small amount of information in your question. You haven't described your code or your setup, which would allow this answer to be more specific.
According to the FireBeetle ESP32 schematics here, you should be able to connect an external power supply between VCC(+) and GND(-).

The voltage regulator on the FireBeetle ESP32 is a low-dropout RT9080 regulator, which, according to its datasheet has a maximum voltage drop of about 0.5 V when outputting the 3.3 V needed by your board and a maximum input voltage of 5.5 V.
That means the voltage supplied at VCC should be between 3.8 V and 5.5 V, and the ~4.5 V supplied by your 3 x AA batteries (assuming they're connected in series), falls nicely into this range.
The fact that your board does not seem to run your code might be caused by a number of things.

Does your program expect a Serial port connection which, of course, is not available when it's not connected to a PC by USB?
The power demanded by your board might be too high for the batteries. Are there other things connected to the board that that could cause that?

If you have a multimeter, you should be able to measure a stable 3.3 V on the 3.3 V pin of the FireBeetle.

Before trying to measure the 3.3v coming out of the regulator, it might be good to measure the voltage at the output terminals of your battery pack as well...

Sorry, this appears to be a PEBCAK issue, the boards actually runs fine, i just came to the wrong conclusion because the board did not behave like i expected.


text:
MQTT on ESP8266 cannot connect if using Last Will service
Issue (short) description
An ESP8266 using PubSubClient fails to establish connection to MQTT broker (mosquitto) if requesting Last Will Testament (LWT) on connection, though it is able to connect without LWT.
The aim and detailed description of the issue
The aim is actually to make the ESP to receive messages that been published while it was offline. Following the generic recipe for MQTT, I tried to set cleanSession =false which in PubSubClient also requires passing LWT arguments. Using code shown bellow (with the arguments passed to the PubSubClient.connect() method)  results in that the same ESP board connecting to the same MQTT server could not connect anymore (the code below is stripped to MQTT relevant parts):
WiFiClient wclient;
PubSubClient mqtt_client(wclient);

String DEVICE_NAME = "esp8266_test";
const int DEVICE_ID = 1;
String MQTT_CLIENT_ID = DEVICE_NAME + (String)(DEVICE_ID);

const char * mqtt_client_id = MQTT_CLIENT_ID.c_str();
const char* willTopic = (DEVICE_NAME + "/will").c_str();
uint8_t willQos = 0;
bool willRetain = false;
const char* willMessage = "will";
bool cleanSession = false;
int mqtt_keep_alive = 60;

void connect_mqtt(const char *mqtt_user, const char *mqtt_pass, const int timeout){
  int i = 0;
  logger.info("Connecting to MQTT broker.");
  while ((!mqtt_client.connected()) && (i < timeout) && (WiFi.status() == WL_CONNECTED)) {
    logger.info("Attempt " + (String)(++i));
    mqtt_client.setKeepAlive(mqtt_keep_alive);
    mqtt_client.connect(
      mqtt_client_id,
      mqtt_user,
      mqtt_pass,
      willTopic,
      willQos,
      willRetain,
      willMessage,
      cleanSession);
  }

  if (mqtt_client.connected()) {
        logger.info("MQTT broker connected.");
    } else {
        logger.error("Connection timeout. Failed with state: " + (String)(mqtt_client.state()));
        }
}

void start_mqtt(IPAddress mqtt_server, const int mqtt_port, const char *mqtt_user, const char *mqtt_pass){

  mqtt_client.setServer(mqtt_server, mqtt_port);
  // mqtt_client.setCallback(callback);
  connect_mqtt(mqtt_user, mqtt_pass, timeout);
}

In the code above start_mqtt() function is called from setup(), the output it will result in looks as follows:
INFO: Connecting to WIFI SSID: xxxxxxx
INFO: WiFi Connection established
IP address:     192.168.178.55
INFO: Connecting to MQTT broker.
INFO: Attempt 1
INFO: Attempt 2
INFO: Attempt 3
INFO: Attempt 4
INFO: Attempt 5
INFO: Attempt 6
ERROR: Connection timeout. Failed with state: -4

If instead one calls connect() method with only mqtt_client_id, mqtt_user, mqtt_pass arguments, the connection can be established without any issues, e.g.:
mqtt_client.connect(mqtt_client_id, mqtt_user, mqtt_pass)

Attempts to troubleshoot:

I've tried using connect() without cleanSession argument, the behaviour is the same: cannot connect with state -4. So I've concluded that the issue is in LWT service, which I actually don't need but it seems one has to use it with cleanSession
According to PubSubClient documentation the -4 state is "the server didn't respond within the keepalive time", so I've started looking on the server side (see next items)
The server log looks like this:

2023-04-01 18:37:09 1680367029: Client <unknown> disconnected due to protocol error.
2023-04-01 18:38:36 1680367116: New connection from 172.17.0.1:54174 on port 1883.

If connecting without LWT (using only mqtt_client_id, mqtt_user, mqtt_pass arguments) connection can be established and the log looks like this:

2023-04-01 18:38:36 1680367116: New client connected from 172.17.0.1:54174 as esp8266_test1 (p2, c1, k60, u'xxxx').

Mosquitto documentation doesn't say anything about enabling LWT, which suggests that it should work with the mostly default config which is used here.

I tried two different Mosquitto servers configured for user/password authentication, results are the same.

Questions
Based on behaviour above, my conclusion is that using PubSubClient with LWT results in a sort of change of a protocol which is not recognised/supported by Mosquitto. Therefore, the questions are:

Is there is a way to fix the issue, or to further troubleshoot it?
Is there is a way to use cleanSession = false without enabling LWT?
Is there other ways of receiving "offline" MQTT messages on ESP8266 (without using cleanSession = false)?

Hi @Vadim - could you please edit the question to include the values you're using for willTopic, willQos, willRetain and willMessage?

@romkey sure, done

source: Stack Exchange

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

sort: votes


text:
Choosing a good RF library for transmissions
I am trying to send information from an Attiny85 to an ESP32, through RF.
I am using the most popular 433mhz transmitter on the market.
I know various existing libraries to send and receive data between chip on rf hardware ;
Here are the following ones I tried :

Manchester
RC Switch
Radio Head

All of those seems to be working well enough, but aren't very constant in the range. I'm having a lot of troubles receiving correct data a few meters away indoors.
As I am not an expert in radio waves, I would like to have an explanation on what radio protocol can be trusted for simple applications, and what not to use.
I know that a simple encoding like HIGH level for digital 1, and low level for digital 0 can be compromised, and that the manchester encoding is a better idea, but I would like to have a better understanding on how it works.

what leads you to believe that the library is the cause of the problem?

I don't believe any library might be the problem, but that differents protocol will offer different speed. For example I would like to send the received data to another chip, and the receiving speed matters. But I don't really know what protocols they use, and what is the difference between them. In my application the code seems to slow down reception, as I'm not sure how it works, I think the way reception is handled might change things, but I'm not sure... I also didn't really know how to put the question...

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


text:
Program to Multiply Numbers Won't Actually Multiply Them
I am trying to write a program which takes in a number of pairs to be multiplied, then prints out the result of each multiplication. Instead of doing this, the program just prints out the number of multiplications and the numbers, but it never does the multiplications or add the newline characters (despite me explicitly using println). In the example below I specify 2 number pairs to multiply, and then enter 3,4,7,8 (entering a NL character after each number, but spaces and commas cause the same problem).

I thought my approach would work, but I believe that there is something I am doing with the serial input that is causing the code not work (although there could be some other issue). I also wonder if maybe it's because I'm running this in Tinkercad and not the real Arduino IDE. Any help would be greatly appreciated.
void loop()
 {
  int numOfMults = 0;                             // number of pairs to multiply
  float *numArray;                                // pointer to beginning of array memory block
  numArray = (float *)malloc(sizeof(float)*50);   // dynamically allocate an array that can hold up to 50 floats

  numOfMults = Serial.parseInt(); // take in the number of multiplications from user

  Serial.println(numOfMults);

  // take in the specified amount of numbers (2 times the num of multiplications) in format: 1,2,3...
  // then convert that into an array of floats, where every 2 indices
  // is a pair of numbers to multiply
  for (int i = 0; i < (2*numOfMults) ;i++)
    {
      numArray[i] = Serial.parseFloat();
    }
      multNums(numOfMults,numArray);  // call function to get the product of all the numbers

      delay(5000);                    // wait 5 seconds before starting the loop again
 }

void multNums(int numofNums,float nums[])
{
  float *productArray;                                 // pointer to beginning of the product array memory block
  productArray = (float *)malloc(sizeof(float)*25);    // dynamically allocate an array that can hold up to 25 floats (for the products)

  // multiply all the number pairs in the array, store the product in another
  for(int i=0;i<(2*numofNums);i+2)
  {
      productArray[i/2] = nums[i]*nums[i+1];         // multiply current number pair, store in the product array one index at a time
  }
  // print the products
  for(int i=0; i < sizeof(productArray) ;i++)
  {
    Serial.println(productArray[i]);
  }
}

for(int i=0; i < sizeof(productArray) ;i++) are you expecting that the sizeof()  a float pointer to be equivalent to the number of elements in the referenced array ?

@6v6gt that was a good catch, but even after changing it to explicitly be the number of products my output is still not right. I also am printing out the values I'm reading into the float array and they all appear to be there before I call the multiply numbers function.

Ok I figured it out.
In the for loop I had to use i +=2, and not i+2.
What a dumb mistake..

There are quite a few issues in this code:

In C++, you are supposed to do dynamic allocation with new rather
than malloc().

If you allocate dynamic memory in a loop and forget to free it (with
free()/delete), you will quite quickly run out of memory.

Actually, you do not even need to do any dynamic allocation at all:
automatic allocation is the safest way to handle these arrays.

Since you know the exact size you need, allocate that rather than a
default size.

multNums receives as a parameter the number of multiplications, not
the length of the array.

i+2 does not change the value of i. You meant i+=2.

sizeof(productArray) does not give the length of the array, but its
size in bytes. Besides, your last loop is supposed to iterate only
through the initialized part of the array.

If you fix those issues, the program should work as expected.

fixing all those things made the program work, the biggest problem was using i+2 instead of +=. And I will go back and do dynamic memory allocation in a better way or just get rid of it. I actually thought arduino was C (not c++), which is why i used malloc. New is much better.


text:
How to read Arduino voltage
I am trying to do voltage measurement using Arduino. I am using a voltage divider circuit to reduce the voltage to less than 5V. I measured the voltage on the 5V pin of Arduino and found out that its 4.279 V (I am powering through USB).  So, I am doing following calculations for voltage measurement:
int data1   = analogRead(A0);
float data2 = data1 * (4.279/1023.0);
float volts = data2 * (10 + 2.2)/2.2;  //R1=10k , R2=2.2k
Serial.println(volts);

if(volts > 12.00)
{
  digitalWrite(6,HIGH);
}
if(volts < 12.00)
{
  digitalWrite(6,LOW);
}

So I am getting exact values of voltage. Now I have put a condition like if volt is greater than 12V, turn on an output, else turn off the output. For output, I have a transistor and mosfet connected. As soon as the voltage increases above 12V, output get on but the problem is that when the output is on, Arduino displays wrong values. Like if the voltage is 12.3, it shows 13.6.
I looked it into more and found out that the voltage at 5V pin of Arduino (4.279) gets reduced to 3.865 and due to which calculation goes wrong and it displays wrong values of voltage.
Is there anything which I am doing wrong? Is there any function or keyword in Arduino libraries which can tell us the voltage or is there any way through which we can measure it? I tried putting the 5V pin to analog pins to read it and convert it into volts but again for this we need a reference voltage.
I hope I have explained the question clearly.
Schematic

A0 is the analog pin and PIN6 is digital output of arduino

Full schematic and code please.

@Majenko I have updated the code and schematic.

I thought so. You have no base resistor on your BJT. That's causing a brownout.

@Majenko base resistor. I didn't get you. Do you mean resistor on base. Can you please describe it

A small resistor between pin 6 and the base of the resistor to limit the current that can flow through the base. Since you are only switching a MOSFET with it the actual value doesn't matter that much - maybe around 1KΩ should be OK.

The brownout that @Majenko referred to happens because the voltage across the base and emitter of your 2N3904 will limit at about 0.6V.  So your pin 6, when driven high would be pulling the VCC supply down.

@Majenko you should convert your comment into an answer

@Majenko Thanks. I used 1.8k resistance and the voltage is seems to be ok now.

@Majenko I am facing problem regarding the reference voltage for reading the voltage. As I already mentioned, I am using 4.279 but now that voltage has increased to 4.8. Why.? why this voltage is not constant.

USB has quite a wide range that the 5V can be. You can't rely on it being 5V. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/

It would appear that the wrong A/D reading is due to the reduced +5V output. The A/D reference is powered by the input to the computer chip. The big question is what is causing the voltage drop. Are you powering something else
from the USB supply when the FET is turned on? Bottom line is that you cannot
expect the A/D to read the same voltage when the voltage input to the computer chip is changed.

I have connected my arduino using USB and when nothing is connected and blinky program is running, it shows 4.279v instead of 5v. In my project I am planning to use only ATMEGA328P instead of the complete arduino so in that case I will giving it the full 5v power, so may be at that time it will show 5v.

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


text:
How to download a large text file using HTTPS on an ESP32?
Trying to create an ESP32 access to a public Spple calendar, but after connecting to the server and saving to SPIFFS it fails at the same point each time. I end up with a file of around 220 kB, when the total file should be 800 kB.
If it's helpful:
Headers from URL show:
Tranfer-Encoding: Chunked
Connection: keep-alive
Arduino IDE:
Sketch uses 891474 bytes (68%) of program storage space. Maximum is 1310720 bytes.
Global variables use 39640 bytes (12%) of dynamic memory, leaving 288040 bytes for local variables. Maximum is 327680 bytes.

Any help would be greatly appreciated, I've spent way more hours than I'd like to admit even getting here.
#include <WiFi.h>
#include <HTTPClient.h>
#include "FS.h"
#include "SPIFFS.h"

/* You only need to format SPIFFS the first time you run a
   test or else use the SPIFFS plugin to create a partition
   https://github.com/me-no-dev/arduino-esp32fs-plugin */
#define FORMAT_SPIFFS_IF_FAILED true

const char* ssid = "House N";     // your network SSID (name of wifi network)
const char* password = "Sebastian1963George"; // your network password
int LED_inbuilt = 2;

void setup() {
  Serial.end();
  delay(100);
  Serial.begin(115200);
  pinMode(LED_inbuilt, OUTPUT);
  delay(1000);
  Serial.print("WIFI status = ");
  Serial.println(WiFi.getMode());
  WiFi.disconnect(true);

  delay(1000);
  WiFi.mode(WIFI_STA);
  delay(1000);
  Serial.print("WIFI status = ");
  Serial.println(WiFi.getMode());

  digitalWrite(LED_inbuilt, HIGH);
  delay(500);
  digitalWrite(LED_inbuilt, LOW);
  delay(500);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

  if (!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)) {
    Serial.println("SPIFFS Mount Failed");
    return;
  }
}

const char* root_ca= \
"-----BEGIN CERTIFICATE-----\n" \
"MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL\n" \
"MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE\n" \
"BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT\n" \
"IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw\n" \
"MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy\n" \
"ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N\n" \
"T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv\n" \
"biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR\n" \
"FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J\n" \
"cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW\n" \
"BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/\n" \
"BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm\n" \
"fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv\n" \
"GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=\n" \
"-----END CERTIFICATE-----\n";

void loop() {
  getCalendar();

  delay(1000);
  readFile(SPIFFS, "/calendar.txt");
}

void getCalendar() {
 File file = SPIFFS.open("/calendar.txt", "a");

 if (!file) {
   Serial.println("- failed to open file for writing");
   return;
 }

 if ((WiFi.status() == WL_CONNECTED)) { // Check the current connection status
   HTTPClient http;
   http.begin("https://p64-caldav.icloud.com/published/2/MTExOTIzNTUyNDExMTkyM_t4rBfkJzy02anGOy6aHJIsgECeJGkvldH8kJEjylMtRScq7BUY4vOst7NZU_0bLtKJ0JICjDL0ECuF9L_p8lQ", root_ca); //Specify the URL and certificate
    int httpCode = http.GET(); // Make the request

    if (httpCode == HTTP_CODE_OK) { // Check for the returning code
      http.writeToStream(&file);
    }

    file.close();
    Serial.println("you have finished downloading");
    http.end(); // Free the resources
  }

  delay(1000);
}

void readFile(fs::FS &fs, const char * path) {
  Serial.printf("Reading file: %s\r\n", path);

  File file = fs.open(path);
  if (!file || file.isDirectory()) {
    Serial.println("- failed to open file for reading");
    return;
  }

  Serial.println("- read from file:");

  while (file.available()) {
    Serial.write(file.read());
  }
}

void deleteFile(fs::FS &fs, const char * path) {
  Serial.printf("Deleting file: %s\r\n", path);
  if (fs.remove(path)) {
    Serial.println("- file deleted");
  } else {
    Serial.println("- delete failed");
  }
}

this sounds like it's begging to be pre-processed on a different computer/VPS, summarized, then provided to the ESP32 in no-mess form.

Haha, potentially, but I was hoping to get a standalone device that did everything, and it seems like ESP32 should be able to do it, plus I don't have much experience in either, and learning a whole new area of computer programming to get it working seems overwhelming!

You are basically running out of memory, use streamHttpClient.

Just wanted to say thanks to dandavis and hcheung! Got that bit working! The project as a whole has defeated me, but you both were really helpful, thanks!


text:
Why does only one of my motor work in l293d motor shield?
I am building a remote control car using an Arduino and a l293d motor shield but only 1 port in the shield works among the other 4, why is that?
Below is my code:
char Incoming_Value = 0;
#include<AFMotor.h>
AF_DCMotor motor1(3);
AF_DCMotor motor2(2);

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  motor1.setSpeed(255);
  motor2.setSpeed(255);
}

void loop() {
  if (Serial.available() > 0) {
    Incoming_Value = Serial.read();

    if (Incoming_Value == '1')
      digitalWrite(13,HIGH);

    motor1.run(BACKWARD);
    motor2.run(BACKWARD);

    if (Incoming_Value == '0')
      motor1.run(FORWARD);

    motor2.run(FORWARD);
    digitalWrite(13,LOW);

    if (Incoming_Value == '2') // LEFT
      motor1.run(BACKWARD);

    motor2.run(FORWARD);

    if (Incoming_Value == '3') // RIGHT
      motor1.run(BACKWARD);

    motor2.run(FORWARD);

    if (Incoming_Value == '5')
      motor1.run(RELEASE);

    motor2.run(RELEASE);
  }
}

You only use 2 Motors/Ports in your Program. 2. No matter what happend in the if statement your last statement is to switch off motor2. And this for each run of the loop method. So, what you observe and what you've programmed match well. I assume that there are missing braces? ;-)


text:
Arduino Nano 33 IoT LSM6DS3: get gyro angle in degrees
I have an Arduino Nano 33 IoT and I want to get the angle of it using the built-in gyro but I can't seem to find any example code that does this.
The default gyro and accelerometer example code doesn't help. Is it even possible to do this?

a gyro detects the rate of angular change, not an absolute angle ... an accelerometer can measure an angle with respect to gravity

I tried looking for both but there is no code that does it. Could you help me find it?

All I can find is changing numbers but no angles.

You wil have to calculate the angles. Some trigonometry is required, and for the gyroscopes, also some integration. You can read about it here, and in many other places.
You will get the best results if you combine the data from the gyroscopes and the accelerometers using a complementary filter, a Kalman filter, or an other algorithm. These are also easily googled.
There is some example code for the LSM6DS3 IMU on the Nano 33 IoT here on Github.

This is the best solution. This filter is a lot faster than the MadgwickAHRS! Amazing!

You are supposed to use a filter library on top of the output of the gyro as well as the accelerometer data (both is used!) to get angles ... https://www.arduinolibraries.info/libraries/madgwick
Here is a working example that prints the pitch of the sensor from +90 to -90 degrees:
//#include <SPI.h>
//#include <Wire.h>
#include <Arduino_LSM6DS3.h>
#include <MadgwickAHRS.h>
#include <Math.h>

float pitchFilteredOld;
Madgwick filter;
const float sensorRate = 104.00;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  if(!IMU.begin())  {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }
  filter.begin(sensorRate);
  Serial.println("Setup complete!");
}
void loop() {
  float xAcc, yAcc, zAcc;
  float xGyro, yGyro, zGyro;
  float roll, pitch, heading;
  if(IMU.accelerationAvailable() && IMU.gyroscopeAvailable()){
    IMU.readAcceleration(xAcc, yAcc, zAcc);
    IMU.readGyroscope(xGyro, yGyro, zGyro);
    filter.updateIMU(xGyro, yGyro, zGyro, xAcc, yAcc, zAcc);
    pitch = filter.getPitch();
    float pitchFiltered = 0.1 * pitch + 0.9 * pitchFilteredOld; // low pass filter
    Serial.println("pitch: " + String(pitchFiltered));
    pitchFilteredOld = pitchFiltered;
  }
}


text:
Read Comma Separated String
I have a string that looks like this "10.00,20.00,-50.00," in which these are angle values and they have 2 decimals and can be negative. I want to separate them into 3 separate floats. Here is my current code in which I use sscanf. All I get is 0.00 and have no idea why. Any help is truly appreciated.
String recvString = "10.00,20.00,-50.00,";
float r,p,y;

void setup() {
  Serial.begin(9600);
  Serial.println(r);
  int result = sscanf(recvString.c_str(), "%f,%f,%f,", &r, &p ,&y);
  Serial.println(r);
}

void loop() {}

It's not a full duplicate but it will help you understanding the problem and reason better: https://stackoverflow.com/questions/27651012/arduino-sprintf-float-not-formatting. You can use function http://www.cplusplus.com/reference/cstdlib/strtod/`

a comma is not whitespace ...https://stackoverflow.com/questions/15091284/read-comma-separated-input-with-scanf#15091406

Use the indexOf function to find index then use the subString to get values like this:
String recvString = "10.00,20.00,50.00";
float r, p, y;

void setup() {
  Serial.begin(9600);
  //Serial.println(r);
  //recvString.toCharArray(s, recvString.length() + 1);
  //int result = sscanf(recvString.c_str(), "%f,%f,%f,", &r, &p ,&y);
  int i1 = recvString.indexOf(',');
  int i2 = recvString.indexOf(',', i1+1);
  Serial.println(i1);
  Serial.println(i2);

  String firstValue = recvString.substring(0, i1);
  String secondValue = recvString.substring(i1 + 1, i2);
  String thirdValue = recvString.substring(i2 + 1);

  Serial.println(firstValue);
  Serial.println(secondValue);
  Serial.println(thirdValue);

}

void loop() {
  // put your main code here, to run repeatedly:

}

definitely not this way

But it works so why not?

see the other answer

The AVR implementation of sscanf() does not support parsing floating point numbers, thus you only get zeros out of it. You can't use the %f specifier with it. You need to convert these numbers by yourself with functions like atof() or similar.
Splitting a string into parts can be done many ways. You could use sscanf() to split up the string parts and then use something like atof() to actually convert to float. Or you use strtok() for splitting (see my answer to this question). Or you use one of the many other options, that you get, when googling for something like "Arduino split string" or "Arduino split c string".
Note: Using the String class in Arduino is easy for beginners, but not a good practice (dynamic allocation, heap fragmentation). Look at Majenkos blog for more information about that. Since you already used a function for C-strings, I would suggest moving completely to C-strings (which are basically only an array of char).


text:
Code Optimization: Interrupt when a value reaches 0
I have a working program and I wish to improve its efficiency as much as possible.
It will blink slow, then faster and faster  until it restarts.
It works, but my main concern is, currently, I am using a if statement in the void loop(), and I am certain that, using an interrupt when a specific variable has reached 0, would improve efficiency.
byte amp = 0;

void setup() {
  pinMode(13, OUTPUT);
  reset();
}

void loop() {            // The following
  digitalWrite(13,HIGH); // code is for the sake of example
  delay(amp*100);        // Simplified to focus on the loop
  digitalWrite(13, LOW);
  delay(amp*100);
  amp--;
  if (!amp) {reset();}     // <-This right here
}

void reset() {amp = 10;}

My understanding is, the if statement is called every time the loop restarts.

Is it possible to set up an interrupt for when a certain variable reaches 0?
Which option would require less computing power, a continually called if loop, or an interrupt?

For what are you trying to save computing time? The first step would be to ditch all the delay() calls (since with them you have up to 2s, where the Arduino is just twiddling its thumbs) and use millis() like in the BlinkWithoutDelay example for a non-blocking coding style. The if statement only takes so little time, that it doesn't matter for 99,9% of cases. What do you want to do in your code besides the blinking, that you need this optimization?

Thanks for your answer @chrisl, actually this is not my regular code and only for the sake of simplified example.

you can't really use an interrupt to replace an if statement ... the proper way to service an interrupt is to only set a flag in the ISR ... then test the flag in loop(), usually by using an if statement

look at the assembly code created from the sketch if you want to understand advanced things.

@B7th I already thought so, but you still didn't write about what your regular code does besides blinking. I think, that you might look into a totally unnecessary direction for optimizing your code out of missing knowledge. To actually know that, we would need to know, for what you are trying to save "computation power". Only then we can give you an answer, that really gets you further.

You did not specify the kind of Arduino you are using but, based on another recent question of yours, I will assume it is an AVR-based Arduino.
You cannot have an interrupt automatically triggered by a variable reaching zero. What you can do, instead, is trigger an interrupt by software, by toggling a pin that is configured both as an output and as an interrupt source:
const uint8_t int_pin = 2;  // pin used for interrupt

void setup() {
    digitalWrite(int_pin, LOW);
    pinMode(int_pin, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(int_pin, reset, RISING));
}

static inline void trigger_interrupt() {
    digitalWrite(int_pin, HIGH);
    digitalWrite(int_pin, LOW);
}

// Within loop():
if (!amp) trigger_interrupt();

However, if you do that, you will discover that interrupts are slow; awfully slow compared with a simple if test:

digitalWrite() itself is awfully slow. This can be overcome by using direct port access, but that is still two cycles for toggling the pin in each direction.

You will lose an extra cycle in the pin synchronizer.

Once the IRQ is raised, the CPU needs four cycles to prepare itself for servicing it.

The interrupt vector is a jmp instruction, which takes 3 cycles.

The ISR then has to save every single register it is going to use, including the status register. That takes two cycles per register. And there are quite a lot of registers to save...

This ISR, which is provided by the Arduino core, will then look for the interrupt handler you provided with attachInterrupt(). This also involves checking that the pointer to the handler is not zero (the kind of test you seem to be worried about). It then has to call (4 cycles) your handler, which will have to return (4 cycles) to the ISR. You could avoid this indirection by defining the ISR yourself instead of relying on attachInterrupt().

Once the job is done, all the saved registers have to be restored (2 cycles times many register), and the reti instruction (4 cycles) is issued in order to restore control to the interrupted program.

Last but not least, since amp will be modified in interrupt context, you will have to qualify it as volatile. This keyword prevents the compiler from perform optimizations that are unsafe in this situation, and you will loose a lot of time to these missed optimization opportunities.

In contrast, this line:
if (--amp == 0) amp = 10;

would be translated by the compiler into something like this:
   dec  amp     ; --amp, as amp is likely already in a register
   brne 1f      ; if (amp != 0) skip the following
   ldi  amp, 10 ; amp = 10
1:

The whole sequence takes 3 cycles, irrespective of whether the if condition was true or false. That is at least one order of magnitude faster than the interrupt-based solution.

Very complete explanation of how and why. Thank you Edgar this helps make a lot of sense of how the assembly works!

Simple if statements are very fast and won't affect performance much even when used in every looping of the loop.
Using an interrupt to implement something simple like if (!amp) amp = 10; will probably make things slower:

something will have to keep track of the counter to generate an interrupt, and this "something" takes MCU time, unless it is a peripheral;
interrupts have overhead;
on single-thread MCUs, interrupts stop regular code execution until they are done;
amp = 10; will still have to be executed, in the regular code, or, if you must, in the interrupt.

You would gain more by getting rid of the function call to reset(), but the compiler probably does that for you.
Also, I wouldn't know how to replace a regular if with an interrupt, unless the counter is kept by a (timer) peripheral.

Re “amp = 10; will still have to be executed, in the regular code“: Why would you do that in the regular code? This statement would not take longer that setting a boolean.

@Edgar-Bonet: Yes, in this simple example it is just one statement, so it doesn't matter here.. I'm not of the school that says you should always only set a flag in an interrupt and must do everything else in the loop, in case you were worried


text:
Arduino Pro mini does not wake up after a few interrupts from DS3231
I hope someone can help me. I'm building a GSM water level meter that runs on solar power, using an Arduino Pro mini, a DS3231 RTC, a JSN-SR04T - ULTRASONIC SENSOR, and a SIM800L along with a DFrobot DFR0535 solar power manager and 3.7V battery.
My project worked fine before I added the RTC; it connects to the Blynk server, gets the readings from the ultrasonic sensor, and posts them, before going to sleep.
I added the RTC in order to use it to wake up the Arduino using the interrupt signal and save some power during the evenings and no sun.
Even this works, but the interrupts stop after about 30 mins of firing. At the moment its configured to fire every 5 mins. My serial output looks like this:

So at this point the sketch works 100% and does exactly what I need, but unfortunately it stops after a few minutes. Do I need a pull up resistor somewhere maybe?
Any ideas?
Below is my sketch. Any help will be greatly appreciated.
    #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
    #define interruptPin 2 //Pin we are going to use to wake up the Arduino
    #include <DS3232RTC.h>  //RTC Library https://github.com/JChristensen/DS3232RTC
    #include <NewPing.h>
    #define BLYNK_PRINT Serial
    #define TINY_GSM_MODEM_SIM800
    #include <TinyGsmClient.h>
    #include <SoftwareSerial.h>
    #include <BlynkSimpleSIM800.h>
    #define SIM800_TX_PIN 9
    #define SIM800_RX_PIN 8
    #define uS_TO_m_FACTOR 60000000   // Conversion factor for micro seconds to minutes
    char auth[] = "a892d375xxxxxx0d5c086d6b1";
    char apn[]  = "";
    char user[] = "";
    char pass[] = "";
    const int MAX_DISTANCE = 120;                       //max distance to measure
    const int Diameter1 = 110;                                //internal Diameter of tank 1 in cm
    const int Depth1 = 110;                                 //total depth of tank 1 in cm , from sensor to base inside
    const unsigned int Period = 60000;    //period between pings, in milliseconds. i.e  1 munute = 60,000. max 65535. Want longer? use unsigned long
    const int PingPin1 = 6;                          //     GPIO5,  D1
    const int EchoPin1 = 7;                        //     GPIO4,  D2
    const int Area1 = PI * ((Diameter1 / 2) * (Diameter1 / 2));          //area of base of tank 1
    int Litres1, Distance1, WaterDepth1, Decimal, Persentage, battLevel, csq, kill;
    String gsmTime, gsmTime1;
    #include <SoftwareSerial.h>
    SoftwareSerial SerialAT(SIM800_TX_PIN, SIM800_RX_PIN);
    TinyGsm modem(SerialAT);
    //BlynkTimer timer;
    NewPing sonar = NewPing(PingPin1, EchoPin1, MAX_DISTANCE);
    //RTC Module global variables
    const int time_interval = 5; // Sets the wakeup intervall in minutes

    void setup() {
      Serial.begin(115200);//Start Serial
      delay(1000);

      pinMode(LED_BUILTIN,OUTPUT);//We use the led on pin 13 to indecate when Arduino is A sleep
      pinMode(interruptPin,INPUT_PULLUP);//Set pin d2 to input using the buildin pullup resistor
      digitalWrite(LED_BUILTIN,HIGH);//turning LED on

      // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
        RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
        RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
        RTC.alarm(ALARM_1);
        RTC.alarm(ALARM_2);
        RTC.alarmInterrupt(ALARM_1, false);
        RTC.alarmInterrupt(ALARM_2, false);
        RTC.squareWave(SQWAVE_NONE);
         time_t t; //create a temporary time variable so we can set the time and read the time from the RTC
        t=RTC.get();//Gets the current time of the RTC
        RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t)+time_interval, 0, 0);// Setting alarm 1 to go off 5 minutes from now
        // clear the alarm flag
        RTC.alarm(ALARM_1);
        // configure the INT/SQW pin for "interrupt" operation (disable square wave output)
        RTC.squareWave(SQWAVE_NONE);
        // enable interrupt output for Alarm 1
        RTC.alarmInterrupt(ALARM_1, true);
    }

    void loop() {
     delay(5000);//wait 5 seconds before going to sleep. In real senairio keep this as small as posible
     Going_To_Sleep();
    }

    void Going_To_Sleep(){
        sleep_enable();//Enabling sleep mode
        attachInterrupt(0, wakeUp, LOW);//attaching a interrupt to pin d2
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
        digitalWrite(LED_BUILTIN, LOW); //turning LED off
        time_t t;// creates temp time variable
        t=RTC.get(); //gets current time from rtc
        Serial.println("Sleep  Time: "+String(hour(t))+":"+String(minute(t))+":"+String(second(t)));//prints time stamp on serial monitor
        delay(1000); //wait a second to allow the led to be turned off before going to sleep
        sleep_cpu();//activating sleep mode
        Serial.println("just woke up!");//next line of code executed after the interrupt
        myFunction();
        t=RTC.get();
        Serial.println("WakeUp Time: "+String(hour(t))+":"+String(minute(t))+":"+String(second(t)));//Prints time stamp
        //Set New Alarm
        RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t)+time_interval, 0, 0);

      // clear the alarm flag
      RTC.alarm(ALARM_1);
      }

    void wakeUp(){
      Serial.println("Interrrupt Fired");//Print message to serial monitor
       sleep_disable();//Disable sleep mode
      detachInterrupt(0); //Removes the interrupt from pin 2;

    }

    void myFunction() {
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);
      SerialAT.begin(57600);
      delay(1000);// make GPIO8 output low
      Serial.println("Initializing modem...");
      modem.restart();
      Blynk.begin(auth, modem, apn, user, pass);
      delay(1000);
      Distance1 = sonar.ping_cm();                                       //get distance to the top of the water tank 1
      if (Distance1 >= Depth1 || Distance1 == 0 )  Distance1 = Depth1;                   //check it does not go negative
      WaterDepth1 = Depth1 - Distance1;                     //calculate the depth of the water
      Litres1 = ((Depth1 * (PI * (sq(Diameter1 / 2)))) - (Distance1 * (PI * (sq(Diameter1 / 2))))) / 1000;
      Persentage = (Litres1 / 1000.00) * 100;
      battLevel = modem.getBattPercent();
      csq = modem.getSignalQuality();
      Blynk.virtualWrite(V1, WaterDepth1);
      Blynk.virtualWrite(V2, Litres1);
      Blynk.virtualWrite(V3, Litres1 / 10);
      Blynk.virtualWrite(V4, Persentage);
      Blynk.virtualWrite(V5, battLevel);
      Blynk.virtualWrite(V6, csq);
      Serial.println();
      Serial.println();
      Serial.println("Water depth: " + String(WaterDepth1));
      Serial.println("Water distance: " + String(Distance1));
      Serial.println("Litres: " + String(Litres1));
      Serial.println("Percentage: " + String(Persentage));
      Serial.println("Battery: " + String(battLevel));
      Serial.println("Signal Qlty: " + String(csq));
      delay(100);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

Do you have pullup resistors on SCL & SDA?

nope...directly from the RTC into the pro mini...I got a few 2N2222 & MPS2222A's? Or what would you suggest?

don't use String class

4.7K pullups on SCL, SDA are needed for I2C to work. Internal to Atmega328P are insufficient.

I think your code just hangs/crashes after some time. Try commenting out sleep_cpu(); and see if it hangs after half an hour. I don't think this has anything to do with sleeping.

With sleep_cpu(); commented out. The sketch runs in a loop, completely ignoring the sleep time, waking up straight after going to sleep. So far its been running for more than 30mins without freezing.

I have exactly the same issue, after 30 times waking up the code hangs up and the arduino nano is not waking up for the interrupt anymore.
Did you find the issue in the meantime? @Roelof Loots


text:
Pro Micro Double Reset help; Not able to get upload done in 8 seconds
I have timed the double reset as best as possible multiple times but the upload doesn't happen before the board leaves bootloader mode.
this is all I'm given as an error which doesn't appear until after the board leaves bootloader mode  (after the 8 seconds)
The one thing that I haven't been able to find info on is the fact that I do not have a SparkFun version, I have a non branded from ebay if that makes any difference
How can I fix?
Sketch uses 3460 bytes (12%) of program storage space. Maximum is 28672 bytes. Global variables
 use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.

avrdude: ser_open(): can't open device "\\.\COM11": The system cannot find the file specified.

Failed uploading: uploading error: exit status 1

Remove the power to the board
Hold down reset while you power it up.
Release reset when the IDE says that it is uploading.

but there will be no COM port if the 32u4 is in reset state

@Juraj - It will appear once it leaves reset. The IDE keeps checking for the COM port, I believe.

Yeah I know about the bootloader COM port and set that up. I've been able to connect the board during reset. Just not been able to upload some dummy code with the correct processor speed before it disconnects.       I'll try the holding down process tonight


text:
how to config size USB mass storage arduino nano ble 33?
I see that they arduino nano ble 33 support USB 2.0. Is there a way for us to create a USB mass storage of about 200kb for convenient storage of configuration files and history files?
I see example arduino has UsbMassStorage but by default it only creates 1 disk with 512KB capacity. Which 512KB + 200KB bootloader is my chip error.
Is there a way to reconfigure the capacity for UsbMassStorage?
Thank you so much.
    /*
   This example exposes the second half (512KB) of Nano 33 BLE flash
   as a USB disk.
   The user can interact with this disk as a bidirectional communication with the board
   For example, the board could save data in a file to be retrieved later with a drag and drop
*/

#include "PluggableUSBMSD.h"

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

  // write a file with some data
  // a+ means append, so every time the board is rebooted the file will grow by a new line
  FILE *f = fopen("/fs/data.txt", "a+");
  String hello = "Hello from Nano33BLE Filesystem\n";
  fwrite(hello.c_str(), hello.length(), 1, f);
  fclose(f);
}

void loop() {
  delay(1000);
}

which code are you talking about? ... please add the program listing to your question


text:
Problem using CH340 driver for Nano
I am at my wits end and hope somebody here can provide some much-needed guidance.
My platform is an Asus ROG AMD laptop running Windows 11.
I recently decided to try working with Arduinos and purchased a Nano Every direct from Arduino.  I installed the Arduino IDE and when I plugged in the Every it showed up in Device Manager under Ports using the FTDI driver (I suspect that the driver was installed when I installed the IDE).
I had some problems with the Every and decided to try a straight Nano. I purchased one from Micro Center and when I plug it in it also appears in Device Manager under Ports, again using the FTDI driver.  When the Arduino IDE could not communicate with the Nano (I did change board and port) I realized that the unit uses an inexpensive Chinese comm chip was told by Micro Center support that I needed to install the CH340 driver.  As recommended I downloaded the driver installation package from wch-ic.com.  When I ran that installation it reported that the driver was already installed, and I do see two ch341ser.inf_amd64_xxxx entries in Windows\System32\DriverStore\FileRepository.
My problem is that I cannot figure out how to make the Nano use the CH340 driver.  When I try to update the driver in Device Manager it tells me that the current driver is the best one.  When I try to force an update by using "Let me pick from a list", browsing to one of the ch341ser.inf_amd64_xxxx folders in DriverStore\FileRepository and selecting CH341SER.INF I am presented with a set of possible models (CH330, CH340, CH340K, CH341, CH341A).  I was unable to find any guidance on which to select, so I (probably unwisely) experimented.  When I choose CH340 or CH341 the update process begins but my laptop abruptly restarts and afterwards the Device Manager entry in Ports is still using the FTDI driver.
I don't know why the CH340 upodate fails and causes a restart.
I don't know if I should try to delete the FTDI driver (and in fact am uncertain how to go about doing that).
I would greatly appreciate whatever help anyone can provide.
IDE output:
avrdude: Version 6.3-20190619
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "C:\Users\bobwi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 57600

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xbf
avrdude done.  Thank you.
Failed uploading: uploading error: exit status 1

may be just set the Processor option in the Tools menu

OK, tried using Processor ATMega328P (instead of ATMega328P (Old Bootloader)) and upload now works using FTDI driver.

Also had to make sure that Serial Monitor was not open when uploading.


text:
MPU6050 when searching is at address 0x68 but as a result shows only "0"
My circuit uses an Arduino Nano which I communicate via Α4 and A5 via I2C. There are several BMP280, HMC5883 and MPU6050 sensors on the I2C line. While I was dealing with these other two sensors, my MPU6050 stopped working. She started outputting single zeroes regardless of the movements. I found similar problems and it was suggested to conduct a search and if it is searched to try some other code.I tried and nothing helped. They also wrote about power supply problems, but the board I use has resistors between the microcircuit and the SCL/CLK terminals. I also heard about FIFO, but did not understand anything.
I don't know what I did wrong because before that it was working fine. I will add the code I used.
/*
The contents of this code and instructions are the intellectual property of Carbon Aeronautics.
The text and figures in this code and instructions are licensed under a Creative Commons Attribution - Noncommercial - ShareAlike 4.0 International Public Licence.
This license lets you remix, adapt, and build upon your work non-commercially, as long as you credit Carbon Aeronautics
(but not in any way that suggests that we endorse you or your use of the work) and license your new creations under the identical terms.
This code and instruction is provided "As Is” without any further warranty. Neither Carbon Aeronautics or the author has any liability to any person or entity
with respect to any loss or damage caused or declared to be caused directly or indirectly by the instructions contained in this code or by
the software and hardware described in it. As Carbon Aeronautics has no control over the use, setup, assembly, modification or misuse of the hardware,
software and information described in this manual, no liability shall be assumed nor accepted for any resulting damage or injury.
By the act of copying, use, setup or assembly, the user accepts all resulting liability.

1.0  5 October 2022 -  initial release
*/

    #include <Wire.h>
    float RateRoll, RatePitch, RateYaw;
    void gyro_signals(void) {
      Wire.beginTransmission(0x68);
      Wire.write(0x1A);
      Wire.write(0x05);
      Wire.endTransmission();
      Wire.beginTransmission(0x68);
      Wire.write(0x1B);
      Wire.write(0x8);
      Wire.endTransmission();
      Wire.beginTransmission(0x68);
      Wire.write(0x43);
      Wire.endTransmission();
      Wire.requestFrom(0x68,6);
      int16_t GyroX=Wire.read()<<8 | Wire.read();
      int16_t GyroY=Wire.read()<<8 | Wire.read();
      int16_t GyroZ=Wire.read()<<8 | Wire.read();
      RateRoll=(float)GyroX/65.5;
      RatePitch=(float)GyroY/65.5;
      RateYaw=(float)GyroZ/65.5;
    }
    void setup() {
      Serial.begin(57600);
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);
      Wire.setClock(400000);
      Wire.begin();
      delay(250);
      Wire.beginTransmission(0x68);
      Wire.write(0x6B);
      Wire.write(0x00);
      Wire.endTransmission();
    }
    void loop() {
      gyro_signals();
      Serial.print("Roll rate [°/s]= ");
      Serial.print(RateRoll);
      Serial.print(" Pitch Rate [°/s]= ");
      Serial.print(RatePitch);
      Serial.print(" Yaw Rate [°/s]= ");
      Serial.println(RateYaw);
      delay(50);
    }

here is what it outputs now ("0"), although before it was perfectly responsive. At least it accurately displayed the + or - sign along with some values
The type of MPU6050 I used:

Can you restore the circuit and code to the previous state so the MPU6050 once again  works? Have you considered I2C address conflicts between the various modules? Each module may have its own I2C pullup resistors and too many of these in parallel may be a problem.

please do not post pictures of text ... post the text instead

I am responding to 6v6gt's comment.
My circuit didn't change, I had all three sensors connected from the start. However, I just disconnected the BMP280 and HMC5883 from the I2C, leaving only the MPU6050 connected. It will continue to show only zeros.

It sounds like something is broken. Assuming the MPU6050 accelerometer / gyroscope worked with the Arduino. Then, after adding the BMP208 pressure sensor and the HMC5883 magnetometer the MPU6050 stopped working. Finally, after physically removing the BMP208 and HMC5883 from the I2C bus AND REVERTING TO THE VERSION OF CODE which worked with the MPU6050 the MPU6050 continued to not work. Please read that carefully and confirm you did physically remove the 2 new sensors from the I2C but and you did revert back to the code which worked with the MPU6050.

I am responding to st2000's comment.
Just picked up and connected the MPU6050 to another arduino Nano that has nothing else connected except this MPU6050. It shows zeros again.
But I want to note that if you choose the wrong address (that is, not 0x68 or simply do not connect), then -0.02 is displayed instead of zero.

And so I dealt with these sensors separately from each other, that is, they remained connected, but in the code I communicated only with it. And in the case of the MPU6050, I used the above code.
I also remembered that I had a problem with the BMP280, it worked at first and then something froze and I could not connect back to it for several minutes. But now only MPU6050 is not working.


text:
ESP32 - TWAI Timing Problems (cant receive messages below 5ms period)
I am currently trying to read an existing canbus (Car) with my ESP32 Rev3.
I got it to work fine with an external MCP2515 shield using a default library.
But when i connect an transceiver and trying to use the internal TWAI controller built into ESP32 i am starting to get troubles. When receiving messages with at least >5ms period, it works fine but as soon the period gets under 5ms, its rapidly filling up the RX buffer and once its full, its starting to drop packets. When i set the RX buffer to a higher value, this only extend the time until the first error appears. It seems like the transceiver works fine but the twai_receive() function can't catch up. Does anyone have an idea, what i can do here.
For receiving, i am using the following, wich works kind of fine for ESP32 Wroom Rev3.
https://github.com/halfroad/TWAIMessager
Before, i was directly accessing the API by using this documentation, but this has the same behaviour:
https://docs.espressif.com/projects/esp-idf/en/release-v4.4/esp32/api-reference/peripherals/twai.html#examples
If the internal limitation is >5ms per message period, the CAN controller is pretty useless as in most modern cars canbus you have periods as low as 0.4ms per message.
To verify, that i'm not missing anything i setup two ESP32 and sending from A to B.
The code/setup of the receiving part is like this:
#include "driver/twai.h"
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_33, GPIO_NUM_32, TWAI_MODE_LISTEN_ONLY);
    twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
    twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();

    //Install TWAI driver
    if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
        Serial.println("Driver installed\n");
    } else {
        Serial.println("Failed to install driver\n");
        return;
    }

    //Start TWAI driver
    if (twai_start() == ESP_OK) {
       Serial.println("Driver started\n");
    } else {
        Serial.println("Failed to start driver\n");
        return;
    }

The processing of ingoing messages in the loop() function is something like this:
twai_message_t message;

void loop() {
    while (twai_receive(&message, 0) == ESP_OK) {
        // process message (which will only arrive every 5ms
        Serial.printf(msgString, "STD CAN-ID: 0x%.3lX       DLC: %1d  Data:", message.identifier, message.data_length_code);
            for(byte i = 0; i<message.data_length_code; i++){
                        Serial.printf(" 0x%.2X", message.data[i]);
            }
        Serial.println();
    }

return;
}

Here is the receiving side's output when sending in a 5.1ms period:

On the left you can see the period between this, and the previous message.
The ID in green on the right side confirms, that the message is a valid follow up to the previous message (data).
As soon as im trying to go <5ms, 3ms in this example it looks like this:

Here, it starts to drop messages as soon the RX buffer is filled up.
In the last image, you will see a log of the drivetrain canbus of a 2013 VAG car using the ESP32 and a MPC2515 controller externally.
It has periods between 0.41 and 9ms between each package and its not missing a single one of it.

I hope, someone here can actually help with this or had experienced the same behaviour before.
Br Chris

all of this is dependent on your code, which you have not posted

I linked the exact library i used, i am simply SENDING and RECEIVING can messages, and i explained, it doesnt matter which configuration i am using. My problem is not, that i fail to send messages, rather then the timing issues.
But i will post the code..


text:
Strtok operations on Arduino Zero seem to fail in runtime
I am trying to test functionality of strtok() on a new piece of hardware, as I ran out of memory to develop on my Nano. This is a basic example from the internet involving tokenizing the string and reporting the tokenized entries via SerialUSB. I'm running a Rocketscream V3 (Arduino Zero ATSAMD21G18A).
#include <string.h>

void setup() {
  char *token;
  char *mystring = "apples,pears,bananas";

  SerialUSB.begin(9600);
  while (!SerialUSB) { }

  SerialUSB.print("Serial established");

  token = strtok(mystring, ",");

  while (token != NULL) {
    SerialUSB.println(token);
    token=strtok(NULL, ",");
  }
}

The code works as expected on my Nano (with Serial instead of SerialUSB), but while it does compile for the Arduino Zero, the Zero never makes it past printing "Serial established". I have confirmed this by including code (serial print, LED flashing) past the tokenization parts, and these are never executed. The loop() function is never reached, it seems to halt at "token = strtok(mystring, ",");".
I cannot think of a simpler possible way to test strtok(), but it's just not working. Any help would be appreciated.

strtok works by modifying the source string. Your test string points to a constant string.
  char *mystring = "apples,pears,bananas";

This particular platform may put that into read-only memory. Try instead as your test string:
  char mystring [] = "apples,pears,bananas";

I don't have a Zero to test it on, but in any case using strtok on a const string is not recommended forbidden.

If you turn warnings on for the compiler (File -> Preferences) you see this:
 In function 'void setup()':
 warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   char *mystring = "apples,pears,bananas";

If you are doing something "forbidden" then don't expect good results.

You mean char mystring[] = "apples,pears,bananas";.

Oh, and it's way worse than “not recommended”. It is “undefined behavior”.

The compiler should at least be warning, if not giving an error, for passing a const string to a pointer to char.

Ah, it does if you turn warnings on.

@EdgarBonet Yes, a little typo there. Fixed.

Thank you @Nick_Gammon, I didn't realize I had warnings turned off.  That was all I needed. So, the code as written is undefined behavior, but why does it successfully execute on Nano? Just a quirk of how it handles memory during runtime?

Undefined behaviour, by definition, will behave in unexpected (or indeed, undefined) ways. The Nano may not care that you are writing to read-only memory.


text:
Can I use a TCS34725 color sensor with a LilyPad?
I have been trying to get a TCS34725 color sensor working with a LilyPad Arduino USB - ATmega32U4 board, but with no success. I am wondering if it possible?
I have been using the following sketch to try and get a reading but nothing appears in the monitor:
#include <Wire.h>
#include "Adafruit_TCS34725.h"

/* Example code for the Adafruit TCS34725 breakout library */

/* Connect SCL    to analog 5
   Connect SDA    to analog 4
   Connect VDD    to 3.3V DC
   Connect GROUND to common ground */

/* Initialise with default values (int time = 2.4ms, gain = 1x) */
// Adafruit_TCS34725 tcs = Adafruit_TCS34725();

/* Initialise with specific int time and gain values */
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

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

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1);
  }

  // Now we're ready to get readings!
}

void loop(void) {
  uint16_t r, g, b, c, colorTemp, lux;

  tcs.getRawData(&r, &g, &b, &c);
  // colorTemp = tcs.calculateColorTemperature(r, g, b);
  colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
  lux = tcs.calculateLux(r, g, b);

  Serial.print("Color Temp: "); Serial.print(colorTemp, DEC); Serial.print(" K - ");
  Serial.print("Lux: "); Serial.print(lux, DEC); Serial.print(" - ");
  Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
  Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
  Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
  Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
  Serial.println(" ");
}

When really nothing appears on the serial monitor, then your serial connection doesn't work. Do you have selected the correct port and baud rate?

Can I use TCS34725 Color Sensor with Lilypad?

Yes but please note that the I2C pins are D2 (SDA) and D3 (SCL). No extra components are required when connecting to the Adafruit TCS34725 breakout board. It contains pull-up resistors, and voltage/signal level converters (if needed).
Cheers!
Ref. https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad_Arduino_USB_v12.pdf


text:
Connecting a push button to a stepper motor problem
I can't get this code to work. The button code and the step motor code works separately. However, when I code using an if statement saying when the button is pressed the motor will move or else it won't. PLEASE HELP.
const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30

int i = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IN_1, OUTPUT);
  pinMode(IN_2, OUTPUT);
  pinMode(IN_3, OUTPUT);
  pinMode(IN_4, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.print ("start");
}

void loop() {
  buttonState = digitalRead (buttonPin);
  if (buttonState == HIGH) {
    //delay(1000);
    for (i=0; i<4; i++)
      Serial.println ("pressed");
    switch (i) {
      case 3: // ASCII value for '1'
        digitalWrite(IN_1, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_1, LOW);
        break;
      case 1: // ASCII value for '2'
        digitalWrite(IN_2, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_2, LOW);
        break;
      case 0: // ASCII value for '3'
        digitalWrite(IN_3, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_3, LOW);
        break;
      case 2: // ASCII value for '4'
        digitalWrite(IN_4, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_4, LOW);
        break;
      default:
        Serial.println("Not a valid case");
        break;
    }
    if (i == 4) {
      i = 0;
    } else {
      i = 5;
    }
  }
}

What is that if supposed to achieve in your for loop that changes the i value to 5 all the time supposed to achieve?

will you please explain what you are trying to achieve?

Your code makes no sense at all.  Let's break it down. First we'll reformat the code using the auto-formatter (AStyle) in UECIDE:
const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30
int i = 0;

void setup()

{
    Serial.begin(9600);
    pinMode(IN_1, OUTPUT);
    pinMode(IN_2, OUTPUT);
    pinMode(IN_3, OUTPUT);
    pinMode(IN_4, OUTPUT);
    pinMode(buttonPin, INPUT);
    Serial.print("start");
}

void loop()

{
    buttonState = digitalRead(buttonPin);

    if (buttonState == HIGH) {
//delay(1000);
        for (i = 0; i < 4; i++) {
            Serial.println("pressed");
        }

        switch (i) {
            case 3: // ASCII  value for '1'
                digitalWrite(IN_1, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_1, LOW);
                break;

            case 1: // ASCII  value for '2'
                digitalWrite(IN_2, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_2, LOW);
                break;

            case 0: // ASCII  value for '3'
                digitalWrite(IN_3, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_3, LOW);
                break;

            case 2: // ASCII  value for '4'
                digitalWrite(IN_4, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_4, LOW);
                break;

            default:
                Serial.println("Not a valid case");
                break;
        }

        if (i == 4) {
            i = 0;
        } else {
            i = 5;
        }
    }
}

Now that we have fixed the formatting we can see some very strange things:
if (buttonState == HIGH) {

First we're doing this for every loop iteration where the button is pressed. That means we're doing it over and over again until you release the button.
    for (i = 0; i < 4; i++) {
        Serial.println("pressed");
    }

Now we're printing the word "pressed" four times.  After this i will be set to 4.
The switch will now take an input value of 4, which is "Not a valid case". So nothing will happen.
Then:
    if (i == 4) {
        i = 0;
    } else {
        i = 5;
    }

i is always 4, so it will always set it to 0.  Quite what this block is supposed to achieve I have no clue. If it were supposed to be inside the for loop above then it would just kill the loop on the first iteration, since i, when 0, would not be 4, so would be changed to 5, which is > 4. It makes no sense and can achieve nothing of value.
As for the switch: if it were inside the for loop and able to get some varying values of i, it would just make each output briefly activate in turn. If that's what you need to drive your motor, then fine. However, it's never going to run since the rest of the program is just nonsense.


text:
DS18B20 with only OneWire library
Peter Scargill found a way to use a DS18B20 temperature sensor only using the OneWire library, and it's amazing how blazing fast it is! (It's an old article from 2013.)
#include <OneWire.h>

int16_t dallas(int x,byte start) {
  OneWire ds(x);
  byte i;
  byte data[2];
  int16_t result;
  do {
    ds.reset();
    ds.write(0xCC);
    ds.write(0xBE);
    for (int i = 0; i < 2; i++)
      data[i] = ds.read();
    result = (data[1] << 8) |data[0];
    result >>= 4;
    if (data[1]&128)
      result |= 61440;
    if (data[0]&8)
      ++result;
    ds.reset();
    ds.write(0xCC);
    ds.write(0x44, 1);
    if (start)
      delay(1000);
  } while (start--);
  return result;
}

void setup () {
  dallas(A0,1);
}

void loop () {
  float currentTemp = dallas(A0, 0);
}

The problem is the accuracy; he converts float to int to get an accuracy of 1°C and it's working just fine.
How can I get an accuracy of 0.5°C (or 0.2°C) using this semi library?

Which is the pin of DS18B20? i dont understand

Actually he isn't really converting float to int. He never uses float since he doesn't need it. The datasheet of the DS18B20 shows at page 6 how the data is formatted:

The 4 highest bits just resemble the sign bit 11.
The first digit with full degrees is bit 4. Every bit below that has values below 1°C

So the data bytes 0b1111100001010000 will represent a temperature of -123°C and 0b1111100001011000 -122.5°C.
The author from the link then shifts this data 4 bits to the right, so that all bits representing values under 1 vanish. You can convert the received value per hand to float by also using this.
int16_t whole_degree = (result & 0x07FF) >> 4;
float temperature =
whole_degree +
0.5 * ((data[0]&0x8)>>3) +
0.25 * ((data[0]&0x4)>>2) +
0.125 * ((data[0]&0x2)>>1) +
0.0625 * (data[0]&0x1);
if (data[1]&128)
  temperature *= -1;

As float does not have the same structure as the data, we need to convert it. So I first calculate the number of whole degrees analog to your code. Then I add this up with the values of the lowest 4 bits. ((data[0]&0x8)>>3) and its siblings will be 1, when the corresponding bit is set, and 0, if not.
So you get the full precision of the sensor (12 bits). Please note that for this to work, you should not configure the sensor to less resolution. In that case you would have to ignore the corresponding lowest bits. But the sensor is in 12 bit mode at power up anyway and your code does not configure it otherwise.
Note: I'm unsure about the line result |= 61440; in the original code. This sets the 4 highest bits of a 16 bit value to 1. I don't see why this should be correct here, since a normal 16-bit integer does only have 1 sign bit. In my understanding the original code would lead to false readings (way off), when reading temperatures below zero. I instead simply multiplied the resulting temperature with -1.
The whole code would look like this (I also added the statement for printing out the pure received data as binary, as I requested it in my comment. These statements are currently commented out):
#include <OneWire.h>

float dallas(int x,byte start) {
  OneWire ds(x);
  byte i;
  byte data[2];
  int16_t result;
  float temperature;

  do {
    ds.reset();
    ds.write(0xCC);
    ds.write(0xBE);
    for (int i = 0; i < 2; i++)
      data[i] = ds.read();
    result = (data[1]<<8) |data[0];
    // Here you could print out the received bytes as binary, as requested in my comment:
    // Serial.println(result, BIN);
    int16_t whole_degree = (result & 0x07FF) >> 4; // cut out sign bits and shift
    temperature = whole_degree +
    0.5 * ((data[0]&0x8)>>3) +   // 0.5    = 2^-1
    0.25 * ((data[0]&0x4)>>2) +  // 0.25   = 2^-2
    0.125 * ((data[0]&0x2)>>1) + // 0.125  = 2^-3
    0.0625 * (data[0]&0x1);      // 0.0625 = 2^-4
    if (data[1]&128)
      temperature *= -1;
    ds.reset();
    ds.write(0xCC);
    ds.write(0x44, 1);
    if (start)
      delay(1000);
  } while (start--);
  return temperature;
}

void setup {
  // Adding Serial.begin(9600); for printing the received bytes here
  //Serial.begin(9600);
  dallas(A0,1);
}

void loop {
  float currentTemp = dallas(A0, 0);
}

i implanted that into the code and reading is like around 470 degree!

Mhh, can you output the pure reading in binary and write this into a comment. You can do this via serial by Serial.println(result, BIN);

i think maybe my implantation is wrong, can you please embed that code into my code or provide some instruction to where i should paste those lines?

"'result' was not declared in this scope"

@newbie I added a not-tested implementation to my answer. You can try it. There are also the statements for printing the pure reading in binary. These statements just have to be uncommented in the case, that this code is not working correctly

thank you, it says:
"'result' was not declared in this scope" when i want to do Serial.println(result, BIN); in void loop/setup. and temperature is still above 400...

Yes, surely it says that in loop, since you should not put it there, but into the function dallas(). But you can just use my provided code an uncomment the lines with Serial in dallas() and setup()

111001010 458.00

@newbie you asked me to look at this question, but I think this answer explained it well (and upvoted it)... or do you have something specific for me to look at?

@MichelKeijzers yes thank you, chris explained it well but the temperature reading isn't right. thought maybe you have an idea about it...

@newbie I have corrected my code. The sign thing didn't work as I thought it would, so I now did it simply by multiplying with -1. Also I included a bit to to cut out the sign bits from whole_degree before shifting, so that the 1's there cannot make garbage values. Please again check, if this works for you. I hope, that it is correct now. I tested the calculations with a spare Arduino Nano and a mockup value (The one you posted as comment should result in 28,625°C)

@chrisl thanks but the result is still the same for me! 111000011 451.00  very strange!

@newbie It's more efficient to follow chrisl's fix since he is at the correct answer almost or already, instead of me starting to dive in this problem.

@MichelKeijzers thanks for checking in man, really appreciate it.

@chrisl i copy/pasted the exact code you posted and i'm just doing this two prints: Serial.println(result, BIN); and Serial.println(dallas(A0,0));, why i'm still getting this 111000011 451.00  at the output!

I will investigate again

@chrisl i'd buy you a drink if i knew you in real world, you're such a nice gentleman.

@newbie you're welcome ... but all credits are for chrisl

I think I have found the problem facepalm I didn't change the return statement of the function. It still returned result, but the real temperature is in the variable temperature. I'm changing this now

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

Why not rewrite the dallas() function so that it returns a float?
#include <OneWire.h>

OneWire ds(A0);

float dallas(OneWire& ds, byte start = false) {
    int16_t temp;
    do {
        ds.reset();
        ds.write(0xCC);
        ds.write(0xBE);
        ds.read_bytes((uint8_t*) &temp, sizeof(temp));
        ds.reset();
        ds.write(0xCC);
        ds.write(0x44, 1);
        if (start) delay(1000);
    } while (start--);
    return (temp * 0.0625);
}

void setup {
  dallas(ds, true);
}

void loop {
  float currentTemp = dallas(ds);
}


text:
Attach() resets servo's angle
I'm working on code that will control micro servo. I use generic servo and built-in library for controling servo. Microcontroller is generic STM32.
Controlling servo Works as expected. But I don't want next behavior - attach() function sets servo to 180°(maybe 0°, not sure).
In my project I want next:

Servo stays at angle before going off/reboot
Servo goes to 90° after turning on/reboot

I googled about this problem and tried with write(90); before attach() in setup() function. Servo goes to 90° but after like 50ms attach() stops write(90) function and it goes back to 180°. So this didn't solve my problem.
Next I've open Servo.cpp and found that attach() function contains next code:
    bool Servo::attach(uint8 pin,
                   uint16 minPW,
                   uint16 maxPW,
                   int16 minAngle,
                   int16 maxAngle) {
    timer_dev *tdev = PIN_MAP[pin].timer_device;

    if (tdev == NULL) {
        // don't reset any fields or ASSERT(0), to keep driving any
        // previously attach()ed servo.
        return false;
    }

    if (this->attached()) {
        this->detach();
    }

    this->pin = pin;
    this->minPW = minPW;
    this->maxPW = maxPW;
    this->minAngle = minAngle;
    this->maxAngle = maxAngle;

    pinMode(pin, PWM);

    timer_pause(tdev);
    timer_set_prescaler(tdev, SERVO_PRESCALER - 1); // prescaler is 1-based
    timer_set_reload(tdev, SERVO_OVERFLOW);
    timer_generate_update(tdev);
    timer_resume(tdev);

    return true;
}

What should I do to fix this problem? Servo will adjust angle of PCB which holds LEDs. PCB will be in case and angle of 90° is default angle. 0°/180° will either destory servo or brake case/PCB/something else.

If there are limits to the angles it can travel, I think you need to look at minAngle and maxAngle

You showed us the code from the core for the Servo library.  That code is KNOWN to work.  It works for everyone else.  Most likely the mistake is in the code that you wrote that you haven't shown us.  Please post the code you are having trouble with if you really want help.  It is impossible to help you fix code that I can't see.

@Delta_G Sorry for delayed answer. HLServo.attach(PA8) is in setup() function. Immediately after reboot servo goes to "neutral" angle. So problem lays in servo lib I guess. I'll try with min and max angle parameters.

You still aren't showing the code that you are having problems with.  It's like showing up at the mechanic to ask what's wrong with your car and not bringing the car with you.  Or asking the doctor to tell you what's wrong with your friend that you didn't bring with you.  It is impossible to diagnose what we can't see.  If you can't post the code that you have that you say isn't working then there isn't anything anyone can really do to help you.  Go edit your post and remove the Servo.cpp code.  We all have that code already.  And instead paste in the code that you have that doesn't work.

You can avoid using the attach(); method by programming without the servo library.
  for(x=0; x<150; x=x+1)
  {
    digitalWrite(Servomotor, HIGH);
    delayMicroseconds(2350); //Change the delay here to change the angle it goes to
    digitalWrite(Servomotor, LOW);
    delayMicroseconds(18550);
  }

This is an example code for how it worked for me. It sends a pulse to the servo which makes it turn a bit until it reaches a "barrier".


text:
Motion detection alarm that calls back
I need help. I am making motion detector that calls you when sensor activates
and i have done the code for that, but the thing is i am beginner and i need to make it when it first time boots i send a message with the number that will be called when sensor activates
`
int LED1 = 12;
int GND1 = 13;
int LED2 = 8;
int GND2 = 9;
int pirOutput = 5;
void setup()
{
  Serial.begin(9600);
  pinMode(LED1, OUTPUT);
  pinMode(GND1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(GND2, OUTPUT);
  pinMode(pirOutput, INPUT);

  digitalWrite(pirOutput, LOW);
  digitalWrite(GND1, LOW);
  digitalWrite(GND2, LOW);
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  delay(15000);
  digitalWrite(LED1, HIGH);

}
void loop()
{
  if (digitalRead(pirOutput) == HIGH)
  {
    digitalWrite(LED2, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.println("ATD+381xxxxxxxx;");
    delay(15000);
    Serial.println("ATH");
    digitalWrite(LED2, LOW);
    delay(1000);
  }
}

that is the code i found and it works fine for me

I that code is fine for you, what exactly is your Question?

what does this mean? i send a message with the number that will be called ..... where are you sending a message?


text:
Timer for how long button is not pressed
I would like to timer for how long a button is not pressed. So actually if(buttonState == LOW 'for two seconds') than execute the code that comes after it. But the problem is while the user is still pressing the button the timer already starts.
Code:
int ledPin[] = {7,8,9,10};
int ledPin11 = 11;
long randNumber;
const int buttonPin = 2;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
unsigned long previousMillis = 0;
const long interval = 2000;

void setup() {
 Serial.begin(9600);
 pinMode(LED_BUILTIN, OUTPUT);
 randomSeed(analogRead(0));
 randNumber = random(1, 16);
 Serial.println(randNumber);
 for (int i = 0; i < 4; i++) {
   pinMode(ledPin[i], OUTPUT);
 }
  pinMode(buttonPin, INPUT);
 }

 void loop() {
  displayBinary(randNumber); //functie 'display binary'
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    previousMillis = currentMillis;
    if(buttonState == LOW){
    antwoord(buttonPushCounter,randNumber);
    delay(5000);
    displayBinary(randNumber);
  }
 }
 buttonState = digitalRead(buttonPin);
 if (buttonState != lastButtonState) { // als de button word ingedrukt krijgt buttonPushCounter + 1
 if (buttonState == HIGH) {
  buttonPushCounter++;
  Serial.print("Nummer hoe vaak is gedrukt");
  Serial.println(buttonPushCounter);
 } else {
  Serial.println("off");
}
delay(250);
 }
}

void antwoord(int teller, int antwoord) {
 if (teller == antwoord) {
  for (int i = 0; i < 4; i++) {
  pinMode(ledPin[i], LOW);
 }
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 digitalWrite(LED_BUILTIN, LOW);
 delay(250);
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 } else if (teller > antwoord || teller < antwoord) {
   for (int i = 0; i < 4; i++) {
    pinMode(ledPin[i], LOW);
  }
    digitalWrite(LED_BUILTIN, HIGH);
  }
}

void displayBinary(byte numToShow) //van byte naar decimaal
  {
   for (int i = 0; i < 4; i++) {
    if (bitRead(numToShow, i) == 1) {
    digitalWrite(ledPin[i], HIGH);
    } else {
      digitalWrite(ledPin[i], LOW);
    }
   }
  }

I would start a timer when the button changes state. Then you timeout if
the button is released and it hasn't changed state for too long:
void loop()
{
    static int lastButtonState;
    static unsigned long buttonChangeTime;
    int buttonState = digitalRead(buttonPin);
    unsigned long now = millis();

    // Record time when button changes state.
    if (buttonState != lastButtonState)
        buttonChangeTime = now;

    // Timeout if button is not pushed for too long.
    if (buttonState == LOW && now - buttonChangeTime >= interval)
        Serial.println("Timeout.");

    lastButtonState = buttonState;
}

Don't forget to update lastButtonState on each iteration.

Your question is not clear enough.
I hope I get what you want.
Do while loop about the pressing...
if (button == LOW)
     while(!digitalread(button)){};

Why the if? If it's true, the while won't continue, giving basically the same effect :)

the if here is just if he want to do something before, is just habit.

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


text:
Serial communication problem with sim7600 with Arduino Mega
I am just sending the AT command to test if the serial communication works, the response I am getting is a flipped "?" or a square or rectangle symbol.
I have tested the communication using software provided by Waveshare connected through on board USB to UART.
https://www.waveshare.com/wiki/SIM7600E-H_4G_HAT
int PowerKey = 2;
char answer;

void setup()
{
 Serial3.begin(96u00);
 Serial.begin(9600);
 pinMode(PowerKey, OUTPUT);
 Serial.println("initializing");
 digitalWrite(PowerKey, HIGH);
 delay(1000);
 digitalWrite(PowerKey, LOW);
}

void loop()
{
  answer = send_at_cmd("AT\r\n");
  Serial.println(answer);
}

uint8_t send_at_cmd(const char* ATcommand)
{
  char response;
  // send test command AT
  Serial3.print(ATcommand);
  Serial.println(ATcommand);
  delay(1000);
  //Check for response from the sim7600E-H
  while(Serial3.available() != 0)
  {
    response = Serial3.read();
  }
  return response;
}

Your code sets serial 3 to 9600, but the second image sets the serial port to 115K.  I think that may be a problem, because at least one is wrong.

I have set it to 115200 but I still have the same result

You have change baud rate by at+iprex=9600 before upload your code, because sim7600 set 115200 by default then save your setting by at&w.
hope this help someone.


text:
Where to store critical data in power outage situation on ESP8266
I want to store a counter that is always changing, but I want it to remain and be able to retrieve it on after a power loss.
It's only one long number data, but as it is always changing, I don't know where to store it to not over wear the memory space.
I'm aware that writing to much on ESP's EEPROM or SPIFFS would damage it. I've seen that post, but it doesn't help in my case.
The data to be saved is the volume of water pumped with a water pump during it's entire life.
Of course I could save it only once a while to reduce the number of writes, but I would lose some acccuracy.

As far as I can see SPIFFS does wear leveling. To get a ballpark number of counter updates you can do before you have to think about wear. Get the size of the SPIFFS volume. Divide that by the sector size of the SPI flash (see datasheet). Multiply that by the number of cycles the datasheet specifies for it's endurance. My guess is, your pump has to run for millennia before you can expect problems with the flash.

you could save it to rtc memory each read, and to spiffs (which is wear-leveled) every 10 reads. That would let you lossless-ly resume from brief power interruptions, and balance long-term precision with reliability.

If you worry about the maximum number of write cycles, you could write the data to an SD card or some FRAM connected to the ESP8266, or you could send the data to a (web) server (if you have access to one) using WiFi. The server can then store the data.
If you really care about the data, you could do both. Having a backup is the only protection against catastrophic failure.

A local solution would be to use EERAM.  This is an EEPROM and an SRAM coupled together with some intelligent power management circuitry - writes get stored in SRAM until the power goes (or an instruction to save is sent) when the contents of SRAM get copied into EEPROM using the power stored in a large capacitor.
A good choice is the 47C16 (5V) or 47L16 (3.3V).


text:
Connect 12 V DC sensor to Arduino Uno using TTL RS485
I'm trying to connect an Arduino Uno with a BGT PM2510 sensor (which uses 7-12 V DC) by using a UART TTL to RS485 Two-way Converter.
The only thing I wonder about is: can the sensor damage the MCU?
According to the information on the 12 V sensor, it says:
Output signal: RS485 (Modbus protocol). I did measurements on the A & B ports of that sensor; the multimeter showed 3.3 V.
My question is, can the sensor damage the MCU? I intend to connect the Arduino and sensor as in the diagram below:

You should be fine.
RS-485 does specify signal levels of ±1.5 V to ±5 V, but even so, and even when the sensor would misbehave or when the common mode voltage is low or high, there is still the TTL-to-RS485 converter in the middle that has 5 V TTL logic on the Arduino side.
As long as the TTL-to-RS485 converter is properly connected to the Arduino and working as it should, the Arduino is safe.


text:
i was trying to rebuild my code for my bot but then there are errors coming up i am in the middle of my project so i need quick help
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 200
#define MAX_SPEED 190
#define MAX_SPEED_OFFSET 20

NewPing sonar (TRIG_PIN,ECHO_PIN,MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR34_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);

Servo myservo;
boolean goesForward=fclose;
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 <= 15); {
    moveStop();
    delay(100);
    moveForward();
    delay(300);
    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(170);
    delay(500);
    int distance=readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
  }

  int readPing() {
    delay(70);
    int cm = sonar.ping_cm();
    if (cm ==) {
      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) {
        motor1.setSpeed(speed.Set};
        motor2.setSpeed(speed.Set};
        motor3.setSpeed(speed.Set};
        motor4.setSpeed(speed.Set};
        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) {
      motor1.setSpeed(speed.Set};
      motor2.setSpeed(speed.Set};
      motor3.setSpeed(speed.Set};
      motor4.setSpeed(speed.Set};
      delay(5);
    }
  }

  void moveRight() {
    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 moveRight() {
    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);
  }

this is the error code
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"
C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'void loop()':

sketch_nov27b:53:13: error: 'lookLeft' was not declared in this scope
 distanceL = lookLeft();
             ^~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:53:13: note: suggested alternative: 'lookRight'

 distanceL = lookLeft();
             ^~~~~~~~
              lookRight

sketch_nov27b:58:1: error: 'turnRight' was not declared in this scope
 turnRight();
 ^~~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:58:1: note: suggested alternative: 'lookRight'

 turnRight();
 ^~~~~~~~~
 lookRight

sketch_nov27b:62:1: error: 'turnLeft' was not declared in this scope
 turnLeft();
 ^~~~~~~~

Sketch_nov27b:65:4: error: 'else' without a previous 'if'

   }else

    ^~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'int readPing()':

sketch_nov27b:86:10: error: expected primary-expression before ')' token

   if(cm==)

          ^

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'void moveForward()':

sketch_nov27b:104:1: error: 'goesFORWARD' was not declared in this scope

 goesFORWARD=true;

 ^~~~~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:104:1: note: suggested alternative: 'FORWARD'

 goesFORWARD=true;

 ^~~~~~~~~~~

 FORWARD

sketch_nov27b:111:17: error: 'speed' was not declared in this scope

 motor1.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:111:17: note: suggested alternative: 'speedSet'

 motor1.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

sketch_nov27b:112:17: error: 'speed' was not declared in this scope

 motor2.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:112:17: note: suggested alternative: 'speedSet'

 motor2.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

sketch_nov27b:113:17: error: 'speed' was not declared in this scope

 motor3.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:113:17: note: suggested alternative: 'speedSet'

 motor3.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: At global scope:

sketch_nov27b:114:1: error: 'motor4' does not name a type

 motor4.setSpeed(speed.Set};

 ^~~~~~

sketch_nov27b:114:26: error: expected declaration before '}' token

 motor4.setSpeed(speed.Set};

                          ^

Multiple libraries were found for "Servo.h"

 Used: C:\Users\amish\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\Servo

exit status 1

'lookLeft' was not declared in this scope

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

the servo part was not working so it came together

Sort out your code indentation and you will immediately see where the problem is. Try with the autoformat in the IDE.

thanks a lot...

You say you need quick help. Why?

Your code is riddled with typographical and basic syntax errors. Such things as using brackets instead of parentheses, semicolons after an if meaning it will do nothing, etc.
Sort out your basic syntax errors (hint: autoformat can help you with the indenting to highlight your problems) and you will see where you have gone wrong.
For instance, after autoformatting your code with astyle the moveForward() function has turned into this mess:
 99     if (!goesForward) {
100         goesFORWARD = true;
101         motor1.run(FORWARD);
102         motor2.run(FORWARD);
103         motor3.run(FORWARD);
104         motor4.run(FORWARD);
105
106         for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) {
107             motor1.setSpeed(speed.Set
108         };
109
110         motor2.setSpeed(speed.Set
111     };
112
113     motor3.setSpeed(speed.Set
114 };
115 motor4.setSpeed(speed.Set
116 };
117 delay(5);
118 }
119 }
120 }

Also, you have no lookLeft function - instead you have two lookRight functions.  You really should read what you've written.