text:
Arduino array error
I'm writing a program that has a sub program that saves values to an array, but the sub program that saves the values to the array comes back with an error telling me that the array isnt declared in that scope.
I'm fairly new to this and self taught but even when I try and pass the array into the sub program I get the same error. I'm sure its a fairly simple obvious error I'm making but I just cant get it to work.
If anyone sees any other errors or better ways for me to write any of this any help would be greatly valued as I'm still not confident on what I'm supposed to be doing.
#include <HX711.h>

#include <Wire.h>  // IC2 communication

#include <LiquidCrystal_I2C.h>  //LCD
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

int max_load;
int interval;
int max_load_prev;
int interval_prev;
int mode;
int handle_weight;
int tip_weight;
int stop1;
int mode_previous;
int interval_sum;

int mode1 = 53;
int mode2 = 51;
int mode3 = 49;
int start1 = 39;
int start2 = 37;
int increment = 47;
float potentiometer1 = A0;
float potentiometer2 = A1;
int tare_1 = 45;
int tare_2 = 43;

//stepper motor controller
int stepPin = 12;
int dirPin = 13;

//sensor readings
  HX711 tip_read;
  HX711 handle_read;
  int DOUT_tip = 6;
  int DOUT_handle = 5;
  int CLK_tip = 4;
  int CLK_handle = 3;

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

  lcd.init();
  lcd.backlight();

  //saving to array//
  float data_storage_array[600][3];

  pinMode(mode1, INPUT);
  pinMode(mode2, INPUT);
  pinMode(mode3, INPUT);
  pinMode(start1, INPUT);
  pinMode(start2, INPUT);
  pinMode(increment, INPUT);
  pinMode(stop1, INPUT);
  pinMode(potentiometer1, INPUT);
  pinMode(potentiometer2, INPUT);

  //sesnor readings
  tip_read.begin(DOUT_tip, CLK_tip);
  tip_read.set_scale(55);// change to calibration factor
  handle_read.begin(CLK_tip,CLK_handle);
  handle_read.set_scale(55);// change to calibration factor

  pinMode(tare_1, INPUT);
  pinMode(tare_2, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  mode_previous = 0;
  interval = 25;
  max_load_prev = 0;
  interval_prev = 0;
  interval_sum = 0;
  while (digitalRead(start1) == 0) {
    if (digitalRead(mode1) == 1) {
      mode = 1;
    }
    if (digitalRead(mode2) == 1) {
      mode = 2;
    }
    if (digitalRead(mode3) == 1) {
      mode = 3;
    }
    if (mode_previous != mode) {
      Display_mode_set_up(mode);
      mode_previous = mode;
    }
    if (digitalRead(increment) == 1) {
      delay(500);
      if (interval >= 1000) {
         interval = 25;
      }
      else if (interval < 1000) {
        interval = interval + 25;
      }
    }
    max_load = max_load_reading();
    if (max_load_prev != max_load or interval_prev != interval){
      Display_value_set_up(max_load, interval, mode);
      max_load_prev = max_load;
      interval_prev = interval;
    }
    Display_output(handle_weight, tip_weight);

  tare_one();
  }
  if (mode == 1) {
    mode_one(max_load, tip_weight);
  }
  else if (mode == 2) {
    mode_two(max_load, interval, handle_weight, tip_weight);
  }
  else if (mode ==3) {
    mode_three(max_load, interval, handle_weight, tip_weight);
  }
  Pause_stop();
}

//---SUB ROUTINES---

void mode_one(int max_load, int tip_weight) {
  tip_weight = read_tip();
  while (tip_weight < max_load) {
    tip_weight = read_tip();
    turn_motor();
    Pause_stop();
    Display_output(handle_weight, tip_weight);
  }
}

void mode_two(int max_load, int interval, int handle_weight, int tip_weight) {
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip;
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    while (digitalRead(start2) == 0) {
      delay(1);
    }
  }
  send_values_to_pc();
}

void mode_three(int max_load, int interval, int handle_weight, int tip_weight) {
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load) {
    while (tip_weight < aim_value) {
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    delay(10000);
  }
  send_values_to_pc();
}

void tare_one() {
  if (tare_1 == HIGH) {
    tip_read.tare();
  }
  if (tare_2 == HIGH) {
    handle_read.tare();
  }
}

void turn_motor() {
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(500);
}

int read_tip() {
  int weight;
  weight = tip_read.get_units();
  return weight;
}

int read_handle() {
  int weight;
  weight = handle_read.get_units();
  return weight;
}

void save_to_array(int interval_sum) {
  data_storage_array[interval_sum][0] = interval_sum;
  data_storage_array[interval_sum][1] = tip_read.get_units();
  data_storage_array[interval_sum][2] = handle_read.get_units();
  interval_sum = interval_sum + 1;
}

void send_values_to_pc() {
}

int max_load_reading() {
  int KG_value;
  int g_value;
  int load_max;
  KG_value = analogRead(potentiometer1);
  g_value = analogRead(potentiometer2);
  KG_value = KG_value * 2;
  KG_value = KG_value/ 100;
  KG_value = round(KG_value);
  KG_value = KG_value* 100;
  g_value = g_value/ 10;
  g_value = round(g_value);
  if (g_value >= 100){
    g_value = 99;
  }
  load_max = KG_value + g_value;
  return load_max;
}

void Pause_stop() {
  if (digitalRead(stop1) == 1){
    delay(1000);
    while (digitalRead(start1) == 0){
      if (digitalRead(stop1) == 1){
        motor_unwind();
      }
      else{
        delay(100);
        lcd.setCursor(0, 2);
        lcd.print("Program Paused");
      }
    }
    lcd.setCursor(0, 2);
    lcd.print("                    ");
  }
}

void motor_unwind() {
  tip_weight = read_tip();
  while (tip_weight < 100) {
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  int count = 100;
  while (count > 0) {
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
    count = count -1;
  }
}

void Display_mode_set_up(int mode) {
  lcd.setCursor(0, 0);
  if (mode == 1) {
    lcd.print("Mode: Max           ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:---");
  }
  if (mode == 2) {
    lcd.print("Mode: Incrimental    ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  if (mode == 3) {
    lcd.print("Mode: Automatic      ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  lcd.setCursor(0, 3);
  lcd.print("Tip:");
  lcd.setCursor(9, 3);
  lcd.print("Handle:");
}

void Display_value_set_up(int max_load, int interval, int mode) {
  if (mode == 1) {
    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);
  }
  if (mode == 2 or mode == 3) {

    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);

    lcd.setCursor(17, 1);
    lcd.print("   ");
    lcd.setCursor(17, 1);
    lcd.print(interval);
  }
}

void Display_output(int handle_weight, int tip_weight) {
  tip_weight = read_tip();
  handle_weight = read_handle();
  lcd.setCursor(4, 3);
  lcd.print(tip_weight);
  lcd.setCursor(16, 3);
  lcd.print(handle_weight);
}

Google “C++ scope” and do some reading about what variable scope means.  It will all make sense pretty quick.

You are declaring float data_storage_array[600][3] in setup(), and using it in another function, that can't "see" it.
The simplest way of making it work is making your array global by declaring it at the top in the section where you declare other variables like max_load.

As others have mentioned, your array is out of scope and can only be used in the setup() function. I have moved this out of the setup() function and into the global variable section.
I am also cautious of how much SRAM you were using with your (600 x 3 =) 1800 float elements. So I have changed it to ints and reduced it to 250 x 3. You have put down that you are using the Arduino Mega, so this could be expanded further if necessary.
Your variable interval_sum was set to increment with no upper limit. This means you would end up going beyond the limits of the array. I have fixed this.
I have reviewed your code briefly and added some fixes and some comments. It is untested. I hope this helps you.
#include <HX711.h>
#include <Wire.h>  // IC2 communication
#include <LiquidCrystal_I2C.h>  //LCD

LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

int max_load;
int interval;
int max_load_prev;
int interval_prev;
int mode;
int handle_weight;
int tip_weight;
int stop1;
int mode_previous;
int interval_sum;

const int mode1 = 53;    // <-- added the const keyword to all pin definitions as they dont change
const int mode2 = 51;
const int mode3 = 49;
const int start1 = 39;
const int start2 = 37;
const int increment = 47;
const int potentiometer1 = A0;    // <-- Changed to int as it is only a pin definition
const int potentiometer2 = A1;    // <-- Changed to int as it is only a pin definition
const int tare_1 = 45;
const int tare_2 = 43;

//stepper motor controller
const int stepPin = 12;
const int dirPin = 13;

//sensor readings
HX711 tip_read;
HX711 handle_read;
int DOUT_tip = 6;
int DOUT_handle = 5;
int CLK_tip = 4;
int CLK_handle = 3;

//saving to array//
int data_storage_array[250][3];    // <-- Moved before setup(). Changed to int. Reduced to 250x3 elements.

void setup() {
  // put your setup code here, to run once:
  lcd.init();
  lcd.backlight();

  pinMode(mode1, INPUT);
  pinMode(mode2, INPUT);
  pinMode(mode3, INPUT);
  pinMode(start1, INPUT);
  pinMode(start2, INPUT);
  pinMode(increment, INPUT);
  pinMode(stop1, INPUT);
  pinMode(potentiometer1, INPUT);
  pinMode(potentiometer2, INPUT);

  //sesnor readings
  tip_read.begin(DOUT_tip, CLK_tip);
  tip_read.set_scale(55);// change to calibration factor

  handle_read.begin(CLK_tip,CLK_handle);
  handle_read.set_scale(55);// change to calibration factor

  pinMode(tare_1, INPUT);
  pinMode(tare_2, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  mode_previous = 0;
  interval = 25;
  max_load_prev = 0;
  interval_prev = 0;
  interval_sum = 0;
  while (digitalRead(start1) == 0){
    if (digitalRead(mode1) == 1){
      mode = 1;
    }
    if (digitalRead(mode2) == 1){
      mode = 2;
    }
    if (digitalRead(mode3) == 1){
      mode = 3;
    }
    if (mode_previous != mode){
      Display_mode_set_up(mode);
      mode_previous = mode;
    }
    if (digitalRead(increment) == 1){
      delay(500);
      if (interval >= 1000){
         interval = 25;
      }
      else if (interval < 1000){
        interval = interval + 25;
      }
    }
    max_load = max_load_reading();
    if (max_load_prev != max_load or interval_prev != interval){
      Display_value_set_up(max_load, interval, mode);
      max_load_prev = max_load;
      interval_prev = interval;
    }
    Display_output(handle_weight, tip_weight);
    tare_one();
  }
  if (mode == 1){
    mode_one(max_load, tip_weight);
  }
  else if (mode == 2){
    mode_two(max_load, interval, handle_weight, tip_weight);
  }
  else if (mode ==3){
    mode_three(max_load, interval, handle_weight, tip_weight);
  }
  Pause_stop();
}

//---SUB ROUTINES---

void mode_one(int max_load, int tip_weight){
  tip_weight = read_tip();
  while (tip_weight < max_load){
    tip_weight = read_tip();
    turn_motor();
    Pause_stop();
    Display_output(handle_weight, tip_weight);
  }
}

void mode_two(int max_load, int interval, int handle_weight, int tip_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip;
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array();    // <-- Global variable removed
    aim_value = aim_value + interval;
    while (digitalRead(start2) == 0){
      delay(1);
    }
  }
  send_values_to_pc();
}

void mode_three(int max_load, int interval, int handle_weight, int tip_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array();    // <-- Global variable removed
    aim_value = aim_value + interval;
    delay(10000);
  }
  send_values_to_pc();
}

void tare_one(){
  if (tare_1 == HIGH) {
    tip_read.tare();
  }
  if (tare_2 == HIGH) {
    handle_read.tare();
  }
}

void turn_motor(){
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(500);
}

int read_tip(){
  int weight;
  weight = tip_read.get_units();
  return weight;
}
int read_handle(){
  int weight;
  weight = handle_read.get_units();
  return weight;
}

void save_to_array(){    // <-- Global variable removed
  data_storage_array[interval_sum][0] = interval_sum;
  data_storage_array[interval_sum][1] = tip_read.get_units();
  data_storage_array[interval_sum][2] = handle_read.get_units();
  if (interval_sum >= 249){   // <-- Added this if statement as there was no way to cap this number
      interval_sum = 0;
  }
  else{
      interval_sum = interval_sum + 1;
  }
}

void send_values_to_pc(){

}

int max_load_reading(){
  int KG_value;
  int g_value;
  int load_max;
  KG_value = analogRead(potentiometer1);
  g_value = analogRead(potentiometer2);
  KG_value = KG_value * 2;
  KG_value = KG_value/ 100;
  KG_value = round(KG_value);
  KG_value = KG_value* 100;
  g_value = g_value/ 10;
  g_value = round(g_value);
  if (g_value >= 100){
    g_value = 99;
  }
  load_max = KG_value + g_value;
  return load_max;
}

void Pause_stop(){
  if (digitalRead(stop1) == 1){
    delay(1000);
    while (digitalRead(start1) == 0){
      if (digitalRead(stop1) == 1){
        motor_unwind();
      }
      else{
        delay(100);
        lcd.setCursor(0, 2);
        lcd.print("Program Paused");
      }
    }
    lcd.setCursor(0, 2);
    lcd.print("                    ");
  }
}

void motor_unwind(){
  tip_weight = read_tip();
  while (tip_weight < 100){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  int count = 100;
  while (count > 0){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
    count = count -1;
  }
}

void Display_mode_set_up(int mode){
  lcd.setCursor(0, 0);
  if (mode == 1){
    lcd.print("Mode: Max           ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:---");
  }
  if (mode == 2){
    lcd.print("Mode: Incrimental    ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  if (mode == 3){
    lcd.print("Mode: Automatic      ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  lcd.setCursor(0, 3);
  lcd.print("Tip:");
  lcd.setCursor(9, 3);
  lcd.print("Handle:");
}

void Display_value_set_up(int max_load, int interval, int mode){
  if (mode == 1){
    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);
  }
  if (mode == 2 or mode == 3){

    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);

    lcd.setCursor(17, 1);
    lcd.print("   ");
    lcd.setCursor(17, 1);
    lcd.print(interval);
  }
}

void Display_output(int handle_weight, int tip_weight){
  tip_weight = read_tip();
  handle_weight = read_handle();
  lcd.setCursor(4, 3);
  lcd.print(tip_weight);
  lcd.setCursor(16, 3);
  lcd.print(handle_weight);
}


text:
Transmitting multiple values to an Arduino, and interpreting them with minimum delay
I am building an underwater robot, which can move up/down and forward/reverse, controlled by a Joystick.
The situation is like this :
A USB joystick is connected to a PC, the PC is connected to an Arduino via a tether cable (Ethernet), and the motors of the robot are connected to the Arduino.
The joystick I am using has two sticks, and I have decided to use one stick to control the up/down movement (actually, I'm using only one axis of that stick for this) and the second stick to control the left/right movement.
Whenever the user manipulates both sticks simultaneously (to achieve diagonal motion, for example), the joystick will send two signals, one after the other, one for each stick.
Keeping in mind the limited receiver buffer size of the Arduino, how do I program the Arduino so that it can understand the difference between the linear motion signal and the diagonal motion signal?
I am highly motivated to program this on my own. I just need an intuition for this.
A thought came to my mind is, to use the following strategy:
For my up/down stick value, I add a character such as U, followed by the integer joystick value, e.g. I send U4 to go up at speed 4. With some twitching, I can even send a down signal with the same preceding character U.
Similarly, for forward/backward, I send F to go forward/backward at speed 3. And for diagonal, I send something like T5 to go diagonally at speed 5.
My concern with this is that I will transmit two characters from the PC to the Arduino. Will the Arduino be able to read these two characters, interpret them and act accordingly, without a noticeable lag? Or is there an other better way?
This also makes me wonder, how commercial robots (such as commercial drones) handle such situations?
The movements the robot will make need to be quick. There should not be "visible" lag, that is, the user should not feel that the robot is responding after a couple of seconds.

How exactly are you transmitting data between PC and Arduino? As I understood, you use ethernet. But how are you sending and receiving the data itself? Simple packets? Web sockets? That can account for the biggest lag in the system

Take a look at CAN, most CAN controllers will have a buffer(s) to hold incoming packets. Each packet can have 8 bytes and you can run at a million bits a second. There are some that will go even faster but that would be good for the Arduino modules like the MPC2515 and they are not expensive.

I don't know about commercial drones, however your 'protocol' seems to be quite efficient, as it uses 4 bytes to send 2 values (e.g. U3F5) for Up with speed 3 and Forward with speed 5.
Let's assume values from 0-7. Then you can send them both in 8 bits/one byte:
H H H H V V V V
Where H is the horizontal speed (from -8 (000) to +7 (111), in total 16 possible values.
For the vertical speed you can do the same.
So within one byte you send both speeds (meaning also there is no lag).
In case you need more accuracy, than send two bytes: one byte with horizontal and one byte with vertical speed. Depending on the sending/receiving speed I doubt there is any lag.
Even with your protocol I doubt there is a lag, but the above is more efficient.
I'm sure even more efficient algorithms can be created, probably by using the difference with the previous value (like sending delta values).
Another algorithm that can be created, assuming there is a big chance that only one of the two directions is changed (either horizontal or vertical is) and having a high accuracy
D V V V V V V V

Where D is the direction (0 = horizontal, 1 = vertical) and V is the value/speed (-64 to +63, 7 remaining bits).

The delta values might be problematic if a byte went missing, but otherwise a very nice idea!

@NickGammon Thanks ... It is also possible reserve another bit for a 'change' vs ''next value is absolute' value ... but that decreases the number of bits for the delta.

source: Stack Exchange

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

sort: votes


text:
MPU9250 and MPU6050 not working with SAMD21 board
I am trying to use an MPU6050 with my SAMD21-based board (a LightAPRS W-2), but it doesn't work.
The sensor definitely works, as I can get data from another 3.3 Vlogic-level board, and the sensor works with a level shifter with an Arduino Uno.
I do not know what is wrong. My SAMD21 board I2C works fine with other devices, but both the MPU6050 and the MPU9250 don't work. Here is the code I use:
/***************************************************************************
* Example sketch for the MPU9250_WE library
*
* This sketch shows how to measure pitch and roll angles from the MPU9250.
* I have also included the corrected angle method for comparison.
*
* For further information visit my blog:
*
* https://wolles-elektronikkiste.de/mpu9250-9-achsen-sensormodul-teil-1  (German)
* https://wolles-elektronikkiste.de/en/mpu9250-9-axis-sensor-module-part-1  (English)
*
***************************************************************************/

#include <MPU9250_WE.h>
#include <Wire.h>
#define MPU9250_ADDR 0x68

/* There are several ways to create your MPU9250 object:
 * MPU9250_WE myMPU9250 = MPU9250_WE()              -> uses Wire / I2C Address = 0x68
 * MPU9250_WE myMPU9250 = MPU9250_WE(MPU9250_ADDR)  -> uses Wire / MPU9250_ADDR
 * MPU9250_WE myMPU9250 = MPU9250_WE(&wire2)        -> uses the TwoWire object wire2 / MPU9250_ADDR
 * MPU9250_WE myMPU9250 = MPU9250_WE(&wire2, MPU9250_ADDR) -> all together
 * Successfully tested with two I2C busses on an ESP32
 */
MPU9250_WE myMPU9250 = MPU9250_WE(MPU9250_ADDR);

void setup() {
  Serial.begin(115200);
  Wire.begin();
  if (!myMPU9250.init()) {
    Serial.println("MPU9250 does not respond");
  } else {
    Serial.println("MPU9250 is connected");
  }

  /* The slope of the curve of acceleration vs measured values fits quite well to the theoretical
   * values, e.g. 16384 units/g in the +/- 2g range. But the starting point, if you position the
   * MPU9250 flat, is not necessarily 0g/0g/1g for x/y/z. The autoOffset function measures offset
   * values. It assumes your MPU9250 is positioned flat with its x,y-plane. The more you deviate
   * from this, the less accurate will be your results.
   * The function also measures the offset of the gyroscope data. The gyroscope offset does not
   * depend on the positioning.
   * This function needs to be called at the beginning since it can overwrite your settings!
   */
  Serial.println("Position you MPU9250 flat and don't move it - calibrating...");
  delay(1000);
  myMPU9250.autoOffsets();
  Serial.println("Done!");

  /*  This is a more accurate method for calibration. You have to determine the minimum and maximum
   *  raw acceleration values of the axes determined in the range +/- 2 g.
   *  You call the function as follows: setAccOffsets(xMin,xMax,yMin,yMax,zMin,zMax);
   *  Use either autoOffset or setAccOffsets, not both.
   */
  //myMPU9250.setAccOffsets(-14240.0, 18220.0, -17280.0, 15590.0, -20930.0, 12080.0);

  /*  Sample rate divider divides the output rate of the gyroscope and accelerometer.
   *  Sample rate = Internal sample rate / (1 + divider)
   *  It can only be applied if the corresponding DLPF is enabled and 0<DLPF<7!
   *  Divider is a number 0...255
   */
  myMPU9250.setSampleRateDivider(5);

  /*  MPU9250_ACC_RANGE_2G      2 g    (default)
   *  MPU9250_ACC_RANGE_4G      4 g
   *  MPU9250_ACC_RANGE_8G      8 g
   *  MPU9250_ACC_RANGE_16G    16 g
   */
  myMPU9250.setAccRange(MPU9250_ACC_RANGE_2G);

  /*  Enable/disable the digital low pass filter for the accelerometer
   *  If disabled the bandwidth is 1.13 kHz, delay is 0.75 ms, output rate is 4 kHz
   */
  myMPU9250.enableAccDLPF(true);

  /*  Digital low pass filter (DLPF) for the accelerometer, if enabled
   *  MPU9250_DPLF_0, MPU9250_DPLF_2, ...... MPU9250_DPLF_7
   *   DLPF     Bandwidth [Hz]      Delay [ms]    Output rate [kHz]
   *     0           460               1.94           1
   *     1           184               5.80           1
   *     2            92               7.80           1
   *     3            41              11.80           1
   *     4            20              19.80           1
   *     5            10              35.70           1
   *     6             5              66.96           1
   *     7           460               1.94           1
   */
  myMPU9250.setAccDLPF(MPU9250_DLPF_6);
}

void loop() {
  xyzFloat angles = myMPU9250.getAngles();

/* This method provides quite precise values for x/y
   angles up 60°. */
  Serial.print("Angle x = ");
  Serial.print(angles.x);
  Serial.print("  |  Angle y = ");
  Serial.print(angles.y);
  Serial.print("  |  Angle z = ");
  Serial.println(angles.z);

/* Pitch and roll consider all axes for calculation. According to my experience
   it provides more reliable results at higher angles (>60°) */
  float pitch = myMPU9250.getPitch();
  float roll  = myMPU9250.getRoll();

  Serial.print("Pitch   = ");
  Serial.print(pitch);
  Serial.print("  |  Roll    = ");
  Serial.println(roll);
  Serial.println();

  delay(1000);
}

are you saying that nothing prints in the serial monitor?

@jsotola The serial monitor works fine, and it prints "MPU9250 does not respond"

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


text:
Problem saving "char" variable to EEPROM on ESP32
I am making a project, in which I need to store the WiFi credentials to the EEPROM. For now, I am able to store a bool array in the EEPROM, but I am not able to store the char variables as the ESP32 crashes. I can't share the complete code since it is REALLY long, but here are the problematic functions:
To save to the EEPROM:
//////////////////////////////////WORKING////////////////////////////////
void saveToEEPROM() {
  // Save the contents of the array in EEPROM memory
  for (int i = 0; i < NUM_PARAM_ITEMS; i++) {
    EEPROM.write(i, menu_items_param_bool[i]);
  }
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////NOT WORKING////////////////////////////////
  // Save WiFi credentials in EEPROM if not empty
  int offset = NUM_PARAM_ITEMS;

  if (strlen(ssid1) > 0) {
    for (int i = 0; i < strlen(ssid1); i++) {
      EEPROM.write(offset + i, ssid1[i]);
    }
    offset += strlen(ssid1);
    EEPROM.write(offset, '\0'); // Null-terminate the SSID1 string
  }
  offset++;
  if (strlen(password1) > 0) {
    for (int i = 0; i < strlen(password1); i++) {
      EEPROM.write(offset + i, password1[i]);
    }
    offset += strlen(password1);
    EEPROM.write(offset, '\0'); // Null-terminate the Password1 string
  }
  offset++;
  if (strlen(ssid2) > 0) {
    for (int i = 0; i < strlen(ssid2); i++) {
      EEPROM.write(offset + i, ssid2[i]);
    }
    offset += strlen(ssid2);
    EEPROM.write(offset, '\0');  // Null-terminate the SSID2 string
  }
  offset++;
  if (strlen(password2) > 0) {
    for (int i = 0; i < strlen(password2); i++) {
      EEPROM.write(offset + i, password2[i]);
    }
    offset += strlen(password2);
    EEPROM.write(offset, '\0'); // Null-terminate the Password2 string
  }

  EEPROM.commit(); // Don't forget to call the commit() function to save the data to EEPROM
}

To read from the EEPROM:
void readFromEEPROM() {
//////////////////////////////////WORKING////////////////////////////////
  // Read the contents of the EEPROM memory and restore it to the array
  for (int i = 0; i < NUM_PARAM_ITEMS; i++) {
    menu_items_param_bool[i] = EEPROM.read(i);
  }
//////////////////////////////////NOT WORKING//////////////////////////////////
  // Read WiFi credentials from EEPROM if not empty
  int offset = NUM_PARAM_ITEMS;

  // Read SSID1
  int ssid1Length = EEPROM.read(offset);
  if (ssid1Length > 0) {
    for (int i = 0; i < ssid1Length; i++) {
      ssid1[i] = (char)EEPROM.read(offset + i + 1);
    }
    ssid1[ssid1Length] = '\0'; // Null-terminate the SSID1 string
    Serial.print("SSID1: ");
    Serial.println(ssid1);
  }
  offset += ssid1Length + 1;

  // Read Password1
  int password1Length = EEPROM.read(offset);
  if (password1Length > 0) {
    for (int i = 0; i < password1Length; i++) {
      password1[i] = (char)EEPROM.read(offset + i + 1);
    }
    password1[password1Length] = '\0';  // Null-terminate the Password1 string
    Serial.print("PASSWORD1: ");
    Serial.println(password1);
  }

  offset += password1Length + 1;

  // Read SSID2
  int ssid2Length = EEPROM.read(offset);
  if (ssid2Length > 0) {
    for (int i = 0; i < ssid2Length; i++) {
      ssid2[i] = (char)EEPROM.read(offset + i + 1);
    }
    ssid2[ssid2Length] = '\0'; // Null-terminate the SSID2 string
    Serial.print("SSID2: ");
    Serial.println(ssid2);
  }

  offset += ssid2Length + 1;

  // Read Password2
  int password2Length = EEPROM.read(offset);
  if (password2Length > 0) {
    for (int i = 0; i < password2Length; i++) {
      password2[i] = (char)EEPROM.read(offset + i + 1);
    }
    password2[password2Length] = '\0'; // Null-terminate the Password2 string
    Serial.print("PASSWORD2: ");
    Serial.println(password2);
  }
}

And the variables to save and read are:
char ssid1[32] = "ssid1"; // SSID of the first WiFi network
char password1[64] = "password1"; // Password of the first WiFi network
char ssid2[32] = "ssid2"; // SSID of the second WiFi network
char password2[64] = "password2"; // Password of the second WiFi network

Can anybody help me?

what is the specific problem? ... but not the Char variables does not desctibe what actually  happens ... please update your question above ... do not add a comment below

In your read routine you are trying to read the length of the string from EEPROM, but you never saved the length there, just the null terminated strings themselves. For that to work you would need to write strlen() to EEPROM directly before the string

There are multiple issues with your code.

If strlen(anystring) is zero, you write nothing, but increment offset.
You try to read the lengths of the strings from EEPROM, but you never write them there.

Some things are complicated and can be simplified.

You don't need to explicitly write '\0' (end-of-string marker), since each of your strings already includes it.
Increment offset directly in the course.

This is a possible corrected solution. It uses the length and the end-of-string marker for each stored string.
  // Write anystring
  int anystringLength = strlen(anystring);
  EEPROM.write(offset, anystringLength);
  offset++;
  for (int i = 0; i <= anystringLength; i++) {
    EEPROM.write(offset, anystring[i]);
    offset++;
  }

  // Read anystring
  int anystringLength = EEPROM.read(offset);
  offset++;
  for (int i = 0; i <= anystringLength; i++) {
    anystring[i] = (char)EEPROM.read(offset);
    offset++;
  }
  // start of debug output
  Serial.print("any String: ");
  Serial.println(anystring);
  // end of debug output

Note: To make things explicit, using the offset and incrementing it are separated. You can combine them, though. But terse code tend to be misinterpreted.
This is another possible solution. Instead of expecting the length written before a string, read it until you find the end-of-string marker.
The writing loop writes all characters including the final end-of-string marker. This works for empty strings, too.
  int i;
  // Write anystring
  i = 0;
  do {
    char c = anystring[i];
    EEPROM.write(offset, c);
    offset++;
    i++;
  } while (c != '\0');

The reading loop does the same in the opposite direction. Using the do-while loop ensures that the end-of-string marker is read in any case.
  int i;
  // Read anystring
  i = 0;
  do {
    char c = EEPROM.read(offset);
    anystring[i] = c;
    offset++;
    i++;
  } while (c != '\0');
  // start of debug output
  Serial.print("any String: ");
  Serial.println(anystring);
  // end of debug output

Like the original the solutions lack error checks, for example of too long strings, which are left as an exercise to the reader.
Another bonus point will be received, if you extract these loops into functions. It simplifies the code and removes duplicates. [Edit] I found that the EEPROM class already provides writeString() and readString(). You should read its documentation and consider the usage.


text:
Inaccurate and changed results with ultrasonic sensor
I have an issue using an ultrasonic sensor. The problem is that when I connect the ultrasonic sensor to my Arduino Nano, it always gives some random values, usually 130 cm, I don't know why.
I bought a second ultrasonic sensor and the problem reoccured. One I bought last year, and the other one I bought yesterday.
I tried several programs like the traditional one:
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;

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

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.println(distance);
}

This didn't work, so I searched for useful libraries such as NewPing.h:
#include <NewPing.h>

const int trigPin = 9 ;
const int echoPin = 10;
const int maxDistance = 2000;
unsigned int distance;

NewPing sonar(trigPin, echoPin, maxDistance);

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

void loop() {
  delay(1000) ;
  distance = sonar.ping_cm();

  Serial.print("Distance : ");
  Serial.print(distance);
  Serial.println(" cm !");
}

This also didn't work. This is a simple screenshot of what happens in the monitor: (the 0 cm ! value is caused because I turned off the ultrasonic, and the object was actually 4 cm away):

Any help would be appreciated.

What are you using as object to test the sensors? Ultrasonic distance measurement is not really accurate and has the big flaw, that it depends on the reflectivity of the object. Soft objects can dampen the reflection significantly until you don't get a reliable measurement anymore and hard flat objects, that are placed at an angle, can reflect the sound wave in a direction away from the sensor, again impacting the measurement.

my hand is the object I was using, also a black plastic, and sometimes, thr wall

Please try with something like a book at right angle to the sensors line of view. That should at least rule out that problem for now. I'm not sure, if that solves your problem. I don't see any error in your code. Please also check your wiring (you didn't show it here). It should be rather simple, if you have one of the standard ultrasonic sensor modules for Arduino. Vcc and ground connections between sensor and Arduino and then trigger and echo to the corresponding digital pins (9 and 10).

I tried, everything is well connected, nothing is happening, same error


text:
How do I set a continuous servo to turn on until a switch is flicked?

I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.
Here is the schematic:

Here is my code:
#include <Servo.h>
Servo servo1;

int button = 2; //Assigning pin 2 for the momentary button
int buttonval = 0; //Creating a variable for the buttons value
int green = 12;
int red = 13; //Assigning the green and red LED to pin 12 and pin 13
int red = 13;
int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
int Open = 7;
int Closedval = 0; //Creating two blank variables for the states of the switch
int Openval = 0;

void setup() {
  servo1.attach(4); //Assigning the data pin for the servo
  servo1.write(1); // Giving a starting speed to the servo
  pinMode(button, INPUT); // Setting up the input pin for the momentary button
  digitalWrite(button, HIGH); //  turn on pull up resistors
  pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
  pinMode(Open, INPUT);
  pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);
  digitalWrite(Closed, HIGH);
  //Turning on pull up resistors for the two inputs from the toggle switch
  digitalWrite(Open, HIGH);
}

void loop() {
  Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
  Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

  if (Closedval == HIGH) {
    servo1.write(180);
    // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
  }

  if (Openval == HIGH) {
    servo1.write(86);
    // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
  }

  digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
  digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
}

Any help would be appreciated.

I think you need to look into switch debouncing.
Also add some debug statements to ensure the correct things are happening.

I seem to have got this working just by doing the following code:
#include <Servo.h>
Servo servo1;

int green = 12;       //Assinging the green and red LED to pin 12 and pin 13
int red = 13;

int Closed = 8;       //Assinging the Inputs of the toggle switch to 8 and 7

void setup()
{
  servo1.attach(4);    //Assigning the data pin for the servo
  servo1.write(86);     // Giving a starting speed to the servo

  pinMode(Closed, INPUT);        //Setting up the inputs for the two states of the toggle switch

  pinMode(green, OUTPUT);        //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);

  digitalWrite(Closed, HIGH);    //Turning on pull up resistors for the two inputs from the toggle switch

  delay(50);
  servo1.write(65); // start the motor opening
}

void loop() {
  if (digitalRead(Closed) == HIGH) { //If the toggle switch is changed then turn the servo in the oppisite direction
    servo1.write(100);
    if (digitalRead(Closed) == LOW) { // If the toggle switch is changed again then turn the servo off
      servo1.write(86);
    }
  }
}

Instead of using an external button I have had to use the reset button.

So for now I have got rid of the LED's but I am gonna add them in again later. Instead of using an external button wired up to activate the sequence of the servo motor, I have decided to have start of the sequence before the void loop () and so when I restart the Arduino using the reset button it will restart the sequence. It seems to work well.

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


text:
Interfacing A9G with Arduino for AT commands testing
I am trying to hook up to an A9G Pudding GSM board via an Arduino. I intend to use the onboard UART chip to facilitate TTL-UART conversion between PC and A9G.
I have initiated a software serial instance and using this to pass communication to/from the A9G and the Arduino.
Here's my code. However, all I'm getting is gibberish stuff. I've checked my connections, the link seems to exist but the encoding is mismatched. I'm communicating with the A9G at 115200 and my emulated serial is at 9600.
Could this be an issue?
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  Serial.begin(9600); // Monitor baud rate
  mySerial.begin(57600); // Set to detected baud rate

  Serial.println("A9G Module Communication Test");

  // Send AT command with carriage return and line feed
  mySerial.print("AT\r\n");
  delay(1000); // Wait for response
}
void loop() {
  // Check if data is available from the A9G module
  if (mySerial.available()) {
    // Read the data from the A9G module
    while (mySerial.available()) {
      char c = mySerial.read();
      Serial.write(c); // Send it to the Serial Monitor
    }
  }

  // Check if data is available from the Serial Monitor
  if (Serial.available()) {
    // Read the data from the Serial Monitor
    while (Serial.available()) {
      char c = Serial.read();
      mySerial.write(c); // Send it to the A9G module
    }
  }
}

Here's the output on the serial monitor.

Type "AT" and press "Send" from your Serial Monitor, what do you get?

Try it with mySerial.begin(115200); since that is the default baud rtate of the A9G.

please do not write in all capitals ... it indicates SHOUTING which is considered impolite ... use the edit button to correct the title

please do not post pictures of text ... post the text instead... format as code for readability

You can edit your code like this.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  Serial.begin(9600); // Monitor baud rate to match A9G
  mySerial.begin(115200); // Set to A9G baud rate

  Serial.println("A9G Module Communication Test");

  // Send AT command with carriage return and line feed
  mySerial.print("AT\r\n");
  delay(1000); // Wait for response
}

void loop() {
  // Check if data is available from the A9G module
  if (mySerial.available()) {
    // Read the data from the A9G module
    while (mySerial.available()) {
      char c = mySerial.read();
      Serial.write(c); // Send it to the Serial Monitor
    }
  }

  // Check if data is available from the Serial Monitor
  if (Serial.available()) {
    // Read the data from the Serial Monitor
    while (Serial.available()) {
      char c = Serial.read();
      mySerial.write(c); // Send it to the A9G module
    }
  }
}

why? what is changed?

My serial baud rate has been changed from 57600  to 115200.

and why is that the right value. please write an answer without the sketch if only the baud rate is changed.

The serial monitor is showing garbage value. That's why I thought, the defined baud rate for A9G  might not be correct.

but that should be in your answer. not a copy of the sketch. https://arduino.stackexchange.com/help/how-to-answer


text:
How to connect nRF24L01+ with Arduino Giga R1?
I have bought 2 Arduino Giga R1, 2 nRF24L01+ modules and 2 nRF24L01+ adapters. I am using the Arduino SPI in order to connect it with nRF24L01+. And I am using the following code with this change in the code only:
RF24 radio(7, 10); // CE, CSN

This is the Arduino GIGA R1 SPI documentation, and this is the nRF24L01+ modules, and the related adapter (the links of the modules are from a random Google search, just to show you the images + the documentation of the modules).
However I don't see something working. I added the following command both in the Receiver and Transmitter codes:
SPI.begin();
SPI1.begin();

in order to activate both SPI of each Arduino, because I don't know which is which. The result: Nothing works on Arduino GIGA R1... The same code above works fine on Arduino MEGA 2560 R3, so all the modules and the code are fine. The problem is on Arduino GIGA R1...
I supply the nRF24L01+ and the related adapters with 5V/1.5A power supply. I supply each Arduino GIGA R1 with 5V/1.5A power supply.
I have also tried this code, and I got this message:

We have lost connection, preventing unwanted behavior

Does anyone has any idea how to make the 2 Arduino GIGA R1 communicate via the nRF24L01+ link?

please no links to code and no pictures of code ...  copy your code and paste it into your question ... format as code

I cannot copy paste code from other sites. There are terms of use in every website. It is not my code...

then how do you know that the code has no errors?

It runs if I use Arduino MEGA 2560 R3 instead of Arduino GIGA R1.

Not sure if you found a solution but I had a similar problem and found a solution, which may work for you.
As you know, the Giga has two SPI buses.  The default are the ones on the ICSP header, the second one is on pins 11-13.
The NRF24L01, by default, assumes that you want to use the default one - SPI in this case.  If you want to use the other one (SPI1), all you need to do is call begin on SPI1 and pass that to the NRF begin function, as follows:
    SPI1.begin();
    radio.begin(&SPI1);

This worked for me, hopefully it will for you as well.

I just want to note that You Do Not Need An External Antenna module, because  the Arduino Giga R1 has a micro UFL antenna connector, and an antenna is shipped with every arduino giga(sorry for you if they forgot to include it in your one),
However It IS probably more for wifi porpuses than enclosed communication, still the nRF24L01+ is a great way to actually communicate between two mcu's, especially if an mcu doesnt come with a built in wifi or some sort of wireless communication


text:
DFPlayer library using RT TX pins
I am using the DFRobotDFPlayerMini-1.0.1 library by Angelo. I am trying to use the actual RX TX pins on a Uno R3, but it doesn't connect unless I type in an alternate digital pin number. This is no good for my application as I have a major pin shortage. I have tried typing in (0,1) but that is not being accepted.
The reason for using this library is because it provides a LOOP function that works well.

How do I use the RX TX pins with this library?
Is there another library that has a good LOOP function in it?

Thanks.
Doug

Guys....I haven't posted code as this is a question more about Library function. thanks

On a classic Arduino pins 0 and 1 are used for serial communication with the host PC, so you cannot use them to talk to a peripheral without conflicting with that.  The library may well be coded to trap and reject such an attempt.
On various alternate (ARM, Atmega32u4, etc) boards these pins may be usable, though the library may not be aware of that.  Also on such boards you would generally want to use an available hardware UART rather than a software simulation of one, which may be fairly ATmega-specific anyway - the end result of which is that library code may well need modification to work on a non-traditional device.

Thanks Chris.....Yep...that seems to be the reason..the PWM usage is in conflict. I am working on an alternative using the DFPlayer 0nly...I will post final results in a couple of days hopefully.

PWM does not seem to have any role in the issue.  The output of the DFPlayer may be PWM, but that doesn't touch the Arduino - the issue is with the Arduino's serial command communication to it.

Sorry Chris...Long Night and wrong post...the question is how do i get to use the RX TX pins on a UNO R3 with this Library....however You have answered the other question that I had.

You simply can't use them, unless you give up the connection to the PC.  If you do that, you should re-write the library to use hardware serial.

Chris..this may be what the default :- software serial library is doing as it works on the RX TX pins      #include <softwareserial.h>
#include <dfplayer_mini_mp3.h>   I have found several instances of this , example link   http://stonez56.blogspot.com.au/2015/03/arduino-dfplayer-mini-mp3-module.html    but the problem is how do i LOOP with this library as that function is not well documented??? thanks

When you say "type in (0, 1)" I suppose you mean this:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;

Reference
You cannot use (0, 1) in SoftwareSerial. However, what you could do is pass Serial to the init string:
void setup() {
  // mySoftwareSerial.begin(9600);
  Serial.begin(9600);
  // if (!myDFPlayer.begin(mySoftwareSerial)) {
  if (!myDFPlayer.begin(Serial)) {
    //Use softwareSerial to communicate with mp3.
  }

However that means you cannot use Serial for debugging. You'll have to find another way to log errors and messages.

OK ...with library I have to select digital pins, thats just the way it is built. no options. thanks for the comments...closed

D0, D1 are digital pins. The problem is not there. See my answer.

That true and i did try that but the library didn't like it..however with some round about coding i am now able to get an acceptable result for my project...thanks for the input.

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


text:
Arduino IDE automatic tools
I know that the Arduino IDE does some simple tasks automatically: for example it creates function prototypes, but this function sometimes fails.
Does that IDE run other hidden "pre-precompiler" tasks?
Is there a way to disable them? (this question refers especially to the function prototypes creator).

You could place all your code in a separate .cpp file, and call that from your .ino file. That way your ino file will just be a few lines. You might even be able to just use a single include.

The IDE runs a "preprocessing" routine. As well as adding prototypes it also:

Adds #include <Arduino.h> to the start of your sketch
Removes comments (or the older versions did, I am not sure about arduino-builder)
Identifies the libraries #included in the sketch

The latter is used to build the list of -I ... directories to add to the command line. Removing of comments was chiefly to make finding functions easier for making function prototypes (though there are better ways of doing both those and arduino-builder might use them).
Can you disable it? No. Not for .ino files. However, any .cpp files added to your project are treated as vanilla C++ source code and aren't preprocessed in this way.


text:
How do I use an ATMega 328 (not P) chip with an Arduino board?
I just burned the bootloader on an ATMega328 chip and then I put in on the Arduino board. But when I try to upload a program to it, it says programmer not in sync and programmer not responding.
For burning the bootloader I changed the address in the avrconfig file and reset it back to the original one. Do I need to keep changing the address of the board?
How do I use this as a normal Arduino board, as I fried my original chip? Do I need to get an ATMega328P chip?

Did you set the right fuses for the clock source?

i used an external 16mhz clock but didnt change any code for it.

If you don't set the right fuses it will be running from the internal clock and everything will be the wrong speed. Check your fuse settings.

@Majenko could you help me with this i am a bit new to this.

So I found the solution:
Here is the link to the method that worked for me. I think the reason my previous method didn't work was because of fuses for the clock as mentioned by Majenko in the comments.

thank you for showing me how i am supposed to answer (i am new here).

You can force the 'P' bootloader into it and use it as an Arduino board. The extra possibilities of the 'P' are not used by the standard Arduino libraries and when uploading it does check the bootloader but it does not check the chip signature.
I think you have already done this. Perhaps something else is wrong.


text:
Having trouble passing data through RF24
I have three RF24, all of them are connected to one arduino-uno each. The first one has sensors that sends data to the second one then the second one passes it to the third one. The first pass from RF24 #1 to RF24 #2 is successful but from the RF24 #2 to RF24 #3 there seems to be a problem.
Code for the RF24 #1 (I just copied the setup and loop the other functions are for the sensors, I think it's unnecessary):
//Libraries for temperature
#include <OneWire.h>
#include <DallasTemperature.h>
#define motor1 8
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

//for pH meter
#define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
#define Offset 0.00            //deviation compensate
#define LED 13
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth  40    //times of collection
int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
int pHArrayIndex = 0;

//for NRF24L01
RF24 radio(7, 8); // CE, CSN
const uint64_t waddress = 0xB00B1E50D2LL;
struct package {
  float temperature, ph, Do, inch, cm1;
};
typedef struct package Package;
Package data;
int LID = 4, LOD = 6;

//for ultrasonic
const int trigPin = 3;
const int echoPin = 4;
long duration, inches, cm, meter;

void setup(void)
{
  // start serial port
  radio.begin();
  radio.openWritingPipe(waddress);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();

  pinMode(LED, OUTPUT);
  // Start up the library
  sensors.begin();
}

/*
   Main function, get and show the temperature
*/

void loop(void)
{
  static unsigned long samplingTime = millis();
  static unsigned long printTime = millis();
  static float pHValue, voltage;
  if (millis() - samplingTime > samplingInterval)
  {
    pHArray[pHArrayIndex++] = analogRead(SensorPin);
    if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
    voltage = avergearray(pHArray, ArrayLenth) * 5.0 / 1024;
    pHValue = 3.5 * voltage + Offset;
    samplingTime = millis();
  }
  if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
  {
    digitalWrite(LED, digitalRead(LED) ^ 1);
    // call sensors.requestTemperatures() to issue a global temperature
    // request to all devices on the bus

    sensors.requestTemperatures(); // Send the command to get temperatures

    // After we got the temperatures, we can print them here.
    // We use the function ByIndex, and as an example get the temperature from the first sensor only.

    //Serial.print(pHValue,2);
    //Serial.print(",");
    //Serial.print(sensors.getTempCByIndex(0));

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

    data.ph = (pHValue);
    data.temperature = (sensors.getTempCByIndex(0));
    Serial.print(data.ph);
    Serial.print(data.temperature);
    Serial.print(data.Do);
  }
}

RF24 #2
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const uint64_t raddress = 0xB00B1E50D2LL;
const uint64_t waddress = 0xB00B1E50B1LL;
struct package {
  float temperature, ph, Do, inch, cm1;
};
typedef struct package Package;
Package data;

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(waddress);
  radio.openReadingPipe(1, raddress);
  radio.setPALevel(RF24_PA_MIN);
}

void loop() {
  radio.startListening();

  while (radio.available()) {
    radio.read(&data, sizeof(data));
    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);
  }
  if (radio.write(&data, sizeof(data))) {
    Serial.println(" delivery failed");
  }
  radio.stopListening();
  delay(200);
}

RF24 #3
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
int lid = 2 , lod = 4;
RF24 radio(7, 8); // CE, CSN
const uint64_t raddress = 0xB00B1E50B1LL;
struct package {
  float temperature, ph, Do, inch, cm1;
};
typedef struct package Package;
Package data;

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

  radio.begin();
  radio.openReadingPipe(2, raddress);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
  pinMode(lid, OUTPUT);
  pinMode(lod, OUTPUT);
}

void loop() {
  unsigned long startTimer = millis();
  bool timeout = false;

  while (!radio.available() && !timeout) {
    if (millis() - startTimer > 500 )
    {
      timeout = true;
    }
    // radio.read(&temperature, sizeof(temperature));
    //radio.read(&Do, sizeof(Do));
  }
  if (timeout) {
    Serial.println("Failed to receive data");
  }
  else {
    radio.read(&data, sizeof(data));

    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);
  }
}

The serial monitor for RF24 #2 displays:
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
6.92,28.25,7.20,15.00,38.00
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
6.91,28.25,7.20,15.00,38.00

RF24 #3 Serial Monitor:
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00

Sometimes RF24 #3 receives the data and prints it continuously. I don't know why. Most of the time it displays the above.
Edit: Revision
Update: It turns out that RF24 #3 continuous to print even if RF24 #2 is unplugged/not powered.

You should always call stopListening() right before you write(). Also write() returns true when messages are delivered so your condition is wrong. Try changing the loop() in the second node to:
void loop() {
  while (radio.available()) {
    radio.read(&data, sizeof(data));
    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);

    radio.stopListening();
    if (!radio.write(&data, sizeof(data))) {
      Serial.println("Delivery failed");
    }
    radio.startListening();
  }
}

If a packet is available, it's read, printed and forwarded.
The third node's loop() should also be adjusted to something like:
bool new_data = false;

void loop() {
  if (radio.available()) {
    radio.read(&data, sizeof(data));

    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);
    new_data = true;
  }
  if (new_data) {
    // do stuff
    new_data = false;
  }
}

Data is sent in 32-byte payloads and your entire package is 20 bytes (without padding), assuming a float = 4 bytes. So a complete packet has either arrived or it hasn't; no point in waiting in one place. new_data lets you know when there's new stuff obviously and you clear the flag when you're done processing the data. This way, you can do other stuff while you wait for a packet to show.


text:
One port of motor shield doesn't operating stepper motor

One port of my motor shield (i.e M1 & M2) is not driving the stepper motor as it should.stepper motor jitters at its position.
While the other port (M3 & M4) works fine but it makes stepper motor too hot and also it's respective motor driver L293D IC.
While all the ports of motor shield works fine with DC Motor.

I am making CNC plotter using this setup.
I am powering motor shield with 12 V adapter and Arduino is connected with USB cable.
This is the code I am using :
#include <Servo.h>
#include <AFMotor.h>

#define LINE_BUFFER_LENGTH 512

char STEP = MICROSTEP ;

// Servo position for Up and Down
const int penZUp = 115;
const int penZDown = 83;

// Servo on PWM pin 10
const int penServoPin =10 ;

// Should be right for DVD steppers, but is not too important here
const int stepsPerRevolution = 48;

// create servo object to control a servo
Servo penServo;

// Initialize steppers for X- and Y-axis using this Arduino pins for the L293D H-bridge
AF_Stepper myStepperY(stepsPerRevolution,1);
AF_Stepper myStepperX(stepsPerRevolution,2);

/* Structures, global variables    */
struct point {
  float x;
  float y;
  float z;
};

// Current position of plothead
struct point actuatorPos;

//  Drawing settings, should be OK
float StepInc = 1;
int StepDelay = 0;
int LineDelay =0;
int penDelay = 50;

// Motor steps to go 1 millimeter.
// Use test sketch to go 100 steps. Measure the length of line.
// Calculate steps per mm. Enter here.
float StepsPerMillimeterX = 100.0;
float StepsPerMillimeterY = 100.0;

// Drawing robot limits, in mm
// OK to start with. Could go up to 50 mm if calibrated well.
float Xmin = 0;
float Xmax = 40;
float Ymin = 0;
float Ymax = 40;
float Zmin = 0;
float Zmax = 1;

float Xpos = Xmin;
float Ypos = Ymin;
float Zpos = Zmax;

// Set to true to get debug output.
boolean verbose = false;

//  Needs to interpret
//  G1 for moving
//  G4 P300 (wait 150ms)
//  M300 S30 (pen down)
//  M300 S50 (pen up)
//  Discard anything with a (
//  Discard any other command!

/**********************
 * void setup() - Initialisations
 ***********************/
void setup() {
  //  Setup

  Serial.begin( 9600 );

  penServo.attach(penServoPin);
  penServo.write(penZUp);
  delay(100);

  // Decrease if necessary
  myStepperX.setSpeed(600);

  myStepperY.setSpeed(600);

  //  Set & move to initial default position
  // TBD

  //  Notifications!!!
  Serial.println("Mini CNC Plotter alive and kicking!");
  Serial.print("X range is from ");
  Serial.print(Xmin);
  Serial.print(" to ");
  Serial.print(Xmax);
  Serial.println(" mm.");
  Serial.print("Y range is from ");
  Serial.print(Ymin);
  Serial.print(" to ");
  Serial.print(Ymax);
  Serial.println(" mm.");
}

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

  delay(100);
  char line[ LINE_BUFFER_LENGTH ];
  char c;
  int lineIndex;
  bool lineIsComment, lineSemiColon;

  lineIndex = 0;
  lineSemiColon = false;
  lineIsComment = false;

  while (1) {

    // Serial reception - Mostly from Grbl, added semicolon support
    while ( Serial.available()>0 ) {
      c = Serial.read();
      if (( c == '\n') || (c == '\r') ) {             // End of line reached
        if ( lineIndex > 0 ) {                        // Line is complete. Then execute!
          line[ lineIndex ] = '\0';                   // Terminate string
          if (verbose) {
            Serial.print( "Received : ");
            Serial.println( line );
          }
          processIncomingLine( line, lineIndex );
          lineIndex = 0;
        }
        else {
          // Empty or comment line. Skip block.
        }
        lineIsComment = false;
        lineSemiColon = false;
        Serial.println("ok");
      }
      else {
        if ( (lineIsComment) || (lineSemiColon) ) {   // Throw away all comment characters
          if ( c == ')' )  lineIsComment = false;     // End of comment. Resume line.
        }
        else {
          if ( c <= ' ' ) {                           // Throw away whitepace and control characters
          }
          else if ( c == '/' ) {                    // Block delete not supported. Ignore character.
          }
          else if ( c == '(' ) {                    // Enable comments flag and ignore all characters until ')' or EOL.
            lineIsComment = true;
          }
          else if ( c == ';' ) {
            lineSemiColon = true;
          }
          else if ( lineIndex >= LINE_BUFFER_LENGTH-1 ) {
            Serial.println( "ERROR - lineBuffer overflow" );
            lineIsComment = false;
            lineSemiColon = false;
          }
          else if ( c >= 'a' && c <= 'z' ) {        // Upcase lowercase
            line[ lineIndex++ ] = c-'a'+'A';
          }
          else {
            line[ lineIndex++ ] = c;
          }
        }
      }
    }
  }
}

void processIncomingLine( char* line, int charNB ) {
  int currentIndex = 0;
  char buffer[ 64 ];                                 // Hope that 64 is enough for 1 parameter
  struct point newPos;

  newPos.x = 0.0;
  newPos.y = 0.0;

  //  Needs to interpret
  //  G1 for moving
  //  G4 P300 (wait 150ms)
  //  G1 X60 Y30
  //  G1 X30 Y50
  //  M300 S30 (pen down)
  //  M300 S50 (pen up)
  //  Discard anything with a (
  //  Discard any other command!

  while( currentIndex < charNB ) {
    switch ( line[ currentIndex++ ] ) {              // Select command, if any
    case 'U':
      penUp();
      break;
    case 'D':
      penDown();
      break;
    case 'G':
      buffer[0] = line[ currentIndex++ ];          // /!\ Dirty - Only works with 2 digit commands
      //      buffer[1] = line[ currentIndex++ ];
      //      buffer[2] = '\0';
      buffer[1] = '\0';

      switch ( atoi( buffer ) ){                   // Select G command
      case 0:                                   // G00 & G01 - Movement or fast movement. Same here
      case 1:
        // /!\ Dirty - Suppose that X is before Y
        char* indexX = strchr( line+currentIndex, 'X' );  // Get X/Y position in the string (if any)
        char* indexY = strchr( line+currentIndex, 'Y' );
        if ( indexY <= 0 ) {
          newPos.x = atof( indexX + 1);
          newPos.y = actuatorPos.y;
        }
        else if ( indexX <= 0 ) {
          newPos.y = atof( indexY + 1);
          newPos.x = actuatorPos.x;
        }
        else {
          newPos.y = atof( indexY + 1);
          indexY = '\0';
          newPos.x = atof( indexX + 1);
        }
        drawLine(newPos.x, newPos.y );
        //        Serial.println("ok");
        actuatorPos.x = newPos.x;
        actuatorPos.y = newPos.y;
        break;
      }
      break;
    case 'M':
      buffer[0] = line[ currentIndex++ ];        // /!\ Dirty - Only works with 3 digit commands
      buffer[1] = line[ currentIndex++ ];
      buffer[2] = line[ currentIndex++ ];
      buffer[3] = '\0';
      switch ( atoi( buffer ) ){
      case 300:
        {
          char* indexS = strchr( line+currentIndex, 'S' );
          float Spos = atof( indexS + 1);
          //         Serial.println("ok");
          if (Spos == 30) {
            penDown();
          }
          if (Spos == 50) {
            penUp();
          }
          break;
        }
      case 114:                                // M114 - Repport position
        Serial.print( "Absolute position : X = " );
        Serial.print( actuatorPos.x );
        Serial.print( "  -  Y = " );
        Serial.println( actuatorPos.y );
        break;
      default:
        Serial.print( "Command not recognized : M");
        Serial.println( buffer );
      }
    }
  }

}

/*********************************
 * Draw a line from (x0;y0) to (x1;y1).
 * int (x1;y1) : Starting coordinates
 * int (x2;y2) : Ending coordinates
 **********************************/
void drawLine(float x1, float y1) {

  if (verbose)
  {
    Serial.print("fx1, fy1: ");
    Serial.print(x1);
    Serial.print(",");
    Serial.print(y1);
    Serial.println("");
  }

  //  Bring instructions within limits
  if (x1 >= Xmax) {
    x1 = Xmax;
  }
  if (x1 <= Xmin) {
    x1 = Xmin;
  }
  if (y1 >= Ymax) {
    y1 = Ymax;
  }
  if (y1 <= Ymin) {
    y1 = Ymin;
  }

  if (verbose)
  {
    Serial.print("Xpos, Ypos: ");
    Serial.print(Xpos);
    Serial.print(",");
    Serial.print(Ypos);
    Serial.println("");
  }

  if (verbose)
  {
    Serial.print("x1, y1: ");
    Serial.print(x1);
    Serial.print(",");
    Serial.print(y1);
    Serial.println("");
  }

  //  Convert coordinates to steps
  x1 = (int)(x1*StepsPerMillimeterX);
  y1 = (int)(y1*StepsPerMillimeterY);
  float x0 = Xpos;
  float y0 = Ypos;

  //  Let's find out the change for the coordinates
  long dx = abs(x1-x0);
  long dy = abs(y1-y0);
  int sx = x0<x1 ? StepInc : -StepInc;
  int sy = y0<y1 ? StepInc : -StepInc;

  long i;
  long over = 0;

  if (dx > dy) {
    for (i=0; i<dx; ++i) {
      myStepperX.onestep(sx,STEP);
      over+=dy;
      if (over>=dx) {
        over-=dx;
        myStepperY.onestep(sy,STEP);
      }
    delay(StepDelay);
    }
  }
  else {
    for (i=0; i<dy; ++i) {
      myStepperY.onestep(sy,STEP);
      over+=dx;
      if (over>=dy) {
        over-=dy;
        myStepperX.onestep(sx,STEP);
      }
      delay(StepDelay);
    }
  }

  if (verbose)
  {
    Serial.print("dx, dy:");
    Serial.print(dx);
    Serial.print(",");
    Serial.print(dy);
    Serial.println("");
  }

  if (verbose)
  {
    Serial.print("Going to (");
    Serial.print(x0);
    Serial.print(",");
    Serial.print(y0);
    Serial.println(")");
  }

  //  Delay before any next lines are submitted
  delay(LineDelay);
  //  Update the positions
  Xpos = x1;
  Ypos = y1;
}

//  Raises pen
void penUp() {
  penServo.write(penZUp);
  delay(penDelay);
  Zpos=Zmax;
  digitalWrite(15, LOW);
    digitalWrite(16, HIGH);
  if (verbose) {
    Serial.println("Pen up!");

  }
}
//  Lowers pen
void penDown() {
  penServo.write(penZDown);
  delay(penDelay);
  Zpos=Zmin;
  digitalWrite(15, HIGH);
    digitalWrite(16, LOW);
  if (verbose) {
    Serial.println("Pen down.");

  }
}

This are the connections I made:

I tried replacing motors with each other but the case remains same just the motor now connected to the port(which is not working ) starts jittering and another one works but gets too hot.

I ran into the same issue yesterday. The problem is that one of the pins of the M1 Port touches the housing of the usb-jack and shortens Vcc to Gnd. Try to put some tape around the housing...
bye


text:
Why can't my IF statement see a global?
I'm rather new to Arduino programming. I have a problem compiling the following bit of code:
const int relay1 = 10;  //Power Relay 1
const int relay2 = 11;  //Power Relay 2
const int relay3 = 12;  //Toggle Relay
const int button1 = 3;
const int button2 = 4;
const int button3 = 5;

//---Button States---\\
int button1State;   //Current state of Button 1
int button2State;   //Current state of Button 2
int button3State;   //Current state of Button 3
int button1State_prev = LOW;  //Previous state of Button 1
int button2State_prev = LOW;  //Previous state of Button 2
int button3State_prev = LOW;  //Previous state of Button 3

//---General Variables---\\
int userSelection = 0;
int interlockState = 0;
int platformState = 0;

//---Interval-Tracking Variables---\\
unsigned long lastTime_Debounce1 = 0;   //Button 1 debounce time
unsigned long lastTime_Debounce2 = 0;   //Button 2 debounce time

//---Activity Delays---\\
const unsigned int relayDelay = 10;           //Delay between relay actions (ms)
const unsigned int debounceDelay = 60;        //Delay for button de-bouncing (ms)

void setup() {
  //Configure Pins
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);

  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);
  digitalWrite(relay3, LOW);
}

void loop() {
  //Read value of each input pin
  int button1Reading = digitalRead(button1);  //Current reading of Button 1
  int button2Reading = digitalRead(button2);  //Current reading of Button 2
  int button3Reading = digitalRead(button3);  //Current reading of Button 3

  //Debounce Button1
  if (button1Reading != button1State_prev) {
    lastTime_Debounce1 = millis();
  }
  button1State_prev = button1Reading;
  if ((millis() - lastTime_Debounce1) > debounceDelay) {
    if (button1Reading != button1State) {
      button1State = button1Reading;
    }
  }

  //Debounce Button2
  if (button2Reading != button2State_prev) {
    lastTime_Debounce2 = millis();
  }
  button2State_prev = button2Reading;
  if ((millis() - lastTime_Debounce2) > debounceDelay) {
    if (button2Reading != button2State) {
      button2State = button2Reading;
    }
  }

For some reason, the compiler is convinced that the variable lastTime_Debounce1 in the second IF-statement, on Line 54, has not been declared in-scope. I don't understand how this is possible, since the variable in question is a defined and initialized global.
If I comment-out the first trio of IF-statements (handling Button 1), the second trio (handling button 2) has no problem compiling, even though it does exactly the same thing in exactly the same way.
I checked all the usual suspects: spelling, braces, semicolons, even commented-out blocks of code one at a time, but I can't find the source of the problem. I'm using the Arduino 1.8.2 IDE.
Can someone please point out the mistake I'm missing?

I tagged your question with the C++ tag to see if the syntax highlighting would make the problem more obvious, but unfortunately not.

The backslash in your comments are the problem. As per C++ language definitions, a \ at the end of the line is interpreted as a "line continuation". Thus, your comment gets continued in the next line and your variable declaration and initialization is commented out.
This is apparent when opening your code with a good syntax highlighting program, like Notepad++.

Removing all \\ from the end of the comment line solves your problem.
Side note: For more info, look at https://stackoverflow.com/a/30290133/5296568. Backslashes at the end of a line are actually useful when used in multi-line macro definitions.

I'm surprised the code highlighter here doesn't catch that.

@WernerCD Stack Exchange code markup tries to intelligently detect what language is being used in the code block, but sometimes it fails to do so and thinks it's something it isn't. you can fix it by specifying  before the snippet.

@Nzall see NickGammon comment above; even the StackOverflow syntax highlighter, when put in C/C++ mode (by adding C++ tag), doesn't highlight it correctly.

Why does that even work? Shouldn't the first \ demask the second one and thus not comment out the new line?

I am not aware of a \  in a comment being able to escape the next character as if it the \\ was placed in a character string.


text:
ESP32 struggling to trigger relay module consistently
I'm working with a 4-channel, 5 V relay module and an ESP32 which operates on 3.3 V.

The setup seemed to work well initially  but I have started experiencing some inconsistencies. One of the four relays is working perfectly fine, but the other three are not triggering as they should.
Here are the symptoms:

The LEDs on the non-working relays do light up when a signal is sent from the ESP32, indicating some form of communication.
There is no audible 'click' sound from these relays when they are supposed to trigger.
I noticed that if I gently tap the relay casing, the relay will sometimes trigger, and I can hear it closing.

I had previously thought that I might have fried my first relay module, so I replaced it, but the issue reappeared after a few days.
Any guidance would be greatly appreciated as I'm at a loss here.

Is your relay board compatible with 3.3 V logic?

@StarCat i don't understand your question can you help me figure out or explain a bit more it's supposed to be powered by 5V DC but i'm limited to the esp32 board

Maybe it is your code.  Try posting a small example that reproduces the problem

More questions here then you might think are because of under powered project using fresh but weak batteries.  Almost always avoid using 9 Volt batteries.  Certainly avoid them if a motor or relay is involved.  How is this project powered?

right now i'm using the usb type-C cable to power the esp directly how can i make the esp32 generate more power or make the relay use less current to be triggered

do not use the ESP32 as a power supply ... it can easily become an expensive fuse ... use it for control only ... power the relay module from a separate power supply

With "compatible with 3.3 V logic" I mean: does your relay board work with 3.3 V logic signals according to its documentation?

How are you connecting the VCC pin of the relay module to ESP32?

So it turns out that esp32 boards can actually output 5v alongside with 3.3v output pin, You just have to use the VN pin which is used for powering the board when not connected through USB, this is not what the pin is intended for and also might cause some problems and you cannot upload code to the board when VIN pin is connected but so far it works perfectly and outputs consistent 5V that triggers the relays just fine.
Obviously, I was just looking for a solution no matter what risks it imposed, can anyone with a deeper understanding of this topic explain why the power input pin can also work as output and why is this not a feature that comes with esp32 boards

Hi Hach, The way this site works is one question followed by answers.  You edit the original question to provide more information.  Or you ask a new question separately.

i answered the original question but asked if the solution i found is efficient and if it presents any dangers to the board

I'm afraid that there is a voltage level mismatch between the ESP32 and the relay board. The ESP32 GPIO pins output 3.3V, but it looks like the relays need 5V to switch. If that's the case, you need a logic-level converter to boost the 3.3V signals from the ESP32 to 5V. You can also design a relay board using an on-board ESP32-S3:
https://www.pcbway.com/project/shareproject/ESP32_S3_Relay_control_09c46e0c.html

the relay board in question has the option to power the coils with 5 V and control them with 3.3 V (with a transistor)


text:
Motor noise on my Arduino RC?
I want to make an RC car based on two Arduino Nanos, two nRF24L01s (Rx and Tx), and a Pololu brushed motor driver, and it works, more or less.
Sometimes it works very well and everything goes nicely and suddenly it will "freeze" and stop receiving and when it does, the servo always goes to 0° (I think it must be the Rx because it prints the same value until the next restart in the serial monitor).
It seems the servo trebles in the same direction (to 0°) only when I send high PWM values until it stops reading new data and "freezes".
I have 2 batteries, one for the Nano with a step-up converter, and another for the servo and the brushed motor;  they share a common ground. Everything is close to each other and connected by wires soldered to a prototype breadboard. It is really messy but makes a good contact.
So it seems it is a noise problem, doesn't it? But what else could it be? How can I suppress that noise? I have already watched the Pololu guide about noise but I didn't try the bypass capacitors since I don't know how to solder them properly (can they burn the servo?)
Here is the code for the Tx
#include <SPI.h>
#include "RF24.h"

const int ledBot = 8;
const int padx = A0;
const int pady = A1;
const int sw = 3;
int sws;
int x;
int y;
int botState;
int aBotState;
int ledState;
const float un = 0.25;
const float fy = 0.176;
int sens [4]; // 0: throttle, 1: foward/backwards, 2: steering, 3: lights

RF24 radio(9, 10); // CE, CSN
const byte address[6] = "00001";
void setup() {
  //Serial.begin(9600);
  pinMode(padx, INPUT);
  pinMode(pady, INPUT);
  pinMode(sw, INPUT);
  pinMode(ledBot, INPUT_PULLUP);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  x = analogRead(padx);
  y = analogRead(pady);
  sws = digitalRead(sw);
  botState = digitalRead(ledBot);
  y = 1024-y;

  switch (sws){ //foward and backwards

  case 0:
    sens [0] = un*x;
    sens [1] = 0;
    sens [2] = min(135, max(50, y*fy-2));
    break;

  case 1:
    sens [0] = un*x;
    sens [1] = 1;
    sens [2] = min(135, max(50, y*fy-2));
    break;
  }

  if ( botState == HIGH && aBotState == LOW) { //button switch part
    if (ledState == 0) {
      ledState = 1;
      sens [3] = ledState;
    }
    else {
      ledState = 0;
      sens [3] = ledState;
    }
  }
  aBotState = botState;
  radio.write(&sens, sizeof(sens));

  //Serial.println(sens[0]);
  //Serial.println(ledState);
  // Serial.println(sens[1]);
  //Serial.println(sens [3]);
}

And here for the Rx:
#include <Servo.h>
#include <SPI.h>
#include "RF24.h"

int sens [4];
const int polph = 7;
const int polen = 6;
const int led1 = 2;
const int led2 = 3;
const int ledError = 8;

Servo servo;
RF24 radio(9, 10); //
const byte address[6] = "00001";

void setup() {
  pinMode(polph, OUTPUT);
  pinMode(polen, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  pinMode(ledError, OUTPUT);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  delay(300);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  servo.attach(5);
  //Serial.begin(9600);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    digitalWrite(ledError, LOW);
    radio.read(&sens, sizeof(sens));
    analogWrite(polen, sens [0]);
    digitalWrite(polph, sens[1]);
    servo.write(sens [2]);
    digitalWrite(led1, sens [3]);
    digitalWrite(led2, sens [3]);
  }
}

It’s really hard to diagnose a problem when you can’t see it.  Post the codes and a wiring diagram so someone can actually have a hope of seeing the problem.

Electrical noise is the problem quite often. In order to minimize noise, several key points must be observed:

Solder one 0.1uF ceramic capacitor from each terminal to the motor case. These are called decoupling capacitors and are used to suppress HF noise creeping in from the motors due to sparking/arching.

Choose appropriate AWS rating for your motor leads and adequate power supply. Inappropriately thin leads or insufficient battery discharge current can cause abrupt voltage drop on acceleration which will lead to sudden MCU resets (brown out resets).

Twist the leads around each other. This helps to further nullify arching noise.

As for Arduino, it is not the best way for making reliable RC software because it does simple things terribly wrong, e.g. sequential software polling instead of using hardware input capture. I would highly recommend learning how to write firmware for MCUs in native mode.
Check out this link to gain some inspiration on how to build an RC motor driver:
https://github.com/neoxic/STM8-RC-Dual-Motor-Driver#building-a-dual-12a-bidirectional-esc


text:
Change/declare a constant in setup and use it in loop
I want to change or declare a constant in the setup() and then, I want to access it in the loop().
I have searched a lot, but the only questions I found could be solved by declaring the constant in the beginning of the program. That doesn't work for me because I am using the Adafruit BMP388 and I can't use the pressure before setup().
I also tried declaring the variable before setup() and changing it inside setup(), but it didn't change when I used it in loop().
How can I solve this?

how are we to know that you actually changed it in loop()?

I didn't change it in loop(), I have to access it there. I want to change it in setup()

look at the fade sketch in arduino IDE example sketches

how are we to know that you actually changed it in setup()?

I want to use it in loop(): I need the startpressure (declared in setup()) and compare it to the current pressure

the title of your post does not match the content of your post ... title asks about a variable, content asks about a constant ... i suggest that you research the difference

Constants cannot, by definition, be changed. Do you mean variables?

I also tried declaring the variable before the setup() and changing it inside the setup(), but it didn't change when I used it in the loop(). - Can you show this code? A variable, changed in setup, would stay changed. Unless you declared it twice (shadowed it).

You are not going to get good answers without showing your code, but maybe this is a good guess of what you want:
why not try something roughly like this (untested and incomplete)?
Adafruit_BMP3XX bmp;
float startPressure;
float difference;

void setup() {
  bmp.begin_I2C();
  startPressure = bmp.readPressure();
}

void loop() {
  difference = startPressure - bmp.readPressure();
}

Or, better:
Adafruit_BMP3XX bmp;

void setup() {
  bmp.begin_I2C();
}

void loop() {
  static const float startPressure = bmp.readPressure();
  static float difference;
  difference = startPressure - bmp.readPressure();
}

I'm not entirely sure this is the direction he's going in.  But if he is, you could move float startPressure; into the loop(), perform startPressure = bmp.readPressure(); as part of its initialization, and make it static and const.
As in: static const float startPressure = bmp.readPressure();
This would behave as what you have but would limit startPressure to the only scope it's used in.

@timemage: True, and better, but it would require an explanation of "static", and I don't feel up to it 8-). I will add it though.

difference does not need to be static.

Yeah, and it technically isn't "constant" in C++ terms.  But it seems to be in the spirit of the question so far as I understand the question.

@Edgar-Bonet: No, doesn't have to be in the example, but who knows if he wants it to remain the same over several loops in his code.


text:
How to scan Lora E32-TTL-100 devices by using only one ESP 8266 + Lora E32-TTL-100s?
I'm investigating for some function of Lora E32-TTL-100.
Currently, I can communicate between two E32 like the following image:

But 3 days ago, I saw a person used only one MCU to scan the other E32 is power-on or power-off:

It's so interesting, and tried many way, but wasn't successful.
I found many documents but they always mention communicate 2 MCUs + 2 Loras.
Again, the purpose is how to do for the 1st E32 know that the 2nd E32 is power-on.
Can anyone please help me with it or have any ideas about it?
This's the link I followed https://www.mischianti.org/2019/11/10/lora-e32-device-for-arduino-esp32-or-esp8266-fixed-transmission-part-4/
This is the schema to simulate it:

Thank.

please post a link to what you saw 3 days ago

@jsotola, I saw my teacher done it like the above images. We will know that the 2nd is power-off, the 2nd, 3rd E32 is power-on. I'm not sure about how to implement it. I also ask my teacher, but he said that I should find the solutions for it. but no hope.


text:
using a variable to index an array
I'm using the keypad library to return a number 1-9. (im fairly sure this returns an int)
I have an array (data) showing the state of each button press.
so i would like the number returned by the keypad (key) to be the index number that gets edited from 0 to 1 and from 1 to 0.
    //REMOTE KEYPAD TO CONTROL OUTPUTS OVER SERIAL

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},

};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int iAm = 1;                                    //this is device number 1
float checkSum = 0.00;                          //check sum to send as serial
float voltage = 5.26;                           //system voltage
bool data[8] {0, 0, 0, 0, 0, 0, 0, 0, 0};       //keypad output call

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

void loop() {

  int key = keypad.getKey();

  if (key) {
        data[key] = 1;

    //checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
    //Serial.print(iAm);
    //Serial.print("/");
    Serial.print(data[1]);
    Serial.print("/");
    Serial.print(data[2]);
    Serial.print("/");
    Serial.print(data[3]);
    Serial.print("/");
    Serial.print(data[4]);
    Serial.print("/");
    Serial.print(data[5]);
    Serial.print("/");
    Serial.print(data[6]);
    Serial.print("/");
    Serial.print(data[7]);
    Serial.print("/");
    Serial.print(data[8]);
    Serial.print("/");
    Serial.print(data[9]);
    Serial.print("/");
    Serial.print(voltage);
    Serial.println("/");
    //Serial.println(checkSum);

  }

}

i can edit the index location by typing data[1] = 1 but not as a variable so i suspect an index cant be addressed as int? but i don't know what it should be addressed as or how to change it to that.

im fairly sure this returns an int -- Wrong. It returns a char. You need to then convert that to an integer before you can use it as an array index. Hint: subtract zero.

{'1','2','3'}, {'4','5','6'}, {'7','8','9'} these are ASCII characters ... the array is equal to {49, 50, 51}, {52, 53, 54}, {55, 56, 57} ... take a wild guess what the array should be, if you want values of 1 to 9

not going to pretend i understand why all my keypad numbers are 48 higher than the number printed on the keypad but:
int key2 = key -48;

works

One word to google: "ASCII".