text:
Blinking cursor on Arduino is inconsistent and misses inputs
I am trying to write a part of a program that prints time and allows the user to move a cursor across it. I have the following code, but there are a few issues with it.
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16,2);
  setTime(12,30,15,0,0,0);
}
int col = 0;

void loop() {
  uint8_t buttons = lcd.readButtons(); //create readable buttons
  char time_out[16];
  lcd.setCursor(0,0);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());
  lcd.print(time_out);
  lcd.setCursor(col,0);
  lcd.blink();
  delay(100);
  if (buttons) {
    lcd.clear();
    if (buttons & BUTTON_RIGHT) {
      col += 1;
    }
    if (buttons & BUTTON_LEFT) {
      col -= 1;
    }
  } //buttons
}

If you upload this to your board, you can tell that the blinking is highly irregular, not at all aesthetically pleasing.
You'll also notice that sometimes, when pressing left/right, the input isn't registered.
I suspect this has to do something with the delay() function used, which pauses the entire program.
I looked into the following method, but this does not work when needing to print something in a loop (as the time library requires).
Any idea how I could make this work better (regular blinking times and no miss of user input)?
Thanks a lot!

the code needs to check the variable col to assure it is inside the valid range before incrementing/decrementing.  This is to avoid the cursor being set outside the valid range.  I.E. if the valid range is 0...15 then check col >0 before decrementing and check col<15 before incrementing.

I think the statement lcd.clear() turns all the LEDs off,  that does not seem like a good idea

strongly suggest using a timer interrupt to handle the blinking, using a keypress interrupt for the cursor motion.

I don't have the hardware to test but, it should be more or less like this;
(I have also normalized the code into several functions for better readability.)
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

unsigned long timerBlink; //Required for periodic blinking
int intervalBlink = 100;

void setup() {
    lcd.begin(16, 2);
    setTime(12, 30, 15, 0, 0, 0);
    timerBlink = 0;
}
int col = 0;

void loop() {
    readButtons();
    printDate();
    if (millis() - timerBlink > intervalBlink) {
        blink();
    }
}

void readButtons() {
    uint8_t buttons = lcd.readButtons(); //create readable buttons
    if (buttons) {
        lcd.clear();
        if (buttons & BUTTON_RIGHT) {
            col += 1;
        }
        if (buttons & BUTTON_LEFT) {
            col -= 1;
        }
    } //buttons
}

void blink() {
    lcd.setCursor(col, 0);
    lcd.blink();
    timerBlink = millis();//Start timer for intervalBlink
}

void printDate() {
    char time_out[16];
    lcd.setCursor(0, 0);
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second());
    lcd.print(time_out);
}

Instead of blocking delay function, using timeout with timestamp is a better practice.


text:
Is there something wrong in my sketch?
I've been working on a project that need two sensors(mq2 and mpu6050), I got each sketches from the internet and I managed to work the mq2 but for the mpu6050, I'm still not sure if its working. The thing is I want the two sensors to work on their own but in one sketch. When the mq2 senses some gas, I want the LED and BUZZER turned on and the only way to turn it off is by resetting the arduino. For the MPU6050, it's the same with the mq2, when the MP6050 is triggered, I want the other LED and the same buzzer turn on, again the only way to turn it off is by resetting the arduino. I want to combine the se two skectches in one. But when I combined it, the circuit won't work. Could someone help me ?
Here is the code that I modified and combined:
#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;
//////////////////////////////////////////////////////////////////

//for mq2

int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 100;

//////////////////////////////////////////////////////////////////

void setup(){
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  mpu.setThreshold(3);
}

//////////////////////////////////////////////////////////////////

void loop(){
  // for mq2

  int analogSensor = analogRead(smokeA0);

  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000);
  }
  else{
  digitalWrite(greenLed, HIGH);
  }
  // for MPU6050

  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis  < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis  < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }

}

Here is the code for the mq2:
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 150;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000);
  }
  else{
  digitalWrite(greenLed, HIGH);
  delay(100);
  }
}

Here is the code for the MPU6050(I removed some lines when I put it at the combined sketch because I dont need the LCD code, dunno if I did it correct):
#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);

  delay (2000);

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  mpu.setThreshold(3);
  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();
  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:
      Serial.println("Stops the clock and keeps the timing generator in reset");
      break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ:
      Serial.println("PLL with external 19.2MHz reference");
      break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ:
      Serial.println("PLL with external 32.768kHz reference");
      break;
    case MPU6050_CLOCK_PLL_ZGYRO:
      Serial.println("PLL with Z axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_YGYRO:
      Serial.println("PLL with Y axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_XGYRO:
      Serial.println("PLL with X axis gyroscope reference");
      break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:
      Serial.println("Internal 8MHz oscillator");
      break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:
      Serial.println("2000 dps");
      break;
    case MPU6050_SCALE_1000DPS:
      Serial.println("1000 dps");
      break;
    case MPU6050_SCALE_500DPS:
       Serial.println("500 dps");
       break;
    case MPU6050_SCALE_250DPS:
       Serial.println("250 dps");
       break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());
  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis  < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis  < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    delay (1000);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }
  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);
  delay(10);
}

The i2c bus uses a4 and a5 for sda and scl. You can still use a0 up to a3 for the mq2 sensor. With some luck, nothing is broken yet, but keep in mind that the mpu6050 is a 3.3v sensor.

only you can decide if your sketch is working ..... if it does something that you do not want it to do, then it is not working ....... not working is a meaningless description of the program behavior ...... if you want real help then you should describe exactly what the program does and what you want it to do

Ok, I'll edit my post

@jsotola could you help me ?

@HamdanieImpa, did you understand my answer? You can read about the used pin numbers also on this page: https://www.arduino.cc/en/Reference/Wire

your description of the desired behavior is very good now ...... your description of the observed results is still vague .... do you mean that no buzzer sounds and no LEDs light? .... does any part work?

read @Jot's first comment ..... then look at this command line int smokeA0 = A5; ..... that is the conflict

@Jot, formulate your first comment as an answer .... the OP must have a 3.3V arduino because the sensor works with a separate sketch

The Arduino Uno has the special functions on fixed pins.
The I2C bus, for example, uses pin A4 and A5.
In the Arduino Wire reference page is a table of the pin numbers for the Arduino boards.
The pins called "SDA" and "SCL" near the USB connector are connected to the pins "A4" and "A5" (for an Arduino Uno).
That means that if you use the I2C bus, you may not use pin "A4" and "A5" for something else.
Connect the MQ2 gas sensor to pin A0, A1, A2 or A3, and it should work.
The MPU-6050 is an old sensor, there are newer and better sensors with less noise.
The MPU-6050 is a 3.3V sensor, that means its power should be 3.3V and the I2C bus should have 3.3V levels.
The Arduino Uno has a microcontroller that runs at 5V, and therefor it has a I2C bus with 5V levels.
A I2C level shifter can be used to connect the Arduino Uno with the MPU-6050. You can also use 4k7 pullup resistors from SDA to 3.3V and from SCL to 3.3V. Those pullup resistors are often already on the MPU-6050 module.
The MPU-6050 will work (for some time) with a I2C bus that has 5V levels, it might even work when the MPU-6050 is powered with 5V directly to the chip. That will influence the data, and the sensor might get damaged. Newer 3.3V sensor chips are often faster damaged with 5V, but don't push your luck with the MPU-6050.

source: Stack Exchange

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

sort: votes


text:
'RtcDateTime' does not name a type
I've tested a code that compiles successfully.
But after i merged it to another code, here it shown an error says RtcDateTime doesn't name a type.
Used library : https://github.com/Makuna/Rtc

Some notes :
- RtcDateTime instances are being used in setup() and loop() without a problem.
- RtcDS3231 header file is included (which includes RtcDateTime.h inside it).
- Tried to include RtcDateTime.h in my sketch, doesn't work !
Code : (Contains combination of 3 devices : RTC , I2C Ultrasonic and HX711 loadcell)
/*
Below, I define the SCL and SDA pins by their ATMEGA pins I have included links to common mappings below.
    UNO:  http://arduino.cc/en/Hacking/PinMapping168
    NANO: (matches UNO but has fewer pins)
    MEGA 2560: http://arduino.cc/en/Hacking/PinMapping2560
The current data matches the setup for the Arduino Uno -- they may need to be changed if the hardware changes.
You can also switch the I2C interface
to any of the tristate pins that you want (not just the SDA or SCL pins).
*/
#define SCL_PIN D2              //Default SDA is Pin5 PORTC for the UNO -- you can set this to any tristate pin
#define SDA_PIN D1              //Default SCL is Pin4 PORTC for the UNO -- you can set this to any tristate pin
#define I2C_TIMEOUT 100        //Define a timeout of 100 ms -- do not wait for clock stretching longer than this time

#include "HX711.h"  //You must have this library in your arduino library folder

#define DOUT  D1
#define CLK  D2

HX711 scale(DOUT, CLK);
float calibration_factor = -10060; //-106600 worked for my 40Kg max scale setup

/*
I have included a couple of extra useful settings for easy reference.
//#define I2C_CPUFREQ (F_CPU/8)//Useful if you plan on doing any clock switching
#define I2C_FASTMODE 1         //Run in fast mode (400 kHz)
#define I2C_SLOWMODE 1         //If you do not define the mode it will run at 100kHz with this define set to 1 it will run at 25kHz
*/
#include <SlowSoftI2CMaster.h>     //You will need to install this library
// create new instance with A4 as SDA, A5 as SCL and enable internal pullups
SlowSoftI2CMaster si = SlowSoftI2CMaster(SDA_PIN, SCL_PIN);

/*
 *  RTC Code starts here
 */

#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>
RtcDS3231<TwoWire> Rtc(Wire);
/*
 *  RTC Headers Ending
 */

void setup(){
  // Initialize both the serial and I2C bus
  Serial.begin(9600);
  Serial.println("Press T to tare");
  scale.set_scale(calibration_factor);  //Calibration Factor obtained from first sketch
  scale.tare();             //Reset the scale to 0

if (!si.i2c_init()) // initialize I2C module
        Serial.println("I2C init failed");

    /*
     *  RTC Setup :
     */
     Rtc.Begin(SDA_PIN,SCL_PIN);

    RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
    printDateTime(compiled);
    Serial.println();

    if (!Rtc.IsDateTimeValid())
    {
        // Common Cuases:
        //    1) first time you ran and the device wasn't running yet
        //    2) the battery on the device is low or even missing

        Serial.println("RTC lost confidence in the DateTime!");

        // following line sets the RTC to the date & time this sketch was compiled
        // it will also reset the valid flag internally unless the Rtc device is
        // having an issue

        Rtc.SetDateTime(compiled);
    }

    if (!Rtc.GetIsRunning())
    {
        Serial.println("RTC was not actively running, starting now");
        Rtc.SetIsRunning(true);
    }

    RtcDateTime now = Rtc.GetDateTime();
    if (now < compiled)
    {
        Serial.println("RTC is older than compile time!  (Updating DateTime)");
        Rtc.SetDateTime(compiled);
    }
    else if (now > compiled)
    {
        Serial.println("RTC is newer than compile time. (this is expected)");
    }
    else if (now == compiled)
    {
        Serial.println("RTC is the same as compile time! (not expected but all is fine)");
    }

    // never assume the Rtc was last configured by you, so
    // just clear them to your needed state
    Rtc.Enable32kHzPin(false);
    Rtc.SetSquareWavePin(DS3231SquareWavePin_ModeNone);

    /*
     *  RTC Setup Ending
     */
}
#define countof(a) (sizeof(a) / sizeof(a[0]))

void loop()
{
  if (!si.i2c_init()) // initialize I2C module
        Serial.println("I2C init failed");
  // (OPTIONAL) Read a sensor at the default address
  read_the_sensor_example();

  scale.begin(SDA_PIN,SCL_PIN);
  Serial.print("Weight: ");
  Serial.print(scale.get_units(), 5);  //Up to 3 decimal points
  Serial.println(" kg"); //Change this to kg and re-adjust the calibration factor if you follow lbs

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == 't' || temp == 'T')
      scale.tare();  //Reset the scale to zero
  }

  /*
   *  RTC Loop Start
   */
  if (!Rtc.IsDateTimeValid())
    {
        // Common Cuases:
        //    1) the battery on the device is low or even missing and the power line was disconnected
        Serial.println("RTC lost confidence in the DateTime!");
    }

    RtcDateTime now = Rtc.GetDateTime();

    Serial.println();
    // String date = dateS(now);
    // String time = timeS(now);

  RtcTemperature temp = Rtc.GetTemperature();
  temp.Print(Serial);
  // you may also get the temperature as a float and print it
    // Serial.print(temp.AsFloatDegC());
    Serial.println("C");

  /*
   *    RTC loop Ending
   */
}

void printDateTime(const RtcDateTime& dt)
{
    char datestring[20];

    snprintf_P(datestring,
            countof(datestring),
            PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
            dt.Month(),
            dt.Day(),
            dt.Year(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    Serial.print(datestring);
}

///////////////////////////////////////////////////
// Function: Start a range reading on the sensor //
///////////////////////////////////////////////////
//Uses the I2C library to start a sensor at the given address
//Collects and reports an error bit where: 1 = there was an error or 0 = there was no error.
//INPUTS: byte bit8address = the address of the sensor that we want to command a range reading
//OUPUTS: bit  errorlevel = reports if the function was successful in taking a range reading: 1 = the function
//  had an error, 0 = the function was successful
boolean start_sensor(byte bit8address){
  boolean errorlevel = 0;
  bit8address = bit8address & B11111110;               //Do a bitwise 'and' operation to force the last bit to be zero -- we are writing to the address.
  errorlevel = !si.i2c_start(bit8address) | errorlevel;   //Run i2c_start(address) while doing so, collect any errors where 1 = there was an error.
  errorlevel = !si.i2c_write(81) | errorlevel;            //Send the 'take range reading' command. (notice how the library has error = 0 so I had to use "!" (not) to invert the error)
  si.i2c_stop();
  return errorlevel;
}

///////////////////////////////////////////////////////////////////////
// Function: Read the range from the sensor at the specified address //
///////////////////////////////////////////////////////////////////////
//Uses the I2C library to read a sensor at the given address
//Collects errors and reports an invalid range of "0" if there was a problem.
//INPUTS: byte  bit8address = the address of the sensor to read from
//OUPUTS: int   range = the distance in cm that the sensor reported; if "0" there was a communication error
int read_sensor(byte bit8address){
  boolean errorlevel = 0;
  int range = 0;
  byte range_highbyte = 0;
  byte range_lowbyte = 0;
  bit8address = bit8address | B00000001;  //Do a bitwise 'or' operation to force the last bit to be 'one' -- we are reading from the address.
  errorlevel = !si.i2c_start(bit8address) | errorlevel;
  range_highbyte = si.i2c_read(0);           //Read a byte and send an ACK (acknowledge)
  range_lowbyte  = si.i2c_read(1);           //Read a byte and send a NACK to terminate the transmission
  si.i2c_stop();
  range = (range_highbyte * 256) + range_lowbyte;  //compile the range integer from the two bytes received.
  if(errorlevel){
    return 0;
  }
  else{
    return range;
  }
}

/////////////////////////////////////////
// Function: Change the sensor address //
/////////////////////////////////////////
//Uses the I2C library to change the address of a sensor at a given address
//Collects and reports an error bit where: 1 = there was an error or 0 = there was no error.
//INPUTS: byte oldaddress = the current address of the sensor that we want to change
//INPUTS: byte newddress  = the address that we want to change the sensor to
//OUPUTS: bit  errorlevel = reports if the function was successful in changing the address: 1 = the function had an
//      error, 0 = the function was successful
boolean change_address(byte oldaddress,byte newaddress){
  //note that the new address will only work as an even number (odd numbers will round down)
  boolean errorlevel = 0;
  oldaddress = oldaddress & B11111110;  //Do a bitwise 'and' operation to force the last bit to be zero -- we are writing to the address.
  errorlevel = !si.i2c_start(oldaddress) | errorlevel; //Start communication at the new address and track error codes
  errorlevel = !si.i2c_write(170) | errorlevel;        //Send the unlock code and track the error codes
  errorlevel = !si.i2c_write(165) | errorlevel;        //Send the unlock code and track the error codes
  errorlevel = !si.i2c_write(newaddress) | errorlevel; //Send the new address
//  si.i2c_stop();
  return errorlevel;
}

//////////////////////////////////////////////////////////
// Code Example: Read the sensor at the default address //
//////////////////////////////////////////////////////////
void read_the_sensor_example(){
  boolean error = 0;  //Create a bit to check for catch errors as needed.
  int range;

  //Take a range reading at the default address of 224
  error = start_sensor(224);    //Start the sensor and collect any error codes.
  if (!error){                  //If you had an error starting the sensor there is little point in reading it as you will get old data.
    delay(100);
    range = read_sensor(224);   //reading the sensor will return an integer value -- if this value is 0 there was an error
    Serial.print("R:");Serial.println(range);
  }
}

////////////////////////////////////////////////////////////////
// Code Example: Poll all possible addresses to find a sensor //
////////////////////////////////////////////////////////////////
void address_polling_example(){
  boolean error = 0;  //Create a bit to check for catch errors as needed.
  int range = 0;
  Serial.println("Polling addresses...");

  //Walk through all possible addresses and check for a device that can receive the range command and will
  //    return two bytes.
  for (byte i=2; i!=0; i+=2){   //start at 2 and count up by 2 until wrapping to 0. Checks all addresses (2-254) except 0 (which cannot be used by a device)
    error = 0;
    error = start_sensor(i);    //Start the sensor and collect any error codes.
    if (!error){                //If you had an error starting the sensor there is little point in reading it.
      delay(100);
      range = read_sensor(i);   //reading the sensor will return an integer value -- if this value is 0 there was an error
      Serial.println(i);
      if (range != 0){
        Serial.print("Device found at:");Serial.print(i);Serial.print(" Reported value of:");Serial.println(range);
      }
    }
    else{
      Serial.print("Couldn't start:");Serial.println(i);
    }
  }

  Serial.println("Address polling complete.");
}

//////////////////////////////////////////////
// Code Example: Change the default address //
//////////////////////////////////////////////
void default_address_change_example(){
  boolean error = 0;  //Create a bit to check for catch errors as needed.
  int range;

  Serial.println("Take a reading at the default address");

  //Take a range reading at the default address of 224
  error = start_sensor(224);    //Start the sensor and collect any error codes.
  if (!error){                  //If you had an error starting the sensor there is little point in reading it.
    delay(100);
    range = read_sensor(224);   //reading the sensor will return an integer value -- if this value is 0 there was an error
    Serial.print("R:");Serial.println(range);
  }

   Serial.println("Change the sensor at the default address to 222");
  //Change the address from 224 to 222
  error = 0;
  error = change_address(224,222);  //Change the address -- I don't do anything with the error handler at this point but you can if you want.
  delay(200);    //Wait 125ms for the sensor to save the new address and reset

   Serial.println("Take a reading at the new address");

  //Take a range reading at the new address of 222
  error = 0;
  error = start_sensor(222);     //Same as above but at the new address
  if (!error){
    delay(100);
    range = read_sensor(222);
    Serial.print("N:");Serial.println(range);
  }

   Serial.println("Change the sensor back to the default address");

  //Change the address from 222 to 224
  error = 0;
  error = change_address(222,224);
  delay(200);    //Wait 125ms for the sensor to save the new address and reset

}

So i have no idea why this happens .
Any help ?

well, I'VE FOUND THE ERROR! But wtf is this error !? after trimming code out many times finding what addition caused the error. it was line 21 float calibration_factor = -10060;  switching it on/off is the edge of the error appearing !

Believe or don't believe ! the comment causes the error [facepalm]

What version of the IDE are you using? I believe the problem is with the location of the auto generated function prototypes.

It's 1.8.7 - But it's so weird a comment can cause such a thing !

It's not the comment. It's the face that the float is before the include, and that float is where the IDE codes to place the prototypes. Move the include for the rtc to before that float.

move all includes to the top of the file. you make it hard for Arduino builder ino-to-cpp conversion with your style

@Majenko  Thanks for the solution! Now it compiles without errors :) . But the weird thing that removing the comment was resolving the error too! xD

@Majenko Is it terrible if i split my sketch into more than a helper .h file within sketch directory, then include them all in my .ino file?

Weird things happen with the Arduino IDE's prototypes if you're not careful. It's one of the first things I tackled in UECIDE, which always places the prototypes immediately before the first actual function in the code.

It is better to split your code into multiple INO files. The IDE then combines them for you - no need to include them manually.

So, INO not h files ? there could be some interactions between them.

The INO files are only separate to you. To the code it's just one single INO file.

Sorry, I didn't understand you.  I see that there could be 1 .ino file between some .h files at sketch folder, where these are included into .ino file as a header. Is that what you mean?

@Majenko I've just read a thread in arduino forums, It's now more clear to me. I'll figure it out.

@Majenko Hi mister, I've tried to split my code into multi INO files. But the error message returns to appear. I've checked in every INO file : library includes first, then comes defines, then comes global instances and variables.

Make sure that the includes only come at the start of the "main" .INO file - the one that is the name of the sketch.

Thank you very much @Majenko, It works now without any problem. I had before split the includes into files too. Now fixed that and it compiles (y)

I was also getting the same problem,  place the printDateTime function on the first page or the page where the headers and declaration's available
below function
#define countof(a) (sizeof(a) / sizeof(a[0]))
void printDateTime(const RtcDateTime& dt)
{
    char datestring[20];

    snprintf_P(datestring,
            countof(datestring),
            PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
            dt.Month(),
            dt.Day(),
            dt.Year(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    Serial.print(datestring);
}

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


text:
Equivalent of millis() in Atmel studio
This code It works in atmel studio.But this millis function is starting to run 31-34 miliseconds behind of arduino millis fuction.Why?I am adding picture.
Picture: https://imageshack.com/a/img922/3060/umtNJp.jpg
Update 2
#define F_CPU 8000000UL
#include <avr/io.h>

#include <avr/interrupt.h>

#define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (F_CPU / 1000L) )
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
// the fractional number of milliseconds per timer0 overflow. we shift right
// by three to fit these numbers into a byte. (for the clock speeds we care
// about - 8 and 16 MHz - this doesn't lose precision.)
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
#define FRACT_MAX (1000 >> 3)
volatile unsigned long timer0_overflow_count = 0;
volatile unsigned long timer0_millis = 0;
static unsigned char timer0_fract = 0;

volatile uint8_t count;

ISR (TIMER0_OVF_vect)

{

    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }

    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

}

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;

    return m;
}

int main (void)

{
    DDRB |= (1<<0);
    TCNT0 = 0;
    count = 0;
    TCCR0B |= (0<<CS02) | (1<<CS01) | (1<<CS00); // PRESCALER 64
    TIMSK0 = (1<<TOIE0);
    sei();

    while(1)
    {
        millis() to uart.

    }

}

cross post https://stackoverflow.com/questions/53780848/using-of-millis-in-atmel-studio

The millis() function is defined in the Arduino Core for AVR architecture, specifically the wiring.c file.
You can see that timer0 is setup with various parameters for prescaling and interrupt triggering and handling of timer0 overflow such that a variable called timer0_millis contains the number of milliseconds since the sketch started.
The millis() function basically returns that timer0_millis value.
If you wish to make use of the function in AVR Studio, then you would need to include the same kind of timer0 setup and interrupt/overflow handling that the Arduino core does.

I have found example code,but isn't same.Can you write equivalent of code in above?for being example and my learning.Of course,If is this possible?Thanks.

I will not write it for you. It's already written in wiring.c

oh sorry,I hadn't seen wiring.c file.I have added to my project.But I am not using timer0_millis.Error: 'timer0_millis' undeclared (first use in this function).
What can I add wiring.c to my project?

You will need to read all of wiring.c, understand it, and then implement it in your own project. Arduino makes very simple the things which are complex on "pain" AVR programming. What is the reason you choose to use AVR Studio?

Because I am learning atmel studio.But now,I need to this function.No need to make it so difficult.Just,I want to counter like millis() which has forward direction.I need solution.

I'm not trying to be a jerk about it, but there is A LOT of complexity and options that are simplified by Arduino. In my answer, I said that millis() basically returns timer0_millis, however, that variable gets its value from an overflow-triggered interrupt service routine. There is no "just give code" answer -- to learn AVR Studio means to learn AVR architecture. Fortunately, wiring.c and the files it includes contain all you need to be able to implement millis() in your own project.

If wiring.c is enough for millis then you can give me code.just,copy and paste bro.I promise learn how is it work.But now,I really need.And I am trying to run part of wiring.c,I don't still run.Good days.

Asking for users to just give you code isn't a good way to get anything, especially an understanding of how it should work

You already got your answer @alexjla, it is time to study now, if you want to learn

@alexjla, I gave you on SO a link to AVR forum. there is the code https://www.avrfreaks.net/comment/907712#comment-907712


text:
In ESP-12E NodeMCU, what's the pin number of A0?
In ESP-12E NodeMCU, all digital pins can be called with a number. Here is the list:
static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t D9   = 3;
static const uint8_t D10  = 1;

So these two lines of code will do the same:
pinMode (D0, INPUT)
pinMode (16, INPUT)

What's the corresponding number for A0 (the only analog input of this board)?

The numeric value of A0 is 17, as defined here.
But unlike on an Arduino board, you can't use it as a digital pin. It only work for pin numbers 0-16.
If you are using as a parameter for analogRead, the numeric values would be 0 and 17, as seen here.
And as such, these three calls would do the same:
analogRead(A0);
analogRead(17);
analogRead(0);

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


text:
Arduino Modbus slave error
I am trying to use Arduino as Modbus- RTU slave and Raspberry Pi as a Modbus master I have interfaced Max485 (RS485 to TTL converter) with Arduino and Rs485 to USB converter in Raspberry Pi, Initially, I was able to send data from Arduino to Raspberry Pi, but the data seems to inconsistent and fails to read most times
I am using https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino for Arduino Minimal Modbus for raspberry pi
Connections:

DI(max485)- TX ( Arduino),
DE(max485) -D2 ( Arduino),
RE(max485) - D2( Arduino),
Ro(max485) - RX( Arduino),
Vcc(max485) -5v( Arduino),
Gnd (max485)- GND( Arduino)

code for Arduino
#include <ModbusRtu.h>
uint16_t au16data[6] = {};
Modbus slave(5,0,2);
void setup() {
  slave.begin(19200,SERIAL_8N2 );
 }
void loop() {
  au16data[0]=100;
  au16data[1]=200;
  au16data[2]=300;
  au16data[3]=400;
  au16data[4]=500;
  au16data[5]=600;
  slave.poll( au16data, 6 );
  delay(3000);
}

python code
import minimalmodbus
from datetime import datetime
import time

instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 5)
instrument.serial.baudrate = 19200
instrument.serial.bytesize = 8
instrument.serial.parity = minimalmodbus.serial.PARITY_NONE
instrument.serial.stopbits = 2
instrument.serial.timeout =6
instrument.mode = minimalmodbus.MODE_RTU

while(1):
    try:
        val = instrument.read_registers(0,6)
        # Registernumber, number of decimals
        print val
    except IOError:
        error_msg = "Failed to read from device"
        error_time = datetime.now()
        print "IO Error Time",error_time.isoformat(),error_msg

    except ValueError:
        error_msg = "Failed to read CRC"
        error_time = datetime.now()
        print "Value Error Time",error_time.isoformat(),error_msg
    time.sleep(2)

but now I am getting The exception of failed to read

why the delay in slave? it must run slave.poll to respond to requests from master

the array positions could be replaced by sensor values, some sensor do work slow for instance DHT11

time sensor reading as BlinkWithoutDelay example, but the slave must poll, the loop must run

even without the delay I am getting the exception of failed to read

on fritzing and in code you have DE as pin 2. in the wiring table in Question you have D4?

I made a mistake corrected that

Hint: Common ground missing. http://www.ti.com/lit/an/slla272c/slla272c.pdf


text:
Initialize and read from a PROGMEM array of pointers to PROGMEM arrays
I'm working on a project for the arduino uno for which I need multiple constant arrays of bytes. Such an array is initialized like so:
const byte charR[] PROGMEM = {
  B01111111,//top half
  B01111111,
  B01000100,
  B01000110,
  B01101111,
  B00111001,
  B00000000,
  B01111000,//bottom half
  B01111000,
  B00000000,
  B00000000,
  B01111000,
  B01111000,
  B00000000
};

This array represents the capital letter R. I read the nth byte of this array like so:
nth_byte = pgm_read_word(charR+n);

This is all fine and good so far, but now I need to take it a step further. I need to create the array message[]. I need to use message[] to read byte arrays in a certain sequence. For instance:
message[] = {
  charR,
  chare,
  charp,
  charl,
  chary,
  charspace,
  charp,
  charl,
  chare,
  chara,
  chars,
  chare
};

Each entry in message[] refers to a byte array that represents a character. Notice how multiples appear. This is kind of like a 2-D array, but I want to save progmem by only defining each character once.
How do I properly initialize message[]? Will I need to use pointers for this? How do I properly get the array size or yth byte of the xth entry in message[]?

const byte* const message[] PROGMEM =
to use an item, load it in RAM
strcpy_P(buffer, (byte*)pgm_read_word(&(message[i])));
source Arduino reference - PROGMEM

@bo-thompson, did it help?

Sorry for the delay, I've been separated from the microcontroller running this project for the last week. Hopefully I will return to it in the coming week and I will mark this as an answer as soon as I've verified that I can understand and use it.


text:
Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega
I used the code from this project... to build an oscilloscope-like project. It worked fine with Uno and Nano.
Later I tried to do the same with a Mega, but I don't know what's wrong. It's not working! Maybe due to some pin or port number mismatch (I think so...). Because it has some low level code like:
------------------------------------------------------
// set up 8 MHz timer on pin 9
pinMode (9, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
OCR1A =  0;       // output every cycle
---------------------------------------------------------

And like:
Data.Values[i]=PINC;

I have very little knowledge about these registers.
Please help me port this code to Mega and make it work...

There is some concept you would have to learn before you can go from Arduino Uno to Mega.
Because your project is designed to operate on Arduino Uno R3, the registers operations like below are specific to the microcontroller in Arduino Uno - in this case ATmega328P-PU - datasheet here
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
 TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
 OCR1A =  0;
You can find description of registers in mentioned datasheet in chapter 19. TC0 - 8-bit Timer/Counter0 with PWM
Now, you grab another datasheet - one which describes ATmega2560 (yes, this is microcontroller which is sitting in Arduino Mega), find corresponding pin (like OC1 in Uno - check the drawing below):

and find proper pin and corresponding register from ATmega2560 datasheet.
Take a look at the schematic picture first, select one of OCx pins and configure what is needed.
Pins from Aruino Mega with OCR functionality:

and

You need to learn what registers are, and what they can do. Can be a little demanding task, but believe me - this will give you supernatural powers in microcontrollers world ;)

Thank you very much for giving some idea about the origin of the problem, and definitely I will work on that. But, time being, I have some time constraints on the project. So, can anybody tell me how to set that 8MHz timer on any of mega pins... Also please give me some information on 'PINC'

@Thirumalesh Please realize that this is not a free design house, homework-answering service or an on-line technical encyclopedia, copied out to you on demand. People will help you take the next step if your question shows that you've done as much as you possibly could on your own - which your post doesn't.

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


text:
How should I customize UIPEthernet constants?
I am using UIPEthernet to get an Arduino Nano to drive an ENC28J60 Ethernet Shield for a UDP-based application. I'm customizing a number of its #define parameters to change default settings to save space, but I'm not sure I'm doing it correctly.  It's clearly designed to facilitate per-sketch customization, but things aren't quite working for me, and I can't tell if it's me doing it wrong, or if the customization doesn't quite do what I'm expecting.
Specifically, the comments at the top of utilities/uip-conf.h say:

uIP has a number of configuration options that can be overridden  for each project. These are kept in a project-specific uip-conf.h file and all configuration names have the prefix UIP_CONF.

So that sounds great - I've copied uip-conf.h into my sketch (into the top directory next to my other sources), adjusted it appropriately, and ... nothing changes.
Now, I'm #including <UIPEthernet.h> into my source files, and everything compiles using the Arduino IDE (v1.8.10). Looking in the library, I can see <UIPEthernet.h> includes <utilities/uipopt.h>, which in turn includes "uip-conf.h" (note the quotes). So I think it's intended to be picking up my local one. But it doesn't - it uses the original one from the library.
My understanding of #include "example.h" is that it looks for example.h relative to the current file location, (ie <utilities/uipopt.h>, so utilities/), so I'm actually seeing correct inclusion behaviour and now I don't see how this customization approach could ever work!
I tried adding the #include "uip-conf.h" to my own sources, and that sort of works for my sources, but of course doesn't affect the library .cpp files themselves which still see the original version.
I could probably drag the entire lib into my sketch and fix up the includes, but that seems like the wrong answer. It's extensively designed to be customizable. Do you know what steps need to be taken to do it please? (Or a pointer to some docs would be fine!) Thanks!

have you tried any of the example sketches?

@jsotola Yep, extensively whilst evaluating the library. But the examples don't flex the configuration options.

Creating a copy of the include file in sketch folder will not work. At library compilation the source files of sketch are not included. The "" for include is "search first in the same folder as the including file".
The project in the description of use of uip-conf.h is UIPEthernet. It includes the UIP library by Adam Dunkels and configures it with this file.

A project with UIPEthernet library can configure the library with options in uipopt.h. Most of the options in uipopt.h are defined as
#ifdef UIP_CONF_UDP_CONNS
#define UIP_UDP_CONNS UIP_CONF_UDP_CONNS
#else /* UIP_CONF_UDP_CONNS */
#define UIP_UDP_CONNS    10
#endif /* UIP_CONF_UDP_CONNS */

this allows to define the value on compiler command line as -D. Most IDEs enable to set project defines in project settings. Arduino IDE does not enable this yet, because it doesn't have a project configuration file.
With Arduino IDE you can add defines for platform or for board definitions with build.extra_flags in platform.local.txt or in boards.local.txt. Example for boards.local.txt for Arduino Mega:
mega.build.extra_flags=-DUIP_CONF_UDP_CONNS=20 -DUIP_CONF_MAX_LISTENPORTS=30
platform.local.txt and boards.local.txt must be in boards package folder nect to platform.txt and boards.txt.

A clear answer in the first line. Perspective and context follows, and then options and workarounds - and all before breakfast. Perfect answer, thank you, Juraj - again!


text:
What types of connectors should I use to connect an HC-06 to an Arduino?
I am new to electronics and I need to connect an Arduino Uno with an HC-06 Bluetooth module.
The problem is that I don't know what types of connectors I should use.
I know I need some Dupont wires but there are 3 types: male to male - male to female - female to female.
So my question is: what type of connector should I use?

Since you haven't shared a picture of your module, I guess that the module has 4 male pins on the pcb (if it has backplane).
And Arduino Uno pins are all female. So, "male to female" dupont cables would give you a go.
If you don't want to go with just the wires but ready to use connectors, there will be many options depends on what you expect from a connector in your setup.
Since you are new to electronics, with this module, believe me connector would be your least issue.

I'm not sure on the exact package of you HC-06. All of the ones I have are like this picture. If you have one like this, you will need male to female jumper cables. I would recommend a breadboard as well if you plan on connecting anything additional.

yeap mine is also like that

so with arduino uno + hc-06 + male to female i can connect right ?

Yep, the cables are named based on anatomy. The male one has the pins and the female has the receptacle. Male and female connect together. So, the arduino uno has female connectors which will require a male connector on one end of the cable. On the other end, the bluetooth module has male connectors which will require a female to plug into. So, male->female is the cable that you will need.   See also https://en.wikipedia.org/wiki/Gender_of_connectors_and_fasteners


text:
Passing reference to hardware between methods in custom class
I'm a C++ / Arduino newbie, trying to build a custom library for the first time. I created a unit called CDSensors.cpp, which has two methods, SetupSensor and ReadSensors. The sensor is a SparkFun accelerometer/magnetometer.
If there are any errors in the settings, the sensor returns all zeros for compass and accelerometer. If there is no pointer or other connection between the SetupSensor and ReadSensor methods, the sensor returns all zeros as if it hasn't been setup.
So I'm trying to pass a reference to the sensor library between the methods as shown with the Limu object in the code below. I now get mag data but the accelerometer returns all zeros so something in my object references is messing with the sensor setup? (the accelerometer works ok in the SparkFun demo code, on which my code is based).
Main.ino
#include <CDSensors.h>
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>

CDSensors* LSensors = &CDSensors     (0);
CDSerialPrint* LSerialPrint = &CDSerialPrint (0);
MPU9250_DMP Limu = MPU9250_DMP ();
unsigned long LTimeNow = 0;

struct meas {
  int BUx;
  int acc_x
};

struct meas r;

void setup() {
  LSensors->SetupSensors (Limu);
}

void loop() {
  LSensors->ReadSensors  (Limu, LTimeNow, r.BUx, r.acc_x);
  Serial.print((int) (r.BUx) );
  Serial.print((int) (r.acc_x) );
}

CDSensors.h
#ifndef CDSensors_h_h
#define CDSensors_h
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>

class CDSensors {
  public:
    CDSensors(int);
    static void SetupSensors(MPU9250_DMP *imu);
    void ReadSensors (MPU9250_DMP *imu, unsigned long& TimeNow, int&     BUx,int& BUy,int& BUz,int& acc_x,int& acc_y,int& acc_z,int& a0,int& a1,int& a2,int& a3 );
  private:
    int value;
};
#endif

CDSensors.cpp
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>
#include "CDSensors.h"

//MPU9250_DMP imu;
boolean       MPU9250_found = false;
unsigned long TimeNow = 0;
CDSensors::CDSensors(int givenValue) {
  value = givenValue;
}

static void CDSensors::SetupSensors(MPU9250_DMP imu) {
  if (imu.begin() != INV_SUCCESS) {
    while (1) {
      Serial.println("No MPU-9250 found, Check connections");
      delay(5000);
    }
  }
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);
}

void CDSensors::ReadSensors(MPU9250_DMP imu, unsigned long& TimeNow, int& BUx, int& acc_x) {
  TimeNow = millis();
  if (imu.dataReady()) {
    imu.update(UPDATE_ACCEL | UPDATE_GYRO | UPDATE_COMPASS);
  }
  BUx = imu.calcMag(imu.mx);
  acc_x = imu.calcAccel(imu.ax);
}

Is there a reason, why you are defining the MPU9250_DMP outside of your class and in your main sketch? If you declare it inside of the class as a member variable you can ditch the reference handling

Try passing the imu parameter by-reference (instead of by-copy), i.e. MPU9250_DMP& imu, to the SetupSensors and ReadSensors member functions.

@ChrisL When it was defined just in CDSensors class ithe sensor returned all zeros. I checked with local serialprint, I suppose somehow the connection between settings and reading data is lost.

@Nisse sorry tidied indents & typo, resolved your comment I think.

How die you define it in the class? Did you execute its constructor? If not, that might have been the problem

Can you post CDSensors.h?   I can't make any sense of CDSensors*     LSensors      = &CDSensors     (0); CDSerialPrint* LSerialPrint  = &CDSerialPrint (0);   As the warning says, you are taking the address of a temporary, something that ceases to exist at the end of that line.

Why are you using classes at all? Are there going to be lots of sensors? If so, making a member function static doesn't make any sense.

@Mikael, new to pointers, I tried MPU9250_DMP* imu and MPU9250_DMP *imu Either way I get  this error - no known conversion for argument 1 from 'MPU9250_DMP' to 'MPU9250_DMP& imu gives the same sub-sensor returning zeros problem.

@Nick re why classes - reason for moving this bit of code into a seperate .cpp unit is that the program is about to get a lot more complex, plenty of maths and GPRS comms, so the sensor setup/read seemed like a logical chunk to move out of the main.ino I am presuming that the seperate .cpp unit necesitates defining a class?

No, not at all.

And if you have changed the code, please post the amended code. We can't debug code we can't see.

Change static void SetupSensors(MPU9250_DMP *imu); to static void SetupSensors(MPU9250_DMP& imu); in both source and header file. Do the same change to ReadSensors. BW why are you using static for SetupSensors.

I don't think you are creating instances of these classes correctly. Instead of:
CDSensors*     LSensors      = &CDSensors     (0);
CDSerialPrint* LSerialPrint  = &CDSerialPrint (0);
MPU9250_DMP   Limu = MPU9250_DMP ();

How about:
CDSensors LSensors (0);
CDSerialPrint LSerialPrint (0);
MPU9250_DMP Limu;

I can't get your code to compile, but what I suggest looks a lot simpler.

Is your intention here:
if (imu.begin() != INV_SUCCESS)
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);

.. to really be:
if (imu.begin() != INV_SUCCESS)
  {
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);
  }

The indentation suggests so.

if I understood correctly the class is created on startup with
       CDSensors* LSensors = &CDSensors (0);

and is then persistent.

LSensors is a persistent pointer but CDSensors (0) is a temporary object created for the purpose of doing an assignment. For example:
int foo = 2 + 3;

Now the compiler calculates 2 + 3 (giving 5), assigns that to foo, and then discards the temporarily-calculated 5 used to do the assignment.
In your case CDSensors (0) calls the constructor for CDSensors, creating a temporary object. Then the "&" operator takes its address (somewhere on the stack I would guess). This address is copied into LSensors. Then the object is destroyed because its lifetime is over. The compiler even warns you this is happening:
 CDSensors*     LSensors      = &CDSensors     (0);
                                                 ^
sketch_may07a:5: error: taking address of temporary [-fpermissive]

That means the pointer is now invalid because the underlying object (that it is pointing to) has now been discarded.

I've even seen people do something like this quite a bit:
     CDSensors LSensors = CDSensors (0);

This isn't so bad because pointers aren't involved, but it still involves making a temporary instance of the class, then copying that into LSensors, and discarding the original one.
This is how to make a new instance of a class:
 CDSensors LSensors (0);   // the actual class, not a pointer

Or if you want a pointer:
 CDSensors * pLSensors;  // a pointer to the class (initially NULL)

Then in setup you create the instance:
pLSensors = new CDSensors (0);

thanks Nick, I tried this variation, it also compiles ok, but still have the same problem with the accl sub-sensor returning zeros

Add some debugging prints, don't thrash around adding pointers in the hope it will fix things.

Also see my amended answer.

Re if (imu.begin() != INV_SUCCESS) sorryyyyyyy typo in code at the top, which is now corrected.

I wondered if it might be to do with constructors, but if I understood correctly the class is created on startup with CDSensors* LSensors  = &CDSensors (0); and is then persistent. (unlike what i'm used to in delphi where you can type create/destroy all over the place).

Pointers - right -  I suppose adding pointers saves resources but unlikely to fix a runtime bug.

See amended answer.

The third part is misleading. There's no point in talking about "invalid pointer", since the code itself is simply invalid: the language does nog allow applying built-in & to a temporary. This is non-compilable. I don't know why the OP keeps guessing whether the object is persistent or not. There's no point is that when the code is simply non-compilable.

The fourth part is misleading as well. Even in the old "classic" C++ the copy-initialization syntax is immediately interpreted as direct-initialization when the types on the LHS and RHS are the same. There's no temporary object created, there's no copying performed. The constructor arguments are immediately passed to the LHS object. Copy-initialization syntax in this case is repetitive, bulky and unnecessary, but it does not suffer fron inefficiencies you describe in your answer. It is fully equivalent to the "short" version.

I would add to AnT's comment in this way, why pass the Limu as a parameter to both functions when the constructed object is already global.  Just use Limu and remove the parameter in both methods.  If you really wanted to be 'OO' about it, you would pass Limu to the constructor. As it is you are passing an int that looks like is never used which I don't understand unless there is code missing or is planned for later.


text:
Typedef not accepted as a data type in a function?
I know I'm in a C++ compiler, but I typically create a typedef from structures, probably a holdover from earlier C programming. So this has my head spinning. I create a Typedef from a structure. After that, I have no trouble declaring a global or local version of that structure anywhere in a function, or outside of all functions (global). But when I try to create a function with this typedef as an arg, or even a function arg with a pointer the such a typedef, the compiler complains (and the complaint doesn't seem to make sense). Example...
typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint16_t codeID;

// a few more vars

  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
  uint8_t future[10];
} Sunstates;

So now, this typedef seems as good as any other. Either of these statements compile fine...
Sunstates sunStates;
Sunstates * pSS = &sunStates;

But if I now try to create a function, with either an instance of this data type or a pointer to it, like so...
void systemDataVerify(Sunstates *pST) {  }

The Arduino compiler offers this confusing error message...

Arduino: 1.8.3 (Windows XP), Board: "Arduino Nano, ATmega328"
SolarControler_21a:393: error: variable or field 'systemDataVerify'
declared void
void systemDataVerify(Sunstates *pSS) { }
                   ^

SolarControler_21a:393: error: 'Sunstates' was not declared in this
scope
SolarControler_21a:393: error: 'pSS' was not declared in this scope
void systemDataVerify(Sunstates *pSS) { }
exit status 1 variable or field 'systemDataVerify' declared void

The fact that it doesn't like me declaring a function void is odd, but not as troubling as it calling my function a 'variable or field' and definitely not as strange as it saying my datatype (Sunstates) was NOT "declared in this scope." The data type was defined immediately before the function... and the fact I could declare both instances of the type AND pointers to it kind of proves it exists within the scope. Can someone help me understand why the compiler is complaining?
Edit... I was asked to include a short sketch that shows the problem...
uint8_t somefunction() {
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
} Sunstates;

Sunstates sunStates; // create an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p) {
  return;
}

void setup() {
  // put your setup code here, to run once:
}

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

Now... I have discovered that if I remove the 'somefunction()' definition before the Structure definition, the problem goes away. And I'm using Arduino 1.8.3 to compile this.

Please make a small sketch that shows the problem. It compiles when I try to make a small sketch.

Check the syntax of whatever precedes your function definition. This sounds like the compiler lost sync and isn't expecting a function definition to start here. As a test, can you define a different function here instead?

Well I actually had a really complex function before it, and the project was already pretty huge. Thats why I created such a small sketch to isolate the problem, with the simplest function I could think of. there's nothing really before it. It was easy enough to eliminate all functions before my structure, but it does seem like a compiler bug at this point.

I do not get this error in Arduino IDE 1.8.5 with snippet you provided, but I get it in Sloeber Eclipse plugin. The later attached sketch fails to compile in Arduino IDE 1.8.5 too.
The error is in Arduino build chain ino to cpp conversion for the C++ compilation. Put the typedef declaration into .h file and include it in ino.
EDIT: Details are in my newer answer to a similar problem.

Hmm.. well all I've ever used was the official Arduino 1.8.3 (though I've been dying to try that Eclipse plugin!). Well thanks! I'll try that .H file approach. But the fact it compiles for YOU at least tells me I'm not crazy, and that the code SHOULD be compiling. For now, I've found a work-around... I can just make my function take a void * , and then within the function body make a new pointer to that struct type, and finally cast the passed void pointer to initialize it. That seems to work.

I'm accepting this answer, even though I haven't upgraded my IDE yet, because putting the structure and typedef near the top of the file ( before any functions are declared, but after all other header files) solves the issue. Still, I've updated my post with a short sketch that illustrates the problem reliably, and I'd be interested in a confirmation that your 1.8.5 does compile it without error. Not that I don't trust compiler improvements, but my current project is complex enough that regressive testing is very time consuming, So I'd rather save that upgrade for a "rainy day" :-)

the attached sketch fails in IDE 1.8.5 too

But putting the typedef struct in an H file works? If so, between that suggestion, and my workaround, we till at least have an answer.

yes .h works. it is the same like putting the typedef to the top of the ino

So now the only remaining question, if my original sketch was not breaking any C/C++ rules, do you think maybe I should post this observation in the official Arduino.cc forum? There seem to be a lot of folks there who directly work on development, and might be interested in making a future compiler fix.

it is ino to cpp conversion problem. the coversion does, if I am not mistaken,  the arduino-builder https://github.com/arduino/arduino-builder

one of the things done by the builder is creating forward declaration of functions. my hypothesis is that your order of function, variable and typedef leads to wrong order of forward declarations

It's not a compiler bug, @alm.
If I take the Minimal, Reproducible Example provided by the OP, and compile it, and then look at the intermediate file produced by the IDE (not the compiler) you can see what is happening:
#include <Arduino.h>
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
uint8_t somefunction();
#line 18 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
void systemDataVerify(Sunstates *p);
#line 22 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
void setup();
#line 26 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
void loop();
#line 1 "/home/nick/Arduino/typedef_issue/typedef_issue.ino"
uint8_t somefunction() {
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
} Sunstates;

Sunstates sunStates; // create an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p) {
  return;
}

void setup() {
  // put your setup code here, to run once:
}

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

You will notice that the IDE "helpfully" produces function prototypes for your functions, and that the order in which it does that means that it puts the prototype for void systemDataVerify(Sunstates *p); before the typedef for the structure, leading to the error message.
The solution is simple. Put your own function prototype into your source, thus telling the IDE to not bother, like this:
uint8_t somefunction() {
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag; // lets me know why we're being reset.
} Sunstates;

void systemDataVerify(Sunstates *p);  // <<<<<< ---- function prototype

Sunstates sunStates; // create an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p) {
  return;
}

void setup() {
  // put your setup code here, to run once:
}

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

Looks like a compiler bug to me. Perhaps that should be passed along to the compiler people.

It's not a bug in the compiler, arguably it is an idiosyncrasy of how the IDE works. No point in submitting bug reports to the compiler-writers. You could conceivably raise an issue on Github for the IDE complaining about the way they generate function prototypes.

For more information see my answer here. In it I mention:

The function prototype generation however can lead to obscure error messages if you are not careful.

The dreaded automatic function prototype generator strikes again!

Here I am 5 years after the OP with the same issue. I'm on Arduino IDE Version: 2.2.1 Date: 2023-08-31T14:35:44.802Z. And I'm using the Adafruit ATSAMD21 M0.
Note that my offending typedef is already in a .h file placing it after everything it needs and before any use so that fix doesn't work for me.
I've discovered what does work around this issue:
Changing this:
int storeXXX( framBlock *fb ) {
To this:
int storeXXX( struct _framBlock *fb ) {
That is, use the 'real' type for function arguments.
The typedef appears to be Ok everywhere else, locals, globals, before and after the point of the error report, etc. Just not as a function argument.
Note that the OP found a similar solution in using void * as the type of his typedef'd pointer. I saw no mention of using the 'real' type which is a more straight forward fix.
Looks like a compiler bug to me. Perhaps that should be passed along to the compiler people.

See my answer.


text:
NRF24l01 receiving only zeros
I want to transmit and receive data with the help of NRF24l01 modules. I tried to deliver joystick values from UNO to UNO but I have trouble about it.
In receiver side I have only zeros. I have been connect pins according to pin out orders.
ce--9
csn----10
sck----13
mosi----11
miso-----12

on both side. I am using module adapter to provide constant current and feeding with 3.3 volt and 5 volt another one. Both did not work. I bought new modules and adapters and connected 3.3 volt but nothing changed. I could not understand the problem help me please. Here is are my sketches:
RECEIVER

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int data[3];
void setup()
{
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.openReadingPipe(1, pipe);
  radio.startListening();
  radio.setPALevel(RF24_PA_MAX);
}

void loop() {
  if ( radio.available() ) //Eğer sinyal algılarsan...
  {

    radio.read( &data, sizeof(data) );

    Serial.print("data[0]=");
    Serial.println(data[0]);
    Serial.print("data[1]=");
    Serial.println(data[1]);
    delay(300);
    radio.stopListening();

  }
  else {
    Serial.println("no signal");
  }
}

TRANSMITTER
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#define PIN_ANALOG_X 0
#define PIN_ANALOG_Y 1
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int data[2];

void setup() {

  // Start serial because we will observe values at serial monitor
SPI.begin();
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(pipe);
  radio.setPALevel(RF24_PA_MAX);
}

void loop() {

  // Print x axis values

  Serial.print("x: ");

  Serial.println(analogRead(PIN_ANALOG_X));

  // Print y axis values

  Serial.print("y: ");

  Serial.println(analogRead(PIN_ANALOG_Y));
  data [0] =map( analogRead(PIN_ANALOG_X),0,676,0,255);
  data [1] = map(analogRead(PIN_ANALOG_Y),0,676,0,255);

 radio.write( &data, sizeof(data) );
  Serial.println("data0");
  Serial.println(analogRead(PIN_ANALOG_X));
  Serial.println("data1");
  Serial.println(analogRead(PIN_ANALOG_Y));

Serial.println(data [0]);
Serial.println(data [1]);
  // Some delay to clearly observe your values on serial monitor.

  delay(300);

}

Why do you want to receive 3 ints at the receiver but you send 2 ints at the transmitter? Also why  radio.stopListening(); after one packet is received?

Actually ı found some codes from internet and re-arrange them. At the begining codes that ı found were not containing  radio.stopListening(); command and also it was not working. I wrote it because of ı thought it could be problem but it did not work despite of it.
int data[2]; is a mistake and ı re-arranged it as int data[3];

But at the transmitter side you send a int data[2] array, so it also has to be the same at the receiver. I would also remove the Serial.println("no signal"); in the receiver as to not spam the console. Do you then see any output in the receiver?

I delete the Serial.println("no signal"); and wrote int data [2] at both side but nothing has changed , at receiver side ı have still zeros

"Have zeroes" meaning it prints "data[0]=0 data[1]=0"?

yes at receiver's seril port screen ı have that;
data[0]=0;
data[1]=0;

So th data reception works, because radio.available() returned true and read the data. Are the source data at the transmitter also 0? How did you connect the transmitter to the joystick?

ı am using joystick shield v1.a. I am trying to transmit joystick values hence source data are not zero.There is a place to nrf24l01 and ı directly connected to this place but ı have also tried to connect into pins of shield with same configuration of receiver but nothing has been changed.

Again, what does the transmitter print when it sends data?

transmitter print joystick values as data[0]=329; and data[1]=335; but receiver prints data[0]=0; data[1]=0;


text:
Will this code for braking of dc motor using sensor work?

#define trigPin 13
#define echoPin 14
#define e1 10  // Enable Pin for motor 1
#define t1 8   // Control pin 1 for motor 1
#define t2 9   // Control pin 2 for motor 1
#define led 3
#define led2 5
#define buzzer 4

float duration,distance;
#include<SoftwareSerial.h>

void setup() {
 Serial.begin(9600);
 pinMode(trigPin,OUTPUT);
 pinMode(echoPin,INPUT);
 pinMode(e1, OUTPUT);
 pinMode(t1, OUTPUT);
 pinMode(t2, OUTPUT);

}

void loop() {
  digitalWrite(e1, HIGH);
  digitalWrite(t1, HIGH);
  digitalWrite(t2, LOW);

  digitalWrite(trigPin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin,LOW);

duration=pulseIn(echoPin,HIGH);
distance=(duration/2)*0.0343;
Serial.print("Distance= ");
if(distance>=400||distance<=2)
{
  Serial.println("out of range");
}
else if(distance<=100&&distance<=50)

{
  digitalWrite(led,HIGH);
  delay(1000);
  analogWrite(e1,157);
  digitalWrite(t1,HIGH);
  digitalWrite(t2,LOW);
  delay(500);
}
else if(distance<=50&&distance>=25)
{
  digitalWrite(buzzer,HIGH);
  delay(100);
  analogWrite(e1,56);
  digitalWrite(t1,HIGH);
  digitalWrite(t2,LOW);
}
else if(distance<=25&&distance>=10)
{
  digitalWrite(led2,HIGH);
  delay(100);
  analogWrite(e1,0);

}
else if(distance<=390&&distance>=100)
{  digitalWrite(e1, HIGH);
  digitalWrite(t1, HIGH);
  digitalWrite(t2, LOW);

}

delay(500);
}

Have you tested the code? How does it behave different, than you expect? And you should really add a complete description, what the desired behavior is. Just the title is not enough. Please put some effort into writing your question with all the information needed

you do not use a sensor to brake a motor ... you use a motor driver that is controlled by the program ... the sensor is used only for input ... decisions about motor braking can be made as a result of the input .... since you said nothing about what parameter affects braking, your question is not answerable

Please take the [tour], learn how to [ask], and then [edit] your question with additional informations. You will get much better answers then. ;-)


text:
OLED DISPLAY USING SPI
My display is not responding to this code. Help please
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_MOSI 10
#define OLED_CLK 9
#define OLED_DC 12
#define OLED_CS 13
#define OLED_RESET 11
Adafruit_SSD1306 display(OLED_MOSI,OLED_CLK,OLED_DC,OLED_CS,OLED_RESET);

void setup(){
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();

  display.setTextSize(1);
  display.setCursor(30,30);
  display.print("Hello WOrld");
  display.display();
  }

  void loop(){

    }

what does this mean? not responding

There is no code, that would respond to user actions. It just displays hello world, nothing else.

sorry what i meant was that the display is not turning on. I ran the adafruit example and the display qorks fine. So is there a problem in the code? i copied this code from a youtube video

Pin definitions in your code seem to be mixed up. If Adafruit example works fine with your setup, you should keep the pin definitions Adarfruit uses:
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

Also, you are using a deprecated constructor. It is recommended to use a constructor which explicitly specifies display size.


text:
How to send big data (long string) from PC to Arduino using Bluetooth
One of the requirements of my projects is to send data from my application to the Arduino robot.
I have windows 10, and my robot is Arduino Uno.
The Bluetooth I'm using on my robot is HC-06.
The app side:

I'm writing some script (With the format I've created)
Then converting it into JsonString
Opening the port and sending a start communication signal.
Sending the JsonString, each represents another command and they're separated with a special character that can't be written in the script.
Here's the problem, I tried sending string length of 256 bytes (not a JsonString) just to test the Bluetooth.

The test I did in my robot

I read the data
Turned the led on
Waited (data.length() / 10) seconds
Turned the led off

For my data of 256 bytes, the led was ON for 12.8 seconds, which is 128 bytes. And sometimes when I changed some stuff The time was 6.4 seconds.
C# (Application)
string data = @"0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101";

protocolBT.BTcontroller.OpenPort();
protocolBT.BTcontroller.SendChar(ProtocolBT.COM_OpenChar);
protocolBT.BTcontroller.SendBigData(data);
protocolBT.BTcontroller.ClosePort();

The Bluetooth Class
public class BluetoothController
{
    private readonly SerialPort _serialPort;

    public BluetoothController(string portName, BaudRate baudRate)
    {
        _serialPort = new SerialPort(portName, (int)baudRate, Parity.None, 8, StopBits.One);
    }

    public static bool IsBluetoothSupported()
    {
        return BluetoothRadio.IsSupported;
    }

    public static void SetConnection()
    {
        if (IsBluetoothSupported())
        {
            if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
        }
    }

    public void OpenPort()
    {
        try
        {
            _serialPort.Open();
        }
        catch(IOException IOex)
        {
            throw IOex;
        }
    }

    public void ClosePort()
    {
        _serialPort.Close();
    }

    public void SendData(string msg)
    {
        try
        {
            if (_serialPort.IsOpen)
            {
                byte[] data = Encoding.UTF8.GetBytes(msg);
                _serialPort.Write(data, 0, data.Length);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void SendBigData(string msg)
    {
        try
        {
            if (_serialPort.IsOpen)
            {
                foreach (char ch in msg)
                {
                    SendChar(ch);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void SendChar(char ch)
    {
        try
        {
            if (_serialPort.IsOpen)
            {
                byte[] data = Encoding.UTF8.GetBytes(new char[]{ ch });
                _serialPort.Write(data, 0, data.Length);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

}

And this is my Arduino test code
#include <SoftwareSerial.h>

#define RX 10
#define TX 11
SoftwareSerial BT = SoftwareSerial(RX, TX);

String startCom = "»";

String MessageStart = "";
bool isListen = false;
String data = "";

int yellow = 12;

void setup()
{
  // Define LED
  pinMode(yellow, OUTPUT);

  // Test yellow led
  digitalWrite(yellow, HIGH);
  delay(1000);
  digitalWrite(yellow, LOW);

  // Define Bluetooth
  pinMode(RX, INPUT);
  pinMode(TX, OUTPUT);
  BT.begin(9600);
}

void loop()
{
  if(isListen == false)
  {
    readStartCommand();
  }
  else if(isListen == true)
  {
    readAllData();

    int len = data.length();
    if(len > 0)
    {
      robotLedOn(0); // Turn on the yellow led
      for(int i = 0; i < len; i++) // Wait (len * 0.1) second
      {
        delay(100);
      }
      robotLedOff(0); // Turn off the yelloe led
    }
  }
}

void readStartCommand()
{
  if(BT.available() > 0)
  {
    char ch = BT.read();
    Message += ch;

    if(MessageStart == startCom)
    {
      // Blink the yellow led if the start communication command recieved
      robotLedOn(0);
      delay(1000);
      robotLedOff(0);
      delay(2000);

      MessageStart = "";
      isListen = true;
    }
  }
}

void readAllData()
{

  while(BT.available() > 0)
  {
    data += BT.read();
  }
  isListen = false;
}

I tried to put the 256 bytes data manually to string in the Arduino and the timer was on 25.6 seconds.
So I think that there is a limit for the size of the data that Bluetooth can handle.
Note:

I need Json because I have complicated commands, not only leds. Some of the commands require multi-parameters from different types.
Soon I will get Arduino-Mega because I don't have enough pins in my Uno.

Tried:

Change the timeout, it still stops receiving at 128 bytes.
with read() and setTimeout(100-2000) Timer result: 12.8 seconds
With readString() and setTimeout(100-2000) Timer result: 6.4 seconds
My WriteBufferSize in the PC Bluetooth is 2048 bytes. So I'm pretty sure that all the data is sent.
Different Baud Rates and using the Library instead of the
The only change is that now the timer stops at 15.5 seconds...
Use BT.flush() and all my data is sent 100% for sure, the problem is in receiving in my Arduino. I think there is a buffer limit for the data...
Using another Bluetooth device, still the result is 15.5 seconds instead of 25.6 seconds.

why are using JSON? ..... why don't you simply use single byte commands with single byte data such as, for example  L10 or L:1:0 which could mean LED 1 off ?

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

For any communication you have to indicate your packet end somehow. You can use termination character ot fixed data length. And you have to read data from serial port on Arduino side until receive the termination character ot reach the packet length.

timeout is not applied for available() and read() that is why your code stops reading at a gap in data flow. are the coming in until you blink the LED 3 seconds? then you loose data there