text:
processing data received via serial
Hey i'm trying to make an Arduino that can log key presses from a keypad and save that as a variable. When it receives information from another arduino via serial I want it to create a variable from each position (like comma separated values "/" in this case).Then if its being asked for its data by the master to transmit its string of data.
The code I have below is recording key presses, when it receives serial it puts it in to a string then looks at the first position in that string this becomes the variable RSVP, if RSVP is equal to the Arduinos address (iAm) and later if the checksum adds up, I would like it to respond with its serial string.
for some reason every serial command i send to it, it mirrors back the command i sent to it correctly but when i tell it to separate the first position in to the RSVP variable it always returns 1. Not sure if this is to do with converting characters to integers or something if that's all then hopefully an easy fix once you know how.
I have seen a few posts saying its best to use an array rather than a string (but this is based on the IDE serial example so not sure if that's correct)and presumable would need fully re writing which doesn't sound like an easy fix. Also I don't know how I would go about making an array from serial, and I might not to know how to separate CSVs I have seen a few examples but unfortunately i'm a dimwit. Been on this one problem for 3 days now and i'm still in exactly the same place, but with a slightly fried brain.
#include <Keypad.h>

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

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
int data[20] {0, 0, 0, 0, 0, 0, 0, 0, 0};       //keypad output call
char rsvp = 0;
int rsvp1 = 0;
void setup() {
  Serial.begin(9600);

  inputString.reserve(200);    // reserve 200 bytes for the inputString:
}

void loop() {

  int key = keypad.getKey();

  if (key) {
      int key1 = key -48;

      if (data[key1] == 1){
       data[key1] = 0;

      }
      else {
        data[key1] = 1;
      }

  }
    // print the string when a newline arrives:
  if (stringComplete)  {
    rsvp = inputString.charAt(0);
    rsvp1 = int(rsvp);

    if (rsvp1 = iAm) {
      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(inputString);
      Serial.println(rsvp1);
      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);
    // clear the string:
    inputString = "";
    stringComplete = false;
    }
  }
}
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  de
   if (Serial.available() > 0) {
    int recieved = Serial.read();
    if (recieved == iAm){
      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);
    }
   }
}

the program does not record the sequence of keypresses ... it only records which keys were pressed ... is that the desired behavior?

yea that's correct, its just to tell the master which outputs it would like off or on, the master will reply telling the keypad which outputs are on which will turn on an associated LED on the keypad. any additional keypads on the same serial network will also get  the message and know to update their demand for outputs to the current master state.

do you have an answer to the original question jsotola?

one of your if statements does not evaluate the comparison of two values, but actually assigns the value of one variable to another variable ... it is what is called a logic error ... syntax is correct, but the if statement does not do what you expected

main question is why are you not debugging the code? ... i see no serial.print() statements throughout your code, so that you could see the value of variables as the program execution progresses

the debugging serial prints are here if (rsvp1 = iAm) {
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(inputString);
Serial.println(rsvp1);
Serial.print(iAm); rsvp1 and iAm are the variables being compared in the if statement that was causing problems, so the serial prints are immediately after the part of the code that was causing the issue, is there a better place for the debugging to be done, or a better way of doing it? thanks,  the == got me closer.

use your immagination ... do not assume that a variable has some particular value ... for instance, rsvp = inputString.charAt(0); ... you don't actually know the value of rsvp after that statement executes


text:
4 Digit 7 segment display flickering
I am attempting to make an Arduino counter using a 4 digit 7 segment display. The problem I am encountering is the display flickers. I am using an Arduino Uno and 5641AS digit display (so common cathode). Here is my program:
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
    Serial.println("The value of buttonPress is:  ");
    Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}

I suspect this issue has to do with sevseg.refreshDisplay(), I have tried moving it in the program with no avail. My wiring is correct, as the program displays the correct digits. Thank you!

It's probably the spamming of the serial that's slowing everything down.

remove the serial code and the button code ... display 1234 only ... does it still flicker

Thank you so much Majenko and jsotola!! Running the serial monitor output fixes it

With the help of Majenko and jsotola in the comments, I've got it fixed! It was the text I was displaying in the Serial Monitor that was slowing the display down. Here is the updated program that works:
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
// THE NEXT TWO LINES HAVE BEEN COMMENTED OUT FOR IT TO WORK
   // Serial.println("The value of buttonPress is:  ");
   // Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}

I'm leaving the program modifications here in case anyone else gets the same problem.

source: Stack Exchange

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

sort: votes


text:
Single LED controlled by two pushbuttons - one of which acts like a toggle switch
Trying to control this LED with those 2 pushbuttons - one button that starts a short flashing sequence, another pushbutton acts like a toggle switch, one press bulb is on, another press bulb is off.
If I switch the LED on and then push the flashing button, the on-off flashing starts but then the LED is shut off because off is the last state of the flashing sequence. How do I make the led turn to original state?
#include <ezButton.h>

const int flashing_pin = 2;
const int switch_pin = 3;
const int led_pin = 8;

ezButton button(switch_pin);

int ledState = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(led_pin, OUTPUT);
  pinMode(switch_pin,INPUT_PULLUP);
  pinMode(flashing_pin,INPUT_PULLUP);
  button.setDebounceTime(50);
}

void loop() {
  button.loop();

  if(button.isPressed()) {
    Serial.println("Press");

    ledState = !ledState;

    digitalWrite(led_pin, ledState);
  }

  if( digitalRead(flashing_pin) == LOW )   {
    doFlash(4);
  }
}

void doFlash(uint8_t number_of_times)  {
  while(  number_of_times-- > 0 ) {
    digitalWrite(led_pin,HIGH);
    delay(250);
    digitalWrite(led_pin,LOW);
    delay(250);
  }

}

To explain what I want in short;

if LED is off - flashing sequence works like "ON OFF ON OFF"
if LED is on - flashing sequence works like "OFF ON OFF ON"

digitalWrite(led_pin,HIGH); is hardwired ... digitalWrite(led_pin,!ledstate); is opposite to current state

I got it to work! But I'm confused by the loop state, in my original code there's a rule to doFlash(4); and delay 250 - but when using !ledstate, the 4 flashes are no longer 4 time (ON-OFF) cycles, it's half of it, and the 250 delay is double the time, it's half a second....so in order to get the desired "frequency" 4 flashes in 2 seconds, I need to put doFlash 8 and delay 125....can't figure out why :D but it works

My flash part of the code is this now;
void doFlash(uint8_t number_of_times)  {
while(  number_of_times-- > 0 ) {
ledState = !ledState;
digitalWrite(led_pin, ledState);
delay(125);
digitalWrite(led_pin, ledState);
delay(125);
}

i guess is that you have not looked at what you wrote very closely

ledState = !ledState does not belong in the blink code

I'll fix that - but it does work this way as I intended. But if that's bad practice in coding I'll revise it, I'm learning.

the 4 flashes are no longer 4 time (ON-OFF) cycles ... how is that the way you intended?

Oh - what I meant is that after I altered the code, the sequencing was correct and at a rate intended. But when I get the time I'll try with the fixed values for loop.

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


text:
HC-05 drops connection, then DC Motors won't stop moving 'forward'
This is my first post. I seek you guys' help with my problem. Basically, my project is a Mobile-App Bluetooth Controlled WheelChair. Everything's done except a minor problem comes out during testing. After connecting everything, the wheelchair moves accordingly to the code that I wrote. However, after a few sec/min, the HC-05 drops connection, and the wheelchair drives its own by moving forward. I hope you can understand what I am saying.
When I set the speed = 100. I think I did not face the issue as above (confirmed).
Hardware:
PowerBank
Arduino Uno
HC 05
MDD20A Motor Driver
X2 24V DC Motor
X2 12V Battery
//including the libraries
#include <SoftwareSerial.h> // TX RX software library for bluetooth

//Initializing pins for bluetooth Module
int bluetoothTx = 0; // bluetooth tx to 0 pin
int bluetoothRx = 1; // bluetooth rx to 1 pin
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

//Motor 1
int Motor1_Pin = 2;
int Enable1 = 3;

//Motor 2
int Motor2_Pin = 4;
int Enable2 = 5;

char command ; //variable to store the data
int velocity = 0; //Variable to control the speed of motor

void setup()
{
  //Set the baud rate of serial communication and bluetooth module at same rate.
  // Serial Setup
  Serial.begin(9600); // default communication rate of the HC-06 Bluetooth module;
  bluetooth.begin(9600);

  // Motor Setup
  pinMode(Motor1_Pin,OUTPUT);
  pinMode(Enable1,OUTPUT);
  pinMode(Motor2_Pin,OUTPUT);
  pinMode(Enable2,OUTPUT);

  //Setting the enable as HIGH.
  digitalWrite(Enable1, LOW);
  digitalWrite(Enable2, LOW);
}

void loop(){
  if(bluetooth.available() > 0){  //Checking if there is some data available or not
    command = bluetooth.read();   //Storing the data in the 'command' variable
    Serial.println(command);      //Printing it on the serial monitor

    //Change pin mode only if new command is different from previous.
    switch(command){
    case 'F':  //Moving the Car Forward
      analogWrite(Enable1, 175);
      analogWrite(Enable2, 175);
      digitalWrite(Motor1_Pin, HIGH);
      digitalWrite(Motor2_Pin, HIGH);
      break;
    case 'B':  //Moving the Car Backward
      analogWrite(Enable1, 175);
      analogWrite(Enable2, 175);
      digitalWrite(Motor1_Pin, LOW);
      digitalWrite(Motor2_Pin, LOW);
      break;
    case 'L':  //Moving the Car Left
      analogWrite(Enable1, 175);
      analogWrite(Enable2, 100);
      digitalWrite(Motor1_Pin, HIGH);
      digitalWrite(Motor2_Pin, LOW);
      break;
    case 'R':   //Moving the Car Right
      analogWrite(Enable2, 175);
      analogWrite(Enable1, 100);
      digitalWrite(Motor2_Pin, HIGH);
      digitalWrite(Motor1_Pin, LOW);
      break;
    case 'S':   //Stop
      analogWrite(Enable1, 0);
      analogWrite(Enable2, 0);
      digitalWrite(Motor1_Pin, 0);
      digitalWrite(Motor2_Pin, 0);
      break;
//    case 'I':  //Moving the Car Forward right
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
//    case 'J':  //Moving the Car backward right
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
//    case 'G':  //Moving the Car Forward left
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
//    case 'H':  //Moving the Car backward left
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
    break;

    //Controlling the Speed of Car
    default:  //Get velocity
      if(command=='q'){
        velocity = 255;  //Full velocity
        analogWrite(Enable2, velocity);
        analogWrite(Enable1, velocity);
      }
      else{
        //Chars '0' - '9' have an integer equivalence of 48 - 57, accordingly.
        if((command >= 48) && (command <= 57)){
          //Subtracting 48 changes the range from 48-57 to 0-9.
          //Multiplying by 25 changes the range from 0-9 to 0-225.
          velocity = (command - 48)*25;
          analogWrite(Enable2, velocity);
          analogWrite(Enable1, velocity);
        }
      }
      }
    }

  }

"HC-05 drops connection" Does this mean is no longer connected to the phone (I'm guessing)?  Or does it mean something else?

Yes, true. It has something to do with PWM. When I set the speed at 100, there is no issue with the HC-05 Connection. However, once I set the speed at 175, it doesn't go smoothly for too long until suddenly the HC-05 connection drops the connection and then the dc motor becomes malfunction and drives its own (like stuck at forward). Sorry late. I did not realize this small comment box.

You might try adding some capacitors near the VCC/GND on the HC-05.

I assume that you want the chair to stop if the connection is lost. Is the 'state' pin on your HC-05 implemented, and does it distinguish between connected and not-connected (or something else)? If it's the former you should be monitoring that state pin. Otherwise, your Arduino and the mobile app need to agree on an "Are you there?" protocol; a handshake that takes place every 0.5 sec or so (off the wall guess!), and if the chair controller hasn't got a response darn near immediately, it stops. If the mobile misses a response, it should send a 'stop' (a backup which might not be heard by the chair controller), and alert the operator.
It wouldn't be a half-bad idea to have a watchdog timer (in hardware) on the chair that stops the motors if the chair controller doesn't reset it on short intervals. The chair controller is software; software sometimes fails. You'd like to detect that in hardware in time to cut the drive to the chair before it hits an obstruction or drives into the street.


text:
Interfacing Figaro TGS2600
I am trying to interface TGS 2600 gas sensor to Arduino, particularly to detect methane gas.
Can anyone tell me the conversion equation between Rs/Ro and ppm, so that I can get ppm values from the Rs/Ro ratio. I am looking to detect between 1-10ppm.


text:
How to write & read from SPIFFS file as object data on ESP8266
I am trying write four digit number to SPIFFS file, and read that four digit from SPIFFS file and display on seven segment.
The code, I am writing as below, I got "0" on each segment, but if manually make number = 4567; then seven segment show proper number on every segment.
Please help me to learn more about how to read & write and convert to object data.
Here is my code;
#include <FS.h>

const char* filename = "/InputInt.txt";
int digit_1 = 0;
int digit_2 = 0;
int digit_3 = 0;
int digit_4 = 0;

int Anode_1 = 16;
int Anode_2 = 14;
int Anode_3 = 5;
int Anode_4 = 4;
int count = 0;
int digits[4] ;
int AnodePins[4] = {4, 5, 14, 16};

int clockPin = 12;
int latchPin = 13;
int dataPin = 15;

int number = 0; //declear the variables

byte numbers[10] {B00000011, B10011111, B00100101, B00001101, B10011001, B01001001, B01000001, B00011111, B00000001, B00001001};

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

  bool success = SPIFFS.begin();

  if (!success) {
    Serial.println("Error mounting the file system");
    return;
  }
  SPIFFS.format();
  File fw = SPIFFS.open(filename, "w");

  if (!fw) {
    Serial.println("Error opening file for writing");
    return;
  }
  char Written = fw.print("1234");

  if (Written == 0) {
    Serial.println("File write failed");
    return;
  }
  fw.close();

  pinMode(Anode_1, OUTPUT);
  pinMode(Anode_2, OUTPUT);
  pinMode(Anode_3, OUTPUT);
  pinMode(Anode_4, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

} //End of setup

void loop() {
  int i;
  File fr = SPIFFS.open(filename, "r");

  if (!fr) {
    Serial.println("Failed to open file for reading");
    return;
  }

  for (i = 0; i < 4; i++) {
    byte number = (Serial.write(fr.read()));
  }
  fr.close();
  break_number(number);
  display_number();
  delay(3000);
} // End of loop

// seperate the input number into 4 single digits
void break_number(int num) {
  Serial.println("");
  digit_1 = num / 1000;
  digits[0] = digit_1;
  Serial.print(" Digit_1: ");
  Serial.println(digit_1);
  int dig_1_remove = num - (digit_1 * 1000);

  digit_2 = dig_1_remove / 100;
  digits[1] = digit_2;
  Serial.print(" Digit_2: ");
  Serial.println(digit_2);
  int dig_2_remove = dig_1_remove - (digit_2 * 100);

  digit_3 = dig_2_remove / 10;
  digits[2] = digit_3;
  Serial.print(" Digit_3: ");
  Serial.println(digit_3);
  digit_4 = dig_2_remove - (digit_3 * 10);

  digits[3] = digit_4;
  Serial.print(" Digit_4: ");
  Serial.println(digit_4);
}

void display_number() {                                             //scanning
  digitalWrite(AnodePins[count], HIGH);                            //turn on the relevent digit
  digitalWrite(latchPin, LOW);                                      //put the shift register to read
  shiftOut(dataPin, clockPin, LSBFIRST, numbers[digits[count]]);    //send the data
  digitalWrite(latchPin, HIGH);                                     //put the shift register to write mode
  delay(0);
  digitalWrite(AnodePins[count], LOW);                            //turn on the relevent digit
  count++;                                                          //count up the digit
  if (count == 4) {                                                 // keep the count between 0-3
    count = 0;
  }
}

Here is the result;
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0

Thanks,

I directly see 3 problems with your code:

Serial.write() will not return the written data, but the number of send bytes. This means that in your for loop you are only assigning the written number of bytes to the variable, not the data. But I guess you want to display the actual data, which was read from the file. You should assign the return value of fr.read() to a variable. Then you can send it via Serial.write() and still use that variable for other things later (like displaying).

You need to look into variable scope. You have a global variable number. But in the for loop you are defining a local variable with the same name via
 byte number = ...

This variable is only valid in that specific for loop iteration. When the iteration ends, the variable is thrown away and redeclared in the next iteration. It will not be there anymore, when you leave the for loop. So currently you are saving your data in a variable local to the for loop. It does NOT touch the global variable. Thus the other functions only see the value zero, with which the global variable number was initialized. You can remove the type byte before the variable in the for loop. That makes it an assignment instead of a definition. Thus then you really write the data into the global variable.

Data encoding: Clearly you have your number in the file as ASCII encoded text. But you seem to handle it as binary data. That cannot work. For example: When you read the first character of 1234 (which is written in the file), then you get '1' (the character, not the number). When looking at an ASCII table you can see, that this character corresponds to a decimal number of 49 (or 0x31 in hex). You can convert an ASCII encoded digit to a real number by subtracting the value of the character '0':
 int number = fr.read() - '0';

or
 int number = fr.read() - 48;

(both are equivalent).
Also you are currently just saving the read character into a single variable. That means, that after the for loop only the last character is left. Since this is a composite number, you should do something to compose it. Like this:
 number = 0;
 int factor = 1000;
 for(int i = 0; i<4; i++){
     number += (fr.read() - '0') * factor;
     factor /= 10;
 }

Note: This is untested, it is not the best way, but the easiest at this point, and it only works for numbers between 1000 and 9999 (4 digit numbers). You can implement this more versatile.
First we are resetting the number variable, so that old values are not getting in our way. We are using a variable holding the current factor (starting with 1000, since that is the figure in which the first digit lies). Then we go through the 4 characters, reading them. We subtract the character '0' (as described above) and then multiply by the factor. That resulting number is added to the variable number. Then we divide the factor by 10 (getting from 1000 to 100, then to 10 and finally to 1). At the end we can use number like any other integer variable.

Alternative implementation of reading the number, which is suitable for different numbers of digits:
number = 0;
// Prepare character buffer to read the number in
char buffer[10] = ""; // space for maximum 9 digits
int pos = 0; // position variable in the buffer
while(fr.available() && pos < 9){ // loop while there is data left to read in the file or we have no pace left in buffer (leaving one character for the terminating null character
    char c = fr.read(); // read character into variable
    if(isDigit(c)){
        buffer[pos] = c; // save digit in buffer
        pos++; // increment position for the next character
    } else {
       break; // break out of loop, if read character is not a digit (we don't want to read further when a non-digit character comes up)
    }
}
buffer[pos] = 0; // terminate buffer with null character
number = atoi(buffer); // use standard function to convert to integer number

Note:

This code is not tested, though it compiles without errors
You see, that it is not smaller, than the other one, but can handle different number of digits.
You can still use the first version with smaller numbers, if you always pad them with zeros. So instead 991 you would write 0991 to the file. That will make the first version work.

Thanks Chrisl, I have edit the way you mention, it'sworking well now, you are absolutely right.

Please let me know, how to keep number as four digit (OCT), number is 1000 and minute 4 should display 0996, but display 9911.

Sorry, I don't quite understand. Please explain more clearly

Ok, write number 1008 into file, then read it correct in display, I add some code in loop the final number = number -4; and display number again, start correct from 1008, 1004, 1000, and go to 9911 instead of 0996.

You almost certainly don't pad the number with zeros to 4 digits, when writing it to the file. As I wrote, that will break the code snippet. I added another way of reading the number, which also supports other digit numbers.


text:
Arduino IDE 2.0 Beta doesn't start
Yesterday i downloaded the new version of the IDE to take advantage of all the new features, but it just won't open. I tried installing it to different paths, different PC's, i deleted the package_index.json and the cache folder, but nothing. It stucks in the opening screen (see image below), any other ideas?

Run it from the command line and see what errors you get? Maybe raise an issue on the github repo. It's beta software. Don't expect it to work, and if you want to use it, be prepared to debug it.

I've used v1.9 beta for 2 years; it has been stable and lots faster than 1.8 which was miserably slow to launch (macOS). 2.0 beta is described as "Experimental Software". Based on that, and your experience, I'd probably call it 2.0 alpha. But, yeah, if it's not a released version, somebody doesn't feel it's ready for prime time.

Arduino IDE 2.0 is a very slow start up. How long did you wait? I've since uninstalled it. I recall the start up splash screen being there at least a minute, which is longer than most people would normally wait for a splash screen.

FWIW, I'm running Beta 7 on a 2019 MBP w/ 16G and it's ready to go in about 7 sec, and that's w/ a hefty suite of Docker microservices running and RubyMine and DataGrip in the throes of a large project.

I have a very slow internet connection and the Arduino IDE seems to depend a lot on it. When I launch it, I shut down internet and it opens in a breeze.

About the only time arduino-cli cares about your connection is when you're downloading new board definitions or libraries.

Perhaps you meant "and the Arduino IDE 2.0 seems to depend a lot on it." ?

Noted. I guessed it was the cli the one blocking it from the notification pop-up you get when you start it offline.


text:
Make an LED Turn
//Make an LED Turn ON after pressing a push button switch for five times. Add a reset switch to turn OFF the LED whenever the reset switch is pressed

**void setup()

{

  pinMode(11, OUTPUT);

  pinMode (4,INPUT);

}

void loop()

{

  int y= digitalRead(6); // push button 2

  static int counter {} ;

  int x= digitalRead(4);// push button 1

  if (x==1&& y==0 )

    counter++;

else if (counter == 5) // If counter is pressed 5 times

{

  digitalWrite(11, HIGH); // Turn on the LED

}

if (counter >= 5) // If counter is greater than 5 led will still on

{

  digitalWrite (11, 1);

}

  else if

   (y==1&& x==0 ) // if pressed push button 2  led of
  {

    digitalWrite(11,0);

}

  counter = 0; // Make counter variable = 0

}

Is that a school assignment? What have you tried so far? Where exactly is your problem in implementing this? Have you looked at some of the numerous tutorials online, which teach how to blink an LED and how to read buttons? Btw: For button reading I can suggest the Bounce2 library, which is really helpful

my problem i don't know how to make LED on after press push buttons five times

Remember using either a pullup resistor or INPUT_PULLUP in the setup.

You can try implementing a counter system in your Arduino program.
For example, if this is your loop() function:
void loop(){
int buttonState = digitalRead(1); // Give the variable buttonState the value of pin 1, or whatever your button is connected to
static int counter{}; // Have a counter variable. Static means it doesn't reset to 0 after loop() restarts

if (buttonState == HIGH) // If the button is pressed
{
  ++counter; // Increase the value of counter by 1
}

else if (counter == 5) // If counter is pressed 5 times
{
  digitalWrite(11, HIGH); // Turn on the LED
}
// RESET:
if (counter > 5) // If counter is greater than 5 (you clicked the button again)
{
  digitalWrite (11, LOW);
  counter = 0; // Make counter variable = 0
}
}

Edit In the comments, Python Schlage made very good suggestions: to change buttonState to a boolean and change int to byte to save space on board the Arduino
Try following this tutorial: https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button and modifying it to work with the counter.
Hope this helps! Please let us know if you need help with the setup() function or if anything is unclear.

For saving memory, buttonState can be changed into a Boolean and counter can be a byte. The else part is pretty useless, because it will just turn the LED off all the time, although it already is on LOW.

Good points Python Schlange! I'll add in a modified version with your suggestions


text:
Arduino IDE not seeing Arduino library
Working on my first real Arduino project.
I opened my code in the Arduino IDE and hit build and I get errors "not declared in the scope" on every single call to the Arduino library. For instance, digitalWrite, digitalRead, INPUT, OUTPUT, etc.
I open other projects with my Arduino IDE and they build fine, so it's clearly the code in this project. I've restarted. No change.
Ideas?

If it's "clearly" the code in the project them maybe it would be a good idea to show us that code?

Still not sure what the problem was, but I included Arduino.h and everything worked. This is a hack, but an effective one. If someone else knows what I did wrong, let me know.

It would have been better to develop the question into something where the answer followed from it.  Given your answer, it seems likely that you were not using an .ino (or .pde) extension.  Something that would have revealed itself if you'd put verbose output from the compilation stage.  You should do that in future questions, along with the code, etc.

No, was using an ino. The only posting of code would have been my entire project, which is not small. Since the code belongs to my client, I have concerns about doing that. I would love help, but the price is a bit high in this case and I'll have to settle for a hack workaround.

I'm not going to down-vote this, but for me, what you're describing as an answer would have to be demonstrated to be believed.  If you have an .ino file but the code you're actually talking about is in a non-.ino file, e.g. header, then the answer makes sense, but this fact should be mentioned somewhere.  The Arduino build process does add this #include to your .ino files, originally called WProgram.h since Wiring, before "Arduino" even existed.


text:
Motor not working when using Nano 33 BLE and transistor because of low voltage
I'm a beginner using a new Arduino Nano 33 BLE to power a low voltage motor. I've tested that the motor can run using a standard 1.5V AA battery when connected directly, but I cannot get it to work when using the Nano to complete the circuit using a BC547 transistor.
I've attached a photo of my circuit that's as clear as I could get.

The 1.5V motor is attached on the orange wires, I couldn't fit it in the photo.
The code I've uploaded to the Nano is as follows:
int power = 1023;
int outPin = D10;

void setup() {

  pinMode(outPin, OUTPUT);
}

void loop() {
  digitalWrite(outPin, HIGH);
  delay(1000);
  digitalWrite(outPin, LOW);
  delay(1000);
}

When I complete the circuit with the AA battery, I can see the red LED, that's in series with the battery to the collector of the transistor, does light up but very dimly and so therefore the motor does not run either. I've also tried 2xAA and 4xAA batteries and that lights up the LED very brightly, but the motor still does not run. What could be wrong with this circuit?
Thanks!

So you have a transistor AND a LED in the circuit for the motor? The LED and the transistor will both get some of the voltage. I think the LED will dominate this. Please try without the LED

You have no series resistance for your LED.  This may not be a problem with a single AA battery, but it is a problem when you "also tried 2xAA and 4xAA".

I tried removing the LED and completing the circuit again but still no luck with a single AA.


text:
When accessing a variable from an ISR, is a volatile pointer enough?
Let's say I want to modify a global variable from inside an interrupt service routine. I must ensure that any variables I modify are volatile. Does it work to use a volatile pointer to data I want to modify if the data itself is not volatile?
In my case the data is a struct, but does the answer change if the data is a class, array, or just a variable?
#include <Arduino.h>

#define PIN_INTERRUPT  2

typedef struct MyStruct
{
    int a_field;
} MyStruct;

MyStruct struct_data;
int array_data[32];

volatile bool _flag_ISR = false;
volatile MyStruct *_struct_ISR = &struct_data;
void myISR()
{
    // just some example stuff
    int read = digitalRead(PIN_INTERRUPT);
    _struct_ISR->a_field = read;
    _arr_data_ISR[4] = read;

    _flag_ISR = true;
}

void setup()
{
    attachInterrupt(digitalPinToInterrupt(PIN_INTERRUPT), myISR, CHANGE);
}

void loop()
{
    if (_flag_ISR)
    {
        // do processing here...
        _flag_ISR = false;
    }
}

I think I misunderstood your question the first couple passes through, probably because (I'm guessing) by "volatile pointer" you really meant "pointer to volatile" and the distinction is important.  So, are you asking: "with respect to communicating between the ISR and the main line of execution, is it sufficient to use a pointer-TO-volatile if the thing being pointed-to is, itself, not volatile qualified?"

First, beware that what you have written is not a volatile pointer, it's
a pointer to volatile data. If you always access the object through this
pointer, you should be fine. If you use the pointer in the ISR, but
access the data directly in the main code (bypassing the volatile
qualifier), then the program could fail.
Consider the following:
void loop()
{
    if (_flag_ISR) {
        _flag_ISR = false;
        Serial.println(struct_data.a_field);
    }
}

Once the compiler inlines the call to loop() from main(), the
main program looks like
int main()
{
    init();  // Arduino core initialization
    setup();
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(struct_data.a_field);
        }
    }
}

And now, since struct_data is not volatile, the compiler can
legitimately optimize the code by avoiding repeatedly accessing the same
RAM location:
int main()
{
    init();  // Arduino core initialization
    setup();
    register int data_copy = struct_data.a_field;
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(data_copy);
        }
    }
}

And now the program prints only zeros.

Voting yours up.  I think I took their "volatile pointer" phrasing too literally.  Assuming they confirm this understanding of what they meant your answer has pretty much everything I'd have to say about it anyway.  I'm sort of surprised you're using the register keyword.

@timemage: The register keyword is seldom useful in actual code. Here I am using it only to express the idea that the compiler can choose to keep a copy of the data in an internal CPU register (or set of registers).

It's the latter half of that that I was looking for.  You know, you're not even allowed to use it in `17.


text:
Arduino nano KiCad symbols
Can anyone explain me the difference between the symbols for Arduino nano in KiCad? Is there any important difference at all? All of them seem to have all basic pins.

Different boards with different footprints.

In short, there aren't any substantial differences.  But it makes sense to use the one that actually matches what you have.
My KICAD symbols are out of date, so I downloaded and unpacked the current archive for MCU Module symbols.  These things are defined in text files, so doing this allows you to employ the usual diff tools to them, if you break the parts of interest out into separate files, which is what I did to produce the below images.
Index Entries
Besides the name, they're different in what datasheet they refer to:

Definitions
In the below, on the left you'll see in dark blue background that both the Nano v2.x and v3.x are actually defined in the same file.  So, they are in fact sharing a definition; so, no differences there at all.  The original Nano boards varied in that some had ATMega168P and some had ATMega328P.  These are practically but not quite the same chip.  The significant difference is sizes of the various memories.  And they had different bootloaders.  Nothing that would make their symbols or footprints significantly different.
On the right is the Nano-Every, which is a fairly different beast from the older Nanos in that it's an ATMega4809, one of the new-series AVR parts, and different significant ways greater than just memory sizes.  But, it was designed to have the same layout as the prior Nano boards.  They even went so far as to make classes and objects to try to "emulate" the more traditional style GPIO ports of the Nano for Nano Every users.
As you can see there's really no differences besides the names of the pins and a few changes in drawn locations between the v2/v3 symbol on left and the "Every" symbol on the right.  Some of the pin names are different, but it's the pin numbers that matter when mating it to a footprint in Kicad, and those are the same between the two.
For whatever reason pin number 29 changed from W (in 2/3) to N (in "Every"), which according to their documentation is a change from power input to not connected.  I suppose this might make a difference between whether or not you need to add a PWR_FLAG symbol somewhere in your design to satisfy electrical rules check (ERC).  In the "Every", for whatever reason when they (slightly) rearranged the pins locations in the symbol, they stuck pin number 29 right on top of pin 4.  So, if you're having a hard time seeing pin 29, that (and the light gray text) are why.

Thank you for the excellent answer.


text:
Problem using sequential loop
So I have created this project to have an LED blinking at a constant speed whenever the program is running. The first LED (green) will blink faster and faster the closer an object gets to the sensor. The second LED (Blue(is referenced in code as white)) should be blinking constantly. The LED (blue) is only blinking when my ultrasonic sensor has something in range. I would like to make it so it blinks no matter the circumstances.
This is probably something obvious Im missing - excuse my noob-ness
NOTE: if the picture of the circuit isnt correct (pins not being correct) know that it is correct in real life, this is what I get for doing a quick mock up and post at 1:00 AM
#include "DHT.h";

#define DHTTYPE DHT22   // DHT Type is DHT 22 (AM2302)
#define DHTPIN 7       // DHT-22 Output Pin connection
#define trigPin 5
#define echoPin 6
#define beepPin 12
#define scalingfactor 10
#define blueLed 11

#define ledPin2 10

float hum;    // Stores humidity value in percent
float temp;
float soundsp;
float soundum;
 DHT dht(DHTPIN, DHTTYPE);  // Initialize DHT sensor for normal 16mhz Arduino

int centi = 0;

const long erval = 500;

unsigned long previous = 0;
unsigned long lastduration = 0;
unsigned long duration = 0; //time it takes for sound to return
unsigned long maxtime = 2000;
unsigned long i = 1;  //variable to determine actual distance
unsigned long time2 = 0;
unsigned long time1 = 0;

void setup() {
  Serial.begin (9600);  //open monirot channel
  dht.begin();  //start temp and humidity sensor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(beepPin, OUTPUT);
  pinMode(blueLed, OUTPUT);
}

void calculate(){
      // Calculate the Speed of Sound in M/S in accordance with temp
    soundsp = 331.4 + (0.606 * temp) + (0.0124 * hum);

    // Convert to cm/us
    soundum = soundsp / 10000;
}

void logdistance() {
  digitalWrite(trigPin, HIGH); // send sound signal
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);  // stop sound signal
  duration = pulseIn(echoPin, HIGH);  // listen for sound signal
  centi = (duration* soundum)/2;   // determine delay of sound signal in one direction
  maxtime = scalingfactor * centi;  // change max time in accordance to the distance of the previous object
}

void beep() {
  digitalWrite(beepPin, HIGH);   // turn on the beep pin (or LED pin)
  delay(60);
  logdistance();   // run the log distance function again so we get accurate data
  if (time2 - time1 < 30) {  // delay based on how close an object is
    delay((60 - (time2 - time1)));
  }
  digitalWrite(beepPin, LOW);  // turn off beeper (or LED)
  i = 1;
    while (1) {
    if (i % 60 == 0) {
      logdistance();  // run my log distance funciton
    }
    delay(1);
    ++i;  // add one to i to report that we have recorded the distance
    if (i >= maxtime) { // dont report distanc if sound took longer than max time to return
      break;
      }
    }
}

void BlinkBlue (int interval){
   static long prevMill = 0;
   if (((long)millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(blueLed, !digitalRead(blueLed));
   }
}

void temps(){
  hum = dht.readHumidity();  // Get Humidity value
  temp= dht.readTemperature();  // Get Temperature value
}

void loop() {
  BlinkBlue(500);
  beep();

  temps();
  calculate();

  //print results
  Serial.print (duration);
  Serial.print("c. ");
  Serial.print(centi);
  Serial.print(" ");
  Serial.print(temp);
  Serial.println(" ");
}

Start with the BlinkWithoutDelay example and go from there.

are you saying I need to save a log of my led blinks? The LED's blink based off when an object is detected. would that interfere with the process of it measuring distance?

sorry again- definitely new to this: im probably not picking up what youre putting down

In the IDE look at the File -> Examples menu. In there somewhere is one called "BlinkWithoutDelay". That will teach you how to do your LED blinking in a "non-blocking" manner so they don't interfere with each other.

okay so Ive made a few changes to the project. Ive updated the problem itself.

Look at “BlinkWithoutDelay” and apply that logic to both LEDs.


text:
Minimal example of Task Scheduler Blink?
Scheduler_example00_Blink is ~300 lines. For just an Arduino Uno, what is a minimal example?
It's hard to know what belongs and what doesn't. This example has six different approaches, and I'm just trying to extract one of them.

what about the scheduler template?

the main GitHub page for the library has a link to an awesome web based Arduino emulator .... https://wokwi.com/playground/task-scheduler ... try deleting sections of code until you are left with minimum

i don't see it as being personal ... i am glad that you were able to work through it ... learning experience ... please don't forget to accept your own answer

#include <TaskScheduler.h>

// Scheduler
Scheduler ts;

/*
   Approach 1: LED is driven by the boolean variable; false = OFF, true = ON
*/
#define PERIOD1 500
#define DURATION 10000
void blink1CB(); // <-------------------------------------------|
Task tBlink1 ( PERIOD1 * TASK_MILLISECOND, DURATION / PERIOD1, &blink1CB, &ts        , true );
//           (     500 * 1UL (ms)        , 100000 ms/ 500    , function , just put it,  ?   )

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  ts.execute();
}

inline void LEDOn() {
  digitalWrite( LED_BUILTIN, HIGH );
}

inline void LEDOff() {
  digitalWrite( LED_BUILTIN, LOW );
}

// === 1 =======================================
bool LED_state = false;
void blink1CB()
{
  if ( LED_state )
  {
    LEDOff();
    LED_state = false;
  }
  else
  {
    LEDOn();
    LED_state = true;
  }
}


text:
nRF24L01 +pa +lna link does not communicate
I’m trying to create a link between two nRF24L01 units. Each nRF24L01+-based module (purchased) is connected to Arduino Nano on a custom-designed PCB.

The printed wiring is per the hardware application, and is functionally verified by the positive result of the isChipConnected() method.

The NRF24L01 is fed from the Nano 3.3V output. According to the component’s datasheet this should be OK:
•   According to the datasheet the max consumption is 9mA when transmitting in high power. The Nano output can source up to 150mA. So it doesn't close to the limit.
•   I measured the 3.3V supply line and the value is 3.23V on both modules (the specified minimum is 3.0V).
•   The supply line is being filtered by a 10uF cap.
The two stations are using the same code; the roles are being defined by the level of an IO pin. It contains two modules - the application and the high-level driver class.
Now to the problem: According to the Arduino screenshots it appears that the transmitter does not sending the data. Since the low-level transmitting routine (radio.write()) is waiting for the receiver auto acknowledge, I considered also the possibility that receiver side doesn't send the auto-ACK. However, I Switched off the auto acknowledge in both stations and the result wasn't changed.
Any clue will be helpful. Thank tou.
#define Radio0_IRQ   2
#define TerminalPin  6
#define CsnPin       10
#define terminalRole 1

String msgHeader;
bool role;
/************************************************/
void(*resetFunc) (void) = 0;//declare reset function at address 0
/***********************************************************/
#include "radioPortClass.h"
RadioPort communicationPort;

/************************************************/
void setup(void)
{
  pinMode(TerminalPin, INPUT_PULLUP);
  role = !digitalRead(TerminalPin);
  if(role == terminalRole)
    msgHeader = "Terminal: ";
  else
    msgHeader = "Field unit: ";

  Serial.begin(9600);
  while (!Serial)
    delay(10);
  if (communicationPort.portInit(role))
    Serial.println(msgHeader + "Port initiated successfully\n\n");
  else if (!radio.isChipConnected ())
  {
    Serial.println(msgHeader + "Port initiation failed\n\n");
    delay(2000);
    resetFunc();
  }
}
/***********************************************************/
void loop(void)
{
  if (role == terminalRole)
  {
// Terminal role. Transmit a message and receive the reply
    if (!communicationPort.tx("Terminal to field unit"))
      Serial.println(msgHeader + "Failed, transmit timed out.\n\n");
    else
    {
      Serial.print(msgHeader + "Got response: ");
      delay(1000);
      Serial.println(communicationPort.rx());
      started_waiting_at = millis();
    }
    delay(3000);
  }
  else  // Field unit role. Receive each packet, print it and reply
  {
    String receive_payload = communicationPort.rx();
    if (receive_payload == "\0")
    {
      if((millis() - started_waiting_at) > rxDelay)
      {
        Serial.println(msgHeader + "Failed, receive timed out.\n\n");
        delay(100);
        resetFunc(); //call reset
      }
    }
    else
    {
      Serial.print  (msgHeader + "Got payload: ");
      Serial.println(receive_payload);
      if (!communicationPort.tx("Field unit to terminal"))
        Serial.println(msgHeader + "Failed, transmit timed out.\n\n");
      else
        Serial.println(msgHeader + "Sent response.\n\n");
    }
  }
}

Radio Driver
class RadioPort
{
  public:
    bool tx(String txData);
    String rx(void);
    bool portInit(bool role);
};
#include "RF24.h"
RF24 radio(9, CsnPin);

const uint64_t pipes[2] = {0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL};
#define rxDelay   1000
#define txDelay   100
unsigned long started_waiting_at;

/************************************************/
bool RadioPort::tx(String txData)
{
// First, stop listening so we can talk.
  radio.stopListening();
  bool success = radio.write(&txData, txData.length());
  radio.startListening();
  return success;
}
/************************************************/
String RadioPort::rx(void)
{
 // if there is data ready
  if (radio.available())
  {
// Fetch the payload, and see if this was the last one.
    uint8_t len = radio.getDynamicPayloadSize();
    char receive_payload[len + 1];
    radio.read(receive_payload, len);
// Put a zero at the end for easy printing
    receive_payload[len] = 0;
    return receive_payload;
  }
  else return "\0";      // Dummy statement, for the compiler warning
}
/************************************************/
bool RadioPort::portInit(bool role)
{
  pinMode(Radio0_IRQ, INPUT_PULLUP);
  radio.begin();//(5,CsnPin)
  if(!radio.isChipConnected ())
    return false;

  radio.enableDynamicPayloads();
  radio.setRetries(15,15);
  radio.setPALevel(0, true);
  radio.setChannel(105);
  radio.setAutoAck(false);//true);

  if (role == terminalRole)
  {
    radio.openWritingPipe(pipes[0]);
    radio.openReadingPipe(1,pipes[1]);
  }
  else
  {
    radio.openWritingPipe(pipes[1]);
    radio.openReadingPipe(1,pipes[0]);
    started_waiting_at = millis();
  }
  radio.startListening();
  return true;
}

"According to the Arduino screenshots" what screenshots? Are you confirming that each Arduino is in its correct role?

Yes: I open a serial monitor for every station. As can be seen from the code, the major activity of the LOOP method of the sketch is printing messages to the serial, which are visible on the serial monitor. All the messages are invoked by failure feedback of the tx and rx methods. The messages are prefixed with the station role, so I know which one sent it.


text:
Problems with compiling more then one sketch in the Arduino IDE
I found this ESP8266-MQTT program on Github.
How can I compile this thing with the Arduino IDE?
I only can open one sketch at a time. If I try to compile this then parts of the program are missing for AVRDUDE - but they are in the same folder.
Please can you help me?

Looks like it is all one sketch, though there are multiple .ino files... but the project folder name has to be exactly "ESP8266-MQTT-to-Serial-Bridge", that tells the Arduino IDE that the main project file is named "ESP8266-MQTT-to-Serial-Bridge.ino". The other files contain additional supporting code and must be in the same folder.

thanks but it did not work :(      I have tried both ways.

I can open it in Arduino IDE 1.8.13, but can't build on my system due to missing library (ESP8266WiFi.h: No such file or directory). Not really a avrdude issue. Can you update your question to show exactly what error messages you get (Sketch | Verify/Compile, then "Copy error messages")

Thanks for your answers. I get messages that parts are missing. You must make from ESP8266WiFi.h to WiFI.h I have a ESP32 and i am using Ubuntu.

Related: https://arduino.stackexchange.com/questions/35117/fatal-error-esp8266wifi-h-no-such-file-or-directory

Related: https://arduino.stackexchange.com/questions/48669/includeesp8266wifi-h-showing-error-message

Related: https://arduino.stackexchange.com/a/58751/7174

thanks but this are not liberys. This are parts of the sketch.

Related: https://arduino.stackexchange.com/questions/71405/whats-the-relation-between-arduino-standard-library-and-esp8266-library

thanks but i have no libery proplem!!!

"I have a ESP32" and... "ESP8266-MQTT-to-Serial-Bridge" ... see the problem?

ok thanks  But normaly i can use a sketch for both.

I could compile the program fine, when I removed all lines with #include <String.h> (I don't know, why this is included, since the String class in Arduino is available without including something). Just open the ESP8266-MQTT-to-Serial-Bridge, then the Arduino IDE will open with that sketch and the other files (cpp, h, ino) will be in the same window in different tabs.

Though I compiled for the ESP8266. You cannot compile that for the ESP32

That sketch is written for the ESP8266, not the ESP32. The two are very different chips, and the libraries used are very different.
You will have to learn how the sketch works, and how the ESP32 libraries work, and port the sketch to the ESP32 once you have learned how.

thanks Is there some sketch for the ESP32 ?

There are plenty of sketches for the ESP32. One that does that exact same thing? Dunno. Ask Google.


text:
How would one send radio signals from Arduino at a non-standard frequency
TL;DR: How would one send a fixed radio signal at 447,54MHz with Arduino?
Background: I recently purchased a (receive only) SDR and recorded my garage door fob. I found it sends a fixed signal at the frequency 447,54MHz, which I was able to decode. Now I want to try activating the garage door via Arduino. The standard 433MHz senders obviously don't work, since they have a totally different frequency.
I tried searching for senders of my frequency (447MHz) and also for senders with different or variable frequencies. I didn't really find much. Also I read in some post (that I don't remember currently), that building an own sender circuit is not easy (since the exact PCB design plays a big role in the behavior in the ciruit). It didn't seem, that this would be a valid way for me.
Has someone here experience with such frequencies? While I know, that this site doesn't do product recommendations, maybe I just searched for the wrong term and you can help me with that. Or maybe there are no (or very very few) "maker-ready" products for this out there currently. Maybe the creator of the garage door system wanted a non-standard frequency for security-through-obscurity (since that doesn't protect against attackers with a sending SDR).
Also I researched about frequency bands. Normally I would think of a garage door fob as a Short Range Device (SRD), but instead my frequency is right above (and outside) of the band PMR. Maybe this is because the system is really old (can easily be between 15 and 30 years).
I'm kinda lost on how to proceed here, or if proceeding is even viable here.

you have to find a 447,54 MHz transmitter that has a digital input pin ... your question is not about Arduino, so you are limiting your success by posting here

Did you try tuning the standard 433 MHz receiver, adjusting the coil parameters for your secret frequency and don't share your frequency someone can jam your signal or listen to incoming data!

@Avon97 Is it possible to detune a standard 433MHz sender with different coils to a frequency so far away from 433MHz? The sender modules that I have don't even have  a coil on them, though I know, that many others that you can buy have (a fixed) one. I shared the frequency, because it is integral to the question. And its really security through obscurity. If someone would really want to jam my signal, he could just record your fobs signal with an SDR (for example, when we go out for work) to get the frequency. Just as I did.

447 MHz is not realy a problem to build. The little chinese 433 MHz T/R module  pairs prove that. ;-) But there are legal issues you could run into outside of a public band. Here is an example: https://www.cdt21.com/wp/wp-content/uploads/support/download/docs/DS_STD-302Z-447.pdf Search for PLL Synthesizer (Modules|Chips) for 447 MHz to find more.

Try to receive a 433 MHz device (a car key or something) on your SDR just to double check your setup.

@Wirewrap I have already done that. The 433MHz signal of my 433MHz sender modules are received exactly as expected. So I don't have any reason to not believe my frequency measurement of the fob signal

The standard 433MHz senders obviously don't work, since they have a totally different frequency.

I think "433 MHz" is used as a band name, with 433 MHz actually being at the lower limit of a band that covers approximately 40 MHz. Your garage door opener will likely be referred to as a "433 MHz garage door opener", even though it operates at 447.54 MHz.
For your experiments, you might try the HC-12 module. It's billed as a 433 MHz radio, but in fact it covers 433 MHz to 473 MHz in 100 bands with 400 kHz spacing, so it will cover your desired 447.54 MHz. The link above has some Arduino code examples that might help get you started. And of course there is much more information on this topic if you're interested.


text:
Why isn't my ESP32 staying in Deep Sleep longer than 35 minutes?
I've been having an odd issue with a new custom ESP board. I can't push deep-sleep time past 35 minutes no matter how I adjust the timing.
Below is my current pertinent code, but basically the device wakes up, reads several environmental sensors, sends them to the cloud and then turns off. I'm aiming to sleep for an hour between readings to preserve battery power.
 #include <esp_deep_sleep.h>

int SLEEP_TIME;

#define uS_TO_S_FACTOR 9e9  //Conversion factor for micro seconds to seconds
#define TIME_TO_SLEEP  9e8 //Time ESP32 will go to sleep (in seconds)

SLEEP_TIME = (uS_TO_S_FACTOR * TIME_TO_SLEEP);
esp_sleep_enable_timer_wakeup(SLEEP_TIME);

esp_deep_sleep_start();

use uint64_t instread of int. and prefix hex constants with 0x

@Juraj Thank you! This worked great.


text:
lcd byte array display
when reading RFID(MIFARE) information using Arduino mega and display in serial monitor it works fine. But, when printing on 2004LCD only one information(Value) displays correctly. The other information Item Name display a decimal number. Could someone help on this?
 void Price(){
      block = 4;
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      status = mfrc522.MIFARE_Read(block, buffer1, &len);  // ***Note down buffer1 within the bracket
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failedl: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
             //Display price information...
      for (uint8_t i = 0; i < 16; i++)
      {
        if (buffer1[i] != 32) // if buffer1[i] not equal to 32
        {
          Serial.write(buffer1[i]);  //Price
         //lcd.write(buffer1[i]);
          Value = buffer1[i];
          }
       }
      Serial.print("/=");
      Serial.println(" ");
      sscanf(buffer1,"%d",&Value);
      lcd.setCursor(0,1);
      lcd.println(Value);

     }
    //==========================================================
    void Item(){ //----- Get & Display Item information
        block = 1;
     status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      status = mfrc522.MIFARE_Read(block, buffer2, &len);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      for (uint8_t i = 0; i < 16; i++) { //
         Serial.write(buffer2[i]);       // Display Item
         lcd.write(buffer2[i]);
         Item_Name=buffer2[i];
        }
        sscanf(buffer2,"%s",&Item_Name);
       //sprintf(buffer2,"%d",&Item_Name);
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(Item_Name);// displays numbers instead of "Fresh Milk 1Lt
     }

What is the data type of Item_Name?

data type is int

sscanf(buffer2,"%s",&Item_Name); works however return a number instead an string.

Consider the following:
char buffer2[16];  // array of 16 chars
for (uint8_t i = 0; i < 16; i++) {
    do_something_with(buffer2[i]);  // handle one char at a time
}

Here we have an array of 16 cells, each having the char type (which I
assume is what you have). The loop goes through the array, handling one
cell a time. Within the loop, buffer2[i] represents the char being
currently handled.
Keep in mind that a char is just an 8-bit integer. It is somehow
implied that it is meant to represent a character, where 32 = ' '
(space), 33 = '!', 48 = '0', 65 = 'A' and so on (see ASCII).
The Arduino print() methods do assume a char (unlike an int) is
intended to be displayed as a character.
Now your actual loop:
int Item_Name;
for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);  // write the char on the serial port
    lcd.write(buffer2[i]);     // write the char on the LCD
    Item_Name=buffer2[i];      // store the char in a variable
}

This will print the contents of the buffer to both the serial port and
the LCD. You would have seen the expected message on the LCD if you did
not have lcd.clear() right after the loop.
sscanf(buffer2, "%s", &Item_Name);

This means “extract from buffer2 a sequence of contiguous
non-white-space characters, and store it in memory at the address of the
variable ItemName”. If the buffer contains “Fresh Milk 1Lt”, this will
write “Fresh” to that memory location. That is 6 bytes (5 letters and a
terminating NUL). Unfortunately, the compiler has only allocated 2 or
4 bytes of RAM for storing ItemName (depending on the Arduino model),
so this will write past the allocated storage, which is a type of bug
known as buffer overflow. Now your Arduino's memory is corrupted and
anything can happen.
sprintf(buffer2, "%d", &Item_Name);

This tries to find within byffer2 a textual representation of a
number, and store it into Item_Name. This is safe, but only makes
sense if the buffer contains a number, written as text, which is not the
case here.
lcd.print(Item_Name);

This is asking the LCD to print an integer (namely Item_Name). It will
convert the integer to decimal text and print the corresponding digits
on the LCD.
Let's assume for example that Item_Name contains the numeric value
32 (which is the ASCII representation of a space). lcd.print() will
convert that into a sequence of two characters: '3' and '2' (the
decimal representation of 32). It will then send those characters to the
LCD (ASCII values 51 and 50), and you will see the text “32”.
If you want to see the text contained within the buffer, the you can
either send the characters one by one (like you already did right before
lcd.clear()), or provide to lcd.print() a char* pointer with the
whole message:
lcd.print(buffer2);

This assumes that the buffer is terminated with a NUL character. If it
is not, then you can either use the char-at-a-time method, or change
your code in order to put a NUL terminator in the buffer.

Thank you so much! it's working when i change the data type of buffer2 from byte array to character array


text:
ESP32 partition table and writing location
In my ESP32 project I have the following platformio.io file:
[env:esp32-poe]
platform = espressif32
board = esp32-poe
framework = arduino
lib_deps =
    openslab-osu/SSLClient@^1.6.7
    knolleary/PubSubClient@^2.8
    bblanchon/ArduinoJson@^6.16.1
monitor_speed = 115200

[env:custom_builtin_table]
board_build.partitions = default.csv

the default.csv table is this one:
# Name,   Type, SubType, Offset,  Size, Flags
nvs,      data, nvs,     0x9000,  0x5000,
otadata,  data, ota,     0xe000,  0x2000,
app0,     app,  ota_0,   0x10000, 0x140000,
app1,     app,  ota_1,   0x150000,0x140000,
spiffs,   data, spiffs,  0x290000,0x170000,

I noticed that when I upload the code to my ESP32 the output is like this:
[...]
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 17104 bytes to 11193...
Writing at 0x00001000... (100 %)
Wrote 17104 bytes (11193 compressed) at 0x00001000 in 0.3 seconds (effective 521.5 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 128...
Writing at 0x00008000... (100 %)
Wrote 3072 bytes (128 compressed) at 0x00008000 in 0.0 seconds (effective 5621.7 kbit/s)...
Hash of data verified.
Compressed 8192 bytes to 47...
Writing at 0x0000e000... (100 %)
Wrote 8192 bytes (47 compressed) at 0x0000e000 in 0.0 seconds (effective 27422.0 kbit/s)...
Hash of data verified.
Compressed 1003456 bytes to 585011...
Writing at 0x00010000... (2 %)
[...]

Hence, it writes at:

0x1000
0x8000
0xe000 (otadata)
0x10000 (app0)

But I cannot understand what are the first two writings.

0x1000 is the "second stage" bootloader. This is the code that is responsible for loading the code according to the layout specified in the partition table.

In ESP-IDF, the binary image which resides at offset 0x1000 in flash is the second stage bootloader. Second stage bootloader source code is available in components/bootloader directory of ESP-IDF. Note that this arrangement is not the only one possible with the ESP32 chip. It is possible to write a fully featured application which would work when flashed to offset 0x1000, but this is out of scope of this document. Second stage bootloader is used in ESP-IDF to add flexibility to flash layout (using partition tables), and allow for various flows associated with flash encryption, secure boot, and over-the-air updates (OTA) to take place.

0x8000 is the partition table itself.

Second stage bootloader reads the partition table found at offset 0x8000. See partition tables documentation for more information. The bootloader finds factory and OTA partitions, and decides which one to boot based on data found in OTA info partition.

All this is detailed in the ESP-IDF manual.


text:
Arduino code crashing
I am writing an SIM900A + arduino(Arduino UNO with Atmega 328P) code to just send the current time stamp every 20 minutes.
The code keeps crashing in the SendMessage() function as the setup prints keep coming again and again. Please let me know what I am doing wrong. Thanks in advance
#include <SoftwareSerial.h>
#include <LowPower.h>
SoftwareSerial mySerial(9, 10);
char msg;
char call;
int ctr;

#define TIME_STR_LEN 100  // the actual number of characters for date and time

char timeStamp[TIME_STR_LEN]; // holds the time string

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  Serial.println("GSM SIM900A BEGIN");
  mySerial.println( "AT+CLTS=1");
  delay(1000);
  ctr = 0;
  delay(10000);
}

void loop()
{

  if(mySerial.available()>0)
  {
    while (mySerial.available()>0)
    {
      mySerial.read();
    }
  }

  if (ctr%1 == 0)
  {
    delay(1000);
    SendMessage();
    delay(100);
    ctr = 0;
    Serial.println("just sent a message");
  }
  delay(60000);
  ctr++;
  //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART0_OFF, TWI_OFF);
}

void SendMessage()
{
 mySerial.println( "AT+CCLK?" );
 delay(2000);

 int i = 0;

 if (mySerial.available()>0)
 {
      while (mySerial.available()>0 && i < TIME_STR_LEN)
      {
        timeStamp[i]=(mySerial.read());
        i++;
      }
  }
  delay(2000);

  mySerial.println("AT+CMGF=1");
  delay(1000);
  mySerial.println("AT+CMGS=\"xxxxxxxxxx\"\r");
  delay(1000);
  mySerial.println("Motor is ON ");
  delay(100);
  mySerial.println(timeStamp);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

Might be a brownout. Are you sure your power supply is powerful enough? The SIM900A needs quite a lot of current.

Currently I have just powered the sim 900A using the 5V and GND pins of the Arduino

And how is the Arduino powered? We need to know the maximum current and also how the power supply is connected (though barrel jack, through USB or directly to the 5V pin)


text:
SIM7000G Connectivity Issue
I'm using botletics / SIM7000-LTE-Shield with Arduino Uno. I ran LTE-Demo example with the following adjustments based on this source:

fona.setNetworkSettings(F("jawalnet.com.sa"));
fona.setPreferredMode(2);
fona.setPreferredLTEMode(3);
fona.setOperatingBand("NB-IOT", 12);
fona.enableRTC(true);

But I'm getting no where and there is no registered network. I even tried Band (CAT-M) with no luck
I'm powering the shield from UNO with no external battery. 2 Green leds are led + blue led is flashing
Any Idea what am I doing wrong?
FONA basic test
Initializing....(May take several seconds)
Configuring to 9600 baud
Attempting to open comm with ATs
    ---> AT
    <--- AT
    ---> ATE0
    <--- ATE0
    ---> ATE0
    <--- OK
    ---> ATI
    <--- SIM7000G R1529

OK

    ---> AT+CPMS="SM","SM","SM"
    <--- +CPMS: 0,100,0,100,0,100
FONA is OK
Found SIM7000
    ---> AT+GSN
    <--- 869951031081155
Module IMEI: 869951031081155
    ---> AT+CFUN=1
    <--- OK
    ---> AT+CGDCONT=1,"IP","jawalnet.com.sa"
    <--- OK
    ---> AT+CNMP=2
    <--- OK
    ---> AT+CMNB=3
    <--- OK
    ---> AT+CBANDCFG="NB-IOT",12
    <--- OK
    ---> AT+CLTS=1
    <--- OK
    ---> AT&W
    <--- OK
-------------------------------------
[?] Print this menu
[a] Read the ADC; 2.8V max for SIM800/808, 0V-VBAT for SIM7000 shield
[b] Read supply voltage
[C] Read the SIM CCID
[U] Unlock SIM with PIN code
[i] Read signal strength (RSSI)
[n] Get network status
[1] Get network connection info
[c] Make phone Call
[A] Get call status
[h] Hang up phone
[p] Pick up phone
[N] Number of SMSs
[r] Read SMS #
[R] Read all SMS
[d] Delete SMS #
[s] Send SMS
[u] Send USSD
[y] Enable local time stamp (SIM800/808/70X0)
[Y] Enable NTP time sync (SIM800/808/70X0)
[t] Get network time
[G] Enable cellular data
[g] Disable cellular data
[l] Query GSMLOC (2G)
[O] Turn GPS on (SIM808/5320/7XX0)
[o] Turn GPS off (SIM808/5320/7XX0)
[L] Query GPS location (SIM808/5320/7XX0)

-------------------------------------

FONA> C
    ---> AT+CCID
    <--- 8996601730099550895f
SIM CCID = 8996601730099550895f
FONA> n
    ---> AT+CREG?
    <--- +CREG: 0,2
Network status 2: Not registered (searching)
FONA> l
    ---> AT+CIPGSMLOC=1,1
    <--- ERROR
Failed!
Fail code #2
FONA> n
    ---> AT+CREG?
    <--- +CREG: 0,2
Network status 2: Not registered (searching)
FONA>  n
---> AT+CREG?
<---
Network status 0: Not registered
FONA>

what's your question?

@jsotola how to make it work?

Im working on a similar project and running into the same issue with the flashing blue network LED. Im guessing its cycling power since there is no battery for the shield. Guess ill have to wait until my battery arrives.


text:
How to convert an int to const int in Arduino?
For a specific project, I need to convert an int to a const int variable type.
int i = 10;
boolean ShiftRegister[i] //Throws error

const int i = 10;
boolean ShiftRegister[i]// Works Fine

as i am making my own custom library where the size of boolean can be defined by creating an object by the user
myLib Library(20); // user defined boolean size

and the size is stored to a struct like this as it can't directly be converted to a const int.
The header file ...
#ifndef myLib_h
#define myLib_h
#include "Arduino.h"

class myLib{

public:
myLib(int input);
private:
int input;

};
#endif

the C++ code
#include "myLib.h"
#include "Arduino.h"

 struct Data {
  int BoolSize;
 }Data[0];

 myLib::myLib(int input){
 Data[0].BoolSize=input
 }

 const int boolSize = Data[0].BoolSize;

 bool DataBoolean[boolSize];

Whenever i run this library, it throws an error untill i dont predefine the boolean size in cpp code like this..
bool DataBoolean[20];

that means there is something error converting the int to const int in this line
const int boolSize = Data[0].BoolSize;

so what i want is, i dont want to predefine the boolean size in the cpp code. i would rather like to
define boolean size by creating an object(where the code crashed), storing the size to a structure then assigning the structure integer to the const int variable. I need an efficiant way to
turn this struct variable
Data[0].BoolSize;

into a const variable and assign to it like this without any errors
const int boolSize = Data[0].BoolSize;

so how can i convert an integer to a const int so that i can continue to my project?
any helps please? thanks for your kind support.

struct Data { int BoolSize; } Data[0]; declares an array of zero elements. You need to change that 0 to (at least) a 1.

For this you should look at template classes.

@Mat an array starts from number 0, and I don't want more memory for data so I have given array length 0 only . Can I not be able to access data at array position 0 then ?

@Majenko please spend a little more time for me and write an example code here that will be easier for me to understand

I will, but I'm cooking breakfast at the moment.

Yes, sure , I am not in a hurry but when you are free, please do me this favor

If you declare T Data[length] (where T is a type), valid array indices run from 0 to length-1. With the declaration T Data[1], the only valid index is 0 (in which case using an array is pointless). With T Data[0], there is no valid index at all, as the array contains absolutely nothing.

@Edgar Bonet OK...

At the time the constructor of your class is called, its size must be already defined, because the memory allocation takes place before. But you try to give it as a parameter to the constructor. This cannot work.
You have at least these alternatives. (Note: This is an invitation to edit this answer and add more, if you know some serious solution.)
1. Use a template for the size
Please be aware that each different size will generate another implementation in machine code.
template<size_t size>
class myLib {
public:
    inline myLib<size>() {}
private:
    bool data[size];
};

2. Allocate the requested memory dynamically
class myLib {
public:
    inline explicit myLib(size_t size) : data(new bool[size]) {}
    inline ~myLib() {
        delete[] data;
    }
private:
    bool* data;
};

Note: Depending on the version of C++ you're using, you need to consider the Rule of Three (before C++11) or the Rule of Five (beginning with C++11). Since the implementation of the missing methods depends on specific details, it is left as an exercise to the reader.

There is a memory leak in the second example: you should delete[] data in a destructor. But see also the rule of three.

@EdgarBonet Absolutely correct, thanks! My current project is an embedded system that never destructs objects… misleading me. Therefore we don't need any of the additional methods.

If you want variable length of an array, then you can use malloc.
With same conext, if you want to initiate an array with specific length of value you have to use malloc.


text:
FG Frequency output
I have bought the Brushless DC-Flat Motors Series 2610 and Pin number 6 is called FG which is defined as frequency output. I have plugged this pin into the Arduino in A0 and I have tried displaying the outputs. The outputs is either 0 or 1023 and I am not sure how I can convert this to angular speed or RPM. Any help will be appreciated

Without looking at the motor, I'm pretty sure, that this is not an analog output. Almost certainly it is a digital pulse output. So it will output a specific number of pulses per revolution of the motor (Thus you can get the RPM by counting the pulses per time interval). You get 0 and 1023, because you are just reading the HIGH and LOW signal parts of the pulsed signal.

That will be a hall effect output giving you a square wave, the frequency equal to (or proportional to) the RPM.

in the manual it says "6 lines per revolution" does this mean that I need to observe 6 ones in a row for a revolution to be considered? or is a pulse a 0 followed by a 1 then a 0. Sorry if I'm asking basic questions


text:
Compiling for Wemos D1 mini with Visual Studio Code
I'm giving Visual Studio Code (VSC) a try and am getting unexpected results. I have a program (sketch) that compiles fine in the Arduino IDE. I create a workspace in VSC, initialize the project, and after some more mucking about I get a compile there appears to succeed:
[Done] Finished verify sketch - RanchMonitor2.ino

But the console pane shows four "problems":

How can the compilation have succeeded if there are problems?
The same sort of thing is happening with one of the samples - HelloServer.ino
In this case the problems are an incomplete type and memcpy_P not defined.
I wouldn't think it should make a difference, but I'm working without a board physically attached to the USB port.
UPDATE:
I think "Problems" are issues identified by Intellisense. They appear even before a compilation is attempted. All I have to do is open the workspace and wait a few seconds, then the "problems" appear. Hence my conjecture they are Intellisense warnings, not compilation errors.
Adding "ESP8266" to the Defines section of c_cpp_properties.json got rid of the error "WiFiManager" is undefined.

If the compilation fails, it returns error code 1 and doesn't say "finished". I tested this by forcing a failure, removing a semi-colon at the end of a line. See edit to question.

Intellisense reports "Problems" - these are distinct from compile time errors. Just because Intellisense can't resolve a literal or something doesn't mean it won't be resolved in the compiler; thus it's possible to have the IDE report a problem but still be able to have a successful compile. In the case described above, two changes to the c_cpp_properties.json file provided Intellisense with the information it needed. A header file was added to the forcedInclude section to provide pin definitions. A literal "ESP8266" was added to the defines section to indicate the processor type. This define is used in lots of header files so it must be know to Intellisense when reading the headers. Here are the relevant sections of that .json file:
        "forcedInclude": [
            "C:\\Users\\David\\AppData\\Local\\Arduino15\\packages\\esp8266\\hardware\\esp8266\\2.7.1\\variants\\d1_mini\\pins_arduino.h"
        ],
        "defines": [
            "USBCON",
            "ESP8266"
        ],


text:
How to use pyserial to write two separate message?
I'm using pyserial to communicate with my arduino. I set up the connection and everything works fine. Now I have these two writing commands:
pyserial.write("conn".encode())
pyserial.write("mod1".encode())

On my arduino:
while (!Serial.available());
String s = Serial.readString();
if (s=="conn") do...;
if (s=="mod1") do...;

The problem is that none of the if statements are true because s becomes "connmod1", because the messages are sent almost at the same time I guess. I know I could use some delimiter to split the string, but I would like to know what the convenient solution might be?

you already answered your own question I know i could use some delimiter

readString() waits for the next character until timeout. default timeout is 1 second. you can set the timeout with Serial.setTimeout(millis). https://www.arduino.cc/reference/en/language/functions/communication/serial/readstring/

If you want a quick, cheap, and easy solution, you could just use sleep() in your Python script to put a delay between the commands. This obviously isn't a perfect solution, but it's not difficult to implement.
Or, like you said, you could use a delimiter. It's not as easy to implement, but it'll work better.
If you go the delimiter rout, you'll probably need to use Serial.read() instead of Serial.readString(). That way you can examine characters individually as they come in. You can store your characters in a String or char array until you detect your delimiter and then execute your command.
Hope that helps!


text:
Using functions in header files
I want to include a function in my sketch I moved to a .h file.
I did it as follows:
My code:
#include "header.h"

void setup() {
  fct();
}

void loop() {

}

My header:
#include "Arduino.h"
#ifndef MYHELPERS_H
#define MYHELPERS_H

void fct() {
// stuff
}

#endif

The same process seems to work for variables but the IDE says this function in not declared in this scope...
I don't understand what I'm doing wrong...
Thanks guys!

for me it compiles. do you have the header file as tab in IDE?

Where exactly does your header file lie? In the same folder as the main sketch? Or in the libraries folder?

This is not the way you separate your project in modules. In a header file you declare what your module offers publically. The implementation goes into another C++ file and this will be compiled separately. -- Please get a good book on basic C++ and/or Arduino programming and read it. This issue is far too broad to be answered in a SE/Arduino question.

This header file was created with the new file button in the Arduino editor and it resides in the same folder as the main sketch.

File->New, creates a new sketch

I found a solution somewhere else on internet...
This portion:
#ifndef MYHELPERS_H
#define MYHELPERS_H

Was not written correctly... "MYHELPERS_H" should've been replaced by the name of my file. Now it works just fine.

there is no relation between the include guard macro name and the name of the file. this answer is wrong.

It's weird but it fixed my problem

Maybe the guard macro name has to be the name using in the #include of the main sketch but it works now I have done this

no. #include takes a file name. and it doesn't care about the content of the file

Anyway, it worked

so change it back and you see it will still work

I'm on a work trip right now and my pc is home

Sorry Spyro, this answer makes absolutely no sense - downvoted.


text:
Proper wiring for a HiLetgo DAC to Arduino
I have been having trouble finding any recourses for a DAC chip that I bought. It is the HiLetgo PCM5102 DCA.
https://www.amazon.com/gp/product/B07Q9K5MT8/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
There are 6 ports to be routed. VIN, GND (I know these) LCK, DIN, BCK, SCK, but the rest are a mystery to me. The Adafruit version has tutorials online but I got this one because of the built in 3.5mm jack is what I really needed. Any and all help is greatly appreciated. Let me know if I need to post any other resources.
I am trying to read the audio data coming in from songs through the 3.5mm jack.
Here is the data sheet for the Adafruit version of the DCA with a 3.5mm audio jack
I am asking for help in reading audio data from the input jack.
https://cdn-learn.adafruit.com/downloads/pdf/adafruit-i2s-stereo-decoder-uda1334a.pdf

@jsotola Hi, I actually am having trouble finding a data sheet online. I purchased this on amazon, but the product does not appear on the official HiLetgo website. As for a question I am asking what pins the LCK, BCK, DIN, and SCK slots are to be routed to

if you cannot find a datasheet for the module, then look for a datasheet for the main IC that is used in the module

reading audio data from the input jack ... the pictures at amazon are quite clear ... the jack is not an input

A DAC (Digital to Analog Converter) is an output device. You cannot read a signal with it. So the 3.5mm jack is an output (for example for headphones). For reading you need an ADC (Analog to Digital Converter). Also you would need to bias the voltage. Normal audio voltages on such jacks will vary around 0V, also going negative, which an ADC will not simply read (unless it does the biasing internally).

You have tagged this question as 'arduino-uno'.  The board you are asking about uses an I2S interface, which AFAIK is not available on the Uno.


text:
How can I control 2 servos without an external power supply?
I've been trying to implement a project that's been in my head for a while, I want to wirelessly control my light and fan switches using an ESP32 and 2 servos (one for each switch) through an HTML page, and then later integrate it with Alexa
I have seen how one servo can be controlled by connecting the servo's power cable to the ESP32's Vin pin, but how can I control two? I want to avoid using an external power supply like a battery pack because I want it to be a completely automated process, and I don't want to have to keep switching out batteries often for the thing to work. I'll be using a 5V wall outlet to power the ESP32 using a USB.
Also, if anyone can provide a few more tips on how I can make my project more efficient or point out where I might be making a mistake, I'd be glad. I'm still new to the microcontroller world.
Thanks
EDIT :  I've attached a picture of the circuit diagram, just have a look and let me know if it is workable

The power wire is just needed, well, to power the servo. The control is done via the third wire (the other wire being Ground).
You can connect the second servo's power in parallel, only the control wire must be separated from the first servo's control wire.
Note: You need to make sure that the current consumption of both servos does not exceed the provided power.

Oh okay, thanks for that. But I have one doubt, how exactly do I calculate if current consumption of the servos is lesser than what the ESP can provide? I'm using an ESP-WROOM-32, one SG90 servo and one MG90 servo. If anybody can do the calculations as to whether I can control the servo using the ESP32, it'll be very helpful, as I'm still new to this stuff, and another opinion is always better :)

Your servos should be documented, and you are looking for the maximum current of each. Add them. Then add the maximum current of the ESP32, it should be in its documentation, too. The total must be less than the maximum current your 5V wall wart provides.

This is the safe way. If you are sure that your servos never block, the current is much lower, see their documentation. Also the ESP32 consumes in average less current. Only at startup and when peak calculation power is needed, it rises. You might simply try. If the provided current is insufficient, you will notice that your project behaves strange and/or unreliable.

So it IS possible for me to just try it out right? As in, if the servos do demand more than the ESP32 can provide, it won't cause any fatal damage to the servos or the ESP, right?

Since you said that you connect your servos to Vin of the ESP32, which is the same point where you connect your supply device, the ESP32 has nothing to do with it. Its copper line from the USB to this pin should be able to handle the servos current. -- If this is not correct, please edit your question (there is a little link below the question) and show us your circuit. You can draw it with any graphic tool you know.

Right, there seems to be a misunderstanding from my side, I was unaware that the Vin pin and the USB port are connected. Seems like my lack of knowledge of microcontrollers has caught up to me :p. Anyways, I have edited my question and added a picture of the circuit diagram, have a look and tell me if it is workable


text:
SEN0114 moisture sensor low max reading?
I am using the following SEN0114 moisture sensor with an ESP32:  https://datasheetspdf.com/datasheet/SEN0114.html
How come when submerged in water I only get a reading of ~2500?  Should this not read ~4095 as the ESP32 analog pins are 12-bit?

What voltage is it producing when submerged?

I can't measure that directly but I would assume 2V based on the 2500 analog reading?  Would I need to check this with a volt meter?

Well, if you measure it, you can know.  And then your question really has nothing to do with the sensor, and only to do with analogRead with a given input voltage, which is a better question, IMO.  Either that or you're going to discover your understanding about the sensor is wrong, and that will have some value.

This is a resistive sensor and "plain" water is not infinitely conductive. In fact, pure or distilled water is a very poor conductor. Also, "plain" water - tap water, I assume - will vary in its dissolved solids, not only from source to source, but likely over time, too, for some sources and it is these solutes that are responsible for increased conductivity. That goes double for plant-moisture sensing because it is really measuring the resistance of damp dirt, which again, varies in composition.
So the sensor can give you a range from dry to very moist, per plant, but the absolute measurements won't be very meaningful.


text:
OLED 128x64 make text bigger
I have a sketch that prints out a value from 0 to 100.  I want it to take up the whole screen.
I can't figure out how to make the font bigger I think that the part of the code defines the size of the font is :
    oled.setFont(System5x7)

But if I alter the value 5x7 it just spits out errors messages.
This is all the code:
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"
SSD1306AsciiAvrI2c oled;
#define I2C_ADDRESS 0x3C

int TankValue0;
int TankValue1;

void setup() {
  Serial.begin(9600);
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
  oled.setFont(System5x7);
  oled.clear();
}

void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 300, 785, 100, 0);
  TankValue1 = map(sensorTankValue1, 300, 785, 000, 0);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  oled.print(TankValue0);
  oled.print(" L");
  oled.println(" ");
  //oled.print("T1=");
 // oled.print(TankValue1);
 // oled.println(" ");
  oled.setCursor(0, 0);
  delay(1000);
}

You can't just choose arbitrary numbers. "System5x7" is the name of a font. You have to look in the library you're using to see what other fonts are available and choose one accordingly.

spits out errors messages ... what error messages? ...  why do you believe that error messages are useless for determining the source of the problem?

As pointed out above "System5x7" is The name of a font that is being used.  In this case the 5 and 7 do refer to how many dots are used to make up the output text, but it is just the name of the font it is drawing upon who's code is inside the library-- is this case:
"library->SSD1306Ascii->src->fonts"
In this folder are many fonts to chose from that one can substitute for "System5x7" for example "fixed_bold10x15".  I have not found one that fill the whole screen.  Presumably 64x64 would get me both digits.  I have explored the font file, but it is beyond me to create one from scratch.