text:
Proper use of the tone() function within the loop () function
I am trying to have my sketch run a short series of tones (melody) through a Piezo buzzer after a selection is made by the user. I am getting a compilation error with my use of the tone function in the code I've written. I would kindly ask if someone in the "know" could have a look and provide me with a clear, step by step explanation of what I need to change to get it to work. I thank you in advance, your help is much needed and appreciated. -Steve
Here is my sketch:
#include <Stepper.h>
#include <Servo.h>
#include <Tone.h>

/*ARDUINO MOTOR SHIELD
 * The pin breakdown is as follows:
 * Function          Channel A   Channel B
 * Direction         Digital 12  Digital 13
 * Speed (PWM)       Digital 3   Digital 11
 * Brake             Digital 9   Digital 8
 * Current Sensing   Analog 0  Analog 1
 */

const int stepsPerRevolution = 200;  // 1.8 deg. step angle(200 steps/360 deg. rev)
const int dirChA = 12;     // assigning name "dirChA" to pin 12
const int dirChB = 13;     // assigning name "dirChB" to pin 13
const int pwmChA = 3;      // assigning name "pwmChA" to pin 3
const int pwmChB = 11;     // assigning name "pwmChB" to pin 11
const int brkChA = 9;      // assigning name "brkChA" to pin 9
const int brkChB = 8;      // assigning name "brkChB" to pin 8

const int srvoMtr = 10;    // assigning name "srvoMtr" to pin 10

const int pButton1 = 4;    // assigning name "pButton1" to pin 4
const int pButton2 = 5;    // assigning name "pButton2" to pin 5
const int pButton3 = 6;    // assigning name "pButton3" to pin 6
const int pButton4 = 7;    // assigning name "pButton4" to pin 7

const int ledLight = 2;    // assigning name "ledLight" to pin 2

const int tonePin = 14;     // assigning name "tonePin" to pin 14

Stepper myStepper(stepsPerRevolution, dirChA, dirChB);  // initialize the stepper library on pins 12 & 13
Servo myServo;  // initialize the servo library to logical name myServo

int pButton1State = 0;     // variable for reading the pButton1 state as LOW or HIGH
int pButton2State = 0;     // variable for reading the pButton2 state as LOW or HIGH
int pButton3State = 0;     // variable for reading the pButton3 state as LOW or HIGH
int pButton4State = 0;   // variable for reading the pButton4 state as LOW or HIGH

int pButtonFlag = 0;     // variable for when button 1 has been pressed and released

int myServoPos = 0;    // variable for when servo has reached it's position
int myServoFlag = 0;   // variable for servo when any of the 4 pButton are pressed

void setup() {

 // 1 Stepper Motor
 pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
 digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)

 pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
 digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)

 pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
 digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)

 pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
 digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)

 pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
 digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)

 pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
 digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)

 myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM

 // 4 Push Buttons
 pinMode(pButton1, INPUT);   // initialize pin 4 as an INPUT
 digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)

 pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
 digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)

 pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
 digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)

 pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
 digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)

 // 1 Led Light
 pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
 digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)

// 1 Piezo Speaker
 tone();
 pinMode(tonePin, OUTPUT);   // initialize pin 1 as an OUTPUT
 digitalWrite(tonePin, LOW);   // initialize pin 1 as LOW (pin voltage is 0 V)
}

void loop() {
  //Read button state (pressed or not pressed?)
  pButton1State = digitalRead(pButton1);   // read the state of pButton1 as LOW or HIGH
  pButton2State = digitalRead(pButton2);   // read the state of pButton2 as LOW or HIGH
  pButton3State = digitalRead(pButton3);   // read the state of pButton3 as LOW or HIGH
  pButton4State = digitalRead(pButton4);   // read the state of pButton4 as LOW or HIGH

  // check if the pushbutton is pressed. If it is, the pbuttonState is HIGH:
  if (pButton1State == HIGH) {
     pButtonFlag=1;  // change pButton1Flag variable
  }
     if (pButtonFlag == 1){
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(40);          // step forward 40 steps to position 1
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper

        myServoFlag=1;             // change ServoFlag variable to dispense chocolate

        if (myServoFlag == 1){
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 15 milliseconds for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
           delay(2000); // hold position OPEN for 2 sec

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
        }

        myServoFlag=0;         // changes myServoFlag value back to zero (0)
        digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed

        if (ledLight == HIGH){
           digitalWrite(tonePin, HIGH); // turn on Piezo speaker

           // Play Melody
           void tone();{
           tone(tonePin, 233, 203.992851562);
           delay(226.658723958);
           delay(4.82252604167);
           tone(tonePin, 184, 412.325976562);
           delay(458.139973958);
           delay(4.82252604167);
           tone(tonePin, 184, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 155, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(236.303776042);
           tone(tonePin, 184, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 155, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(236.303776042);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(236.303776042);
           tone(tonePin, 233, 555.555);
           }
        }
        digitalWrite(tonePin, LOW);    // turns off Piezo speaker

        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-40);          // step backward 40 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    // disable power to stepper

        digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

        pButtonFlag=0;                // changes pButtonFlat value back to zero (0)
        delay(2000);
     }

  // position 2
  if (pButton2State == HIGH) {
     pButtonFlag=1;  // change pButtonFlag variable
  }
     if (pButtonFlag == 1){
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(80);          // step forward 80 steps to position 2
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper
        delay(2000);

        myServoFlag=1;    // change ServoFlag variable to dispense chocolate

        if (myServoFlag == 1){
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 15 milliseconds for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
           delay(2000);

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
        }
        myServoFlag=0;                // changes myServoFlag value back to zero (0)
        digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed

        if (ledLight == HIGH){
           digitalWrite(tonePin, HIGH); // turn on Piezo speaker

           // Play Melody
           tone(tonePin, 233, 203.992851562);
           delay(226.658723958);
           delay(4.82252604167);
           tone(tonePin, 184, 412.325976562);
           delay(458.139973958);
           delay(4.82252604167);
           tone(tonePin, 184, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 155, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(236.303776042);
           tone(tonePin, 184, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 155, 99.8262890625);
           delay(110.918098958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(4.82252604167);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(236.303776042);
           tone(tonePin, 184, 203.992851562);
           delay(226.658723958);
           delay(236.303776042);
           tone(tonePin, 233, 555.555);
        }
        digitalWrite(tonePin, LOW);    // turns off Piezo speaker

        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-80);          // step backward 80 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper

        digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

        pButtonFlag=0;   // changes pButton2Flag value back to zero (0)
        delay(2000);
    }

    // position 3
    if (pButton3State == HIGH) {
       pButtonFlag=1;   // change pButtonFlag variable
    }
       if (pButtonFlag == 1){
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(120);          // step forward 120 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate

          if (myServoFlag == 1){
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
          }
          myServoFlag=0;                // changes myServoFlag value back to zero (0)
          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed

          if (ledLight == HIGH){
             digitalWrite(tonePin, HIGH); // turn on Piezo speaker

             // Play Melody
             tone(tonePin, 233, 203.992851562);
             delay(226.658723958);
             delay(4.82252604167);
             tone(tonePin, 184, 412.325976562);
             delay(458.139973958);
             delay(4.82252604167);
             tone(tonePin, 184, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 155, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(236.303776042);
             tone(tonePin, 184, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 155, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(236.303776042);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(236.303776042);
             tone(tonePin, 233, 555.555);
          }
          digitalWrite(tonePin, LOW);    // turns off Piezo speaker

          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-120);         // step backward 120 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
          delay(2000);
     }
    // position 4
    if (pButton4State == HIGH) {
       pButtonFlag=1;   // change pButtonFlag variable
    }
       if (pButtonFlag == 1){
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(160);          // step forward 160 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate
          Serial.println("\nServo Flag = 1 - Dispense Chocolate");

          if (myServoFlag == 1){
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
          }
          myServoFlag=0;   // changes myServoFlag value back to zero (0)
          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed

          if (ledLight == HIGH){
             digitalWrite(tonePin, HIGH); // turn on Piezo speaker

             // Play Melody
             tone(tonePin, 233, 203.992851562);
             delay(226.658723958);
             delay(4.82252604167);
             tone(tonePin, 184, 412.325976562);
             delay(458.139973958);
             delay(4.82252604167);
             tone(tonePin, 184, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 155, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(236.303776042);
             tone(tonePin, 184, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 155, 99.8262890625);
             delay(110.918098958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(4.82252604167);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(236.303776042);
             tone(tonePin, 184, 203.992851562);
             delay(226.658723958);
             delay(236.303776042);
             tone(tonePin, 233, 555.555);
          }
          digitalWrite(tonePin, LOW);    // turns off Piezo speaker

          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-160);         // step backward 160 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
          delay(2000);
       }
}

Cut-and-Paste programming?

i do not think that anyone will waste their time trying to figure out which line causes the compile error

your code is overly complicated for no reason ..... you have 4 almost identical code blocks  .... the only difference between them is a number of steps ..... you could easily use a function block that accepts the number of steps as an argument ...... that way you have the code block only once and it will work for any number of buttons

one other thing ..... you write code without thinking about what the code does ..... for instance you have a command myServoFlag=1; which is fine, but the next command is if (myServoFlag == 1){  ............. that if statement is always true, so there is no reason to test the value of myServoFlag  ...................... it is like saying paint the box black, if the box is black then draw a white circle  ...... instead it should be paint the box black, draw a white circle

void tone();{ is just wrong; this should be a/your compilation error. consider refactoring your code.

The code is compiling and loading with mixed results. I've submitted the revised code under a new question - "Code causing Servo motor not to work!" Please have a look. Thx.

First off
Even if compiled your code will not work; in the tone function reference you can read:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

You seem to want to use both pins 3 & 11 for PWM output; you cannot also use the Tone library while using these pins. Although you never actually called analogWrite(...) on these pins so it probably won't do what you want anyway.
Second
the line:
void tone();{

is absolutely wrong; one cannot declare a function within another function in C++ or C. And this isn't even a valid definition either. This is probably your compilation error, your compiler should tell you what line number this is on!
Third
It seems you don't quite understand what the code you are attempting to use even does. I would assume that you haven't read, or understood, the documentation.
digitalWrite(tonePin, HIGH); // turn on Piezo speaker

The tone library doesn't work like this; at best this does nothing, at worst it disrupts the tone library
myServo.attach(srvoMtr);   // attaches the servo library to pin 10
for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
  myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
  delay(15);
}
myServo.detach();

This is not how you use the servo library! .attach() is generally used in setup, .detach() is almost never used.
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(40);          // step forward 40 steps to position 1
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    //disable power to stepper

This is not how you use the stepper library! Steppers are generally powered 100% of the time. When un-powered they cannot generate torque or hold a position! Also those pins aren't associated in any way with the stepper, you assigned dirChA and dirChB to the stepper. The stepper library assumes it is talking to a stepper driver, not driving the stepper itself.
Finally
Your code repeats itself too much, and is too verbose, and does many nonsensical things or things that result in nothing or something very different that the comments imply was intended.
You need to structure you code better, refactor into re-useable functions and remove code that doesn't do anything

Thank you, Esoterik, for taking the time to respond. I'm new to programming, but eager to learn. Any positive instruction I can receive in this forum will only contribute to my learning. That said, I've made a number of changes and the code now compiles. However, the results are unstable. Likely to the inherent conflict with pins 3 & 11 and the use of the tone function. What if I changed to midi()? I've submitted a new question "Code causing Servo motor not to work" with my revised code. I hope you can help.


text:
Cannot communicate with software serial on particular devices (SIM7600G-H)
I have 3 devices:

An UNO (non-genuine)

An SMS hat/shield device SIM7600G-H to communicate with via UART

A USB UART controller for debugging purposes

I'm using the UNO to talk to the SMS device via UART at 9600 baud to send and receive SMS commands. I need the hardware port open to debug, and I am trying to use a software port to talk to the SMS device via it's TX RX pins.
But I cannot get the software port to talk to the SMS device at all.
This is the success I've had trying to talk to and from devices. The bold boxes are needed to be solved for this setup to work. ✅ = working coms, ❌ = nothing on coms at all. Read left to right, HAT serial (SMS DEVICE) can communicate with UNO hardware serial.

And I'm using this code to just relay inputs and outputs between the hardware and software ports for testing.
// Must be same on mock and serial
const int baud = 9600;

// Communication with mock hat
SoftwareSerial mockPort(2, 3);

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

  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  mockPort.begin(baud);
  Serial.println("Mock port has started @ " + String(baud));
}

void loop()
{

  while (mockPort.available() > 0)
  {
    char inByte = mockPort.read();
    // and send to the hardware serial port:
    Serial.write(inByte);
  }

  // while there is data coming in FROM SERIAL, read it and send it back to mock
  while (Serial.available() > 0)
  {
    char inByte = Serial.read();
    // and send to the mock serial port:
    mockPort.write(inByte);
  }
}

Why can't I communicate to the SMS device with the software ports? (or the USB UART as well?) When testing, I can see the UNO's RX light turn on, but I never receive any data back from the SMS device (the serial monitor is just black).

Notes:

I've tried the AltSoftSerial library as well
I've set the SMS hat's baud rate default to 9600
I've tried different communication pins
I've got the TX pins on RX pins and vice versa

I am using simcom7600gh but with esp32.
are you sure you are sending the correct AT Commands to the modem?

@AhmadFirdausIdris All i'm sending is at. I've tried with an ESP32 as well. I can't even get the boot message from the hat.

The TX and RX labels mirror the Raspberry Pi. So I swapped the RX and TX wires to connect as RX->RX and TX->TX and now it works

source: Stack Exchange

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

sort: votes


text:
ESP32 SerialBluetooth disconnects within a second after connecting but not BLEDevice/BLEServer
Code using BluetoothSerial api disconnects immediately after establishing connection with my laptop running Ubuntu 18.04. If instead of BluetoothSerial BLEDevice api is used, the connection stays connected. See minimal examples below.
Another peculiar observation is that connection with my Android phone is stable when running BluetoothSerial example below.
How to make BT connect properly with both the phone and laptop?
The chip running the code is esp32-wroom-32d.
Minimal code with BT disconnecting from laptop Ubuntu 18.04 after roughly a second (from SerialToSerialBT example):
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup() {
  SerialBT.begin("ESP32 SerialBT");
}

void loop() {
}

Minimal code with stable BT connection (from BLE_notify example):
#include <BLEDevice.h>
#include <BLEServer.h>

BLEServer* pServer = NULL;

void setup() {
  BLEDevice::init("ESP32");

  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new BLEServerCallbacks());

  BLEDevice::startAdvertising();
}

void loop() {
}

UPDATE:

Updating Ubuntu to 20.04 did not help.

I know this is old but I had the same issue using bluetoothserial.h.  But by using rfcomm
rfcomm bind 0 <bluetooth MAC ADDRESS>

and then my example command sent to serialBT
echo -ne ">LOOOCR" > /dev/rfcomm0

/dev/rfcomm0 being the device created with the bind. It even still shows as disconnected in the Ubunutu 20.04 bluetooth GUI.  For what it's worth I think it is the same on all devices.  Until you connect to the BT serial port it is only Paired.  But someone with greater knowledge than myself can explain.

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


text:
Arduino Uno R3 cannot detect GPRS Shield SIM900
I am new to Arduino which I got only this week for my project which sends sms from my windows     application.
I have Arduino Uno R3 and GPRS Shield (Simcom) Sim900  (S2-1040S-Z0912)
I am currently following this guide > https://educ8s.tv/arduino-gsm-shield/
As of the moment I have problem connecting the Sim900 to Arduino (I think Arduino cannot detect Sim900). The Arduino is working properly as my PC detected it. Also I confirm that the SIM900 is working properly as I can call the Sim inside and it is ringing (also the led on the device is blinking almost every 3 secs or so)
I found this, but I'm planning to use USB powered only as I only need the SMS feature so I am stacking the SIM900 on top of the Arduino.
How to communicate the Arduino board with SIM900?
I am using this library http://www.tinyosshop.com/datasheet/GSM_GPRS_GPS_Shield_GSMSHIELD.rar
and below is the sketch:
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
SMSGSM sms;

int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];

char sms_position;
char phone_number[20];
char sms_text[100];
int i;

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");

    if(started)
    {
        if (sms.SendSMS("214", "?15001"))
        {
          Serial.println("\nSMS sent OK.");
        }
        else
        {
          Serial.println("\nError sending SMS.");
        }
    }
};

void loop()
{
    if(started)
    {
        sms_position=sms.IsSMSPresent(SMS_UNREAD);
        if (sms_position)
        {
            Serial.print("SMS postion:");
            Serial.println(sms_position,DEC);
            sms.GetSMS(sms_position, phone_number, sms_text, 100);
            Serial.println(phone_number);
            Serial.println(sms_text);
        }
        delay(2000);
    }
};

and here is the output
Trying to force the baud-rate to 9600

1200
2400
4800
9600
19200
38400
57600
115200
ERROR: SIM900 doesn't answer. Check power and serial pins in GSM.cpp

status=IDLE

What I have tried so far:
I tried the sketch with SoftwareSerial mySerial(7, 8); and SoftwareSerial mySerial(9, 10) which i found on other tutorials but didn't work.
I tried modifying GSM.cpp and modify the value of _GSM_TXPIN_  and _GSM_RXPIN_  to 7, 8 and 9, 10 but didn't work.
Found that the pin on my Arduino is RX=0 and TX=1, and SIM900 is TX=0 and RX=1, tried the SoftwareSerial code above but with 0, 1 and GSM.cpp with 0, 1 but still not working.
I am currently still trying every other sketch i find on the internet but nothing works.
EDIT:
This is the link for the module i bought
https://www.lazada.com.ph/products/sim900-gsm-shield-i267689740-s379728457.html?mp=1
I cant find the link for the datasheet of this specific module so I will try to include the picture of the module

Can you provide a link to the actual module you are using? Does it have jumpers on it to change the TX and RX pin assignments?

Hi @Majenko, Please see the edit on the bottom of my question. Thanks

After many trials, I found the solution to my problem, thanks to @Majenko for mentioning the jumpers.
I am still stacking the SIM900 module on top of Arduino.
Switching the jumpers from D1 and D0 to D8 and D7 solved the problem (see green square on the pic)
I don't know why it needs to be on D8 and D7 since on board it says TX=0 and RX=1 and vise-versa for Arduino

Then used the below sketch from this tutorial > https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

With this, it displays correct output on serial monitor based on the tutorial and I can confirm that its working as well on my windows form application as it can send sms from the application.

0 and 1 are the hardware serial pins.  If you are using Serial elsewhere in your code then you can’t use 0 and 1 for the shield.  They’re already in use by the hardware serial.  You are creating a software serial.  It’s not a real serial port.  It’s software pretending to be a serial port.  That won’t use hardware serial pins.

If you want to use 0 and 1 then get rid of all the software serial business and just use Serial to talk to the shield.  But that means you can’t use it for other purposes and it also means complications when you want to upload new code.


text:
What are the traditional ways to optimize program memory usage?
While doing big projects using Arduino boards (Uno, Atmega328P MCU). I used to get warnings like this
Sketch uses 13764 bytes (44%) of program storage space. Maximum is 30720 bytes.
Global variables use 1681 bytes (82%) of dynamic memory, leaving 367 bytes for local variables. Maximum is 2048 bytes.

Low memory available, stability problems may occur.

What are the generally practiced methods for the optimization program memory usage?
Is there any difference in memory usage if the variable is declared globally or locally.
Will it matter what the control statement/selection statements are (like if, switch )
Usage of Serial monitor. Serial.print()
......

Low memory available, stability problems may occur.

How bad are these warnings?
Before marking it duplicate, I have referred the following. But it wasn't satisfactory
Most memory efficient way to program
What are safe memory usage limits?

not a traditional way, but Nano Every has 3 times the SRAM of classic Nano and the updated compiler doesn't copy constant strings into SRAM.

What are the generally practiced methods for the optimization program
memory usage?

First, note you are searching for ways to lower SRAM memory. This contains global (variable) memory and heap space (dynamic memory + stack memory).

Avoid memory gaps, by not using dynamic memory (with free/malloc/new).
Avoid using the String class.
Avoid global memory in SRAM by using PROGMEM, F(..) if possible.
Use the smallest variable size (e.g. uint8_t instead of int).
Store arrays of booleans into bits (8 booleans per byte).
Use bit flags if applicable.
Use some compressed type of memory internally (affects performance), e.g. if you have many 6 bit values to store, store them not in separate bytes but use 6 bytes for 8 times 6 bit values).
Avoid passing arrays by value.
Avoid a deep call stack with many (big) variables. Note this affects your design, so use it as a last resort.
If you need a calculatable table, calculate each value instead of storing it as a table.
Do not use longer arrays than needed, and think about reasonable maximum array sizes otherwise (see hcheung's comment below).
(this is not a complete list).

Is there any difference in memory usage if the variable is declared
globally or locally.

Yes, local variables are added to the stack, but are removed after the function ends, global variables stay (but are only created once).
Note that variables on the stack (and also dynamic memory) are NOT taken into account in the memory calculated in the warning message during compiling.

Will it matter what the control statement/selection statements are
(like if, switch )

No, this will only affect the program memory.

Usage of Serial monitor. Serial.print()

Probably yes, the serial monitor probably reserves (quite?) some memory as a buffer.

Low memory available, stability problems may occur.
How bad are these warnings?

How bad it is, depends on how much memory is used which is not calculated, which is dynamic memory, and stack memory.
You can calculate it manually (which can be quite cumbersome for a big program), you can also use the GitHub library for this:
Arduino MemoryFree
If you know how much heap memory you use worst case, than add it to the calculated global variables memory. If this is less than your maximum available SRAM memory, you are safe.

Upvote for the comprehensive summary. I'd like to add one more "allocate your array size according to the need", I often see many ArduinoJson users created an allocation as large as 1024 bytes with StaticJsonDocument<1024> doc; for a target data object consists of only a couple of key/value pairs that take no more than 50 bytes.

@hcheung ... good one ... for me it's obvious not to use too many, but with limited RAM system you have to think about array limits carefully.

What about macros like #define

@MayooghGirish #define's are only textual substitutions, the result of the substitution can be applied to the examples mentioned in my list.

Nitpick: I would say "avoid using String" rather than "prevent using String". "Avoid" means that you should not do it. "Prevent" means you should make it so someone else cannot do it, or so it cannot happen by itself. Likewise, "avoid storing constant global variables in SRAM" (the constant part is important, you can't just move anything to PROGMEM!)

@user253751 You are right thanks, English is not my native language. I will change it in my answer.

I've made a few more changes, in case you want to check them.

@user253751 All accepted, I used 'sketch'  because in Arduino it's the 'default'  term, although I prefer program as it's used everywhere else.

Arduino programs are called sketches, but I think program memory is still called program memory, not sketch memory. For example PROGMEM

@user253751 That's correct. Probably Arduino used 'sketch' as it seems less 'difficult'  than a program.

I just want to add a single bullet to Michel Keijzers’ excellent answer:

think about every single item you are storing in memory and ask
yourself the question: do I really need to keep this in RAM?

It may sound silly to state what many would consider obvious, but we
have seen here many instances of novices who do not take this into
consideration. As a simple example, consider this function that averages
500 analog readings:
int averageAnalogReading()
{
    // First take and store the readings.
    int readings[500];
    for (int i = 0; i < 500; i++)
        readings[i] = analogRead(inputPin);

    // Then compute the average.
    long sum = 0;
    for (int i = 0; i < 500; i++)
        sum += readings[i];
    return sum / 500;
}

Storing all those readings is completely useless, as you can just update
the sum on the fly:
int averageAnalogReading()
{
    long sum = 0;
    for (int i = 0; i < 500; i++)
        sum += analogRead(inputPin);
    return sum / 500;
}

For the same reason, if you need some kind of running average to smooth
data, you should consider using an exponentially-weighted running
average, which can be incrementally updated without storing the
readings.

Upvoted, very good point. The best way to improve is to check the algorithms itself.
Short note: if you are interested in averages, also look at 'moving averages', also not costing additional SRAM for each measurement made.

@MichelKeijzers If you want a proper box-filter moving average then you do need to store the last N measurements. But if you can change it to an exponential filter, then you don't.

@user253751 You are right in that. Thanks for the clarification.

What are the generally practiced methods for the optimization program memory usage?

(nb. as per Edgar's comment I emphasise that this is about using PROGMEM more efficiently.)

If you can replace code with a table whose size is ≤ the lines of code, do it.

Instead of using a sequence of ifs, find a way to collapse the procedure into a table
Use tables of function pointers if it makes sense
Sometimes you can come up with a mini-language that is much more dense than AVR instructions, for example encoding robot logic into 16 commands, and then you can pack two commands per byte. This could collapse your memory usage 50-fold.

Use functions instead of repeated code—this may sound obvious but there are often subtle ways of rewriting code (but bear in mind that function calls have overhead)
Use hash tables rather than tables with big gaps
Use fixed point rather than floating point (e.g. you can take a byte and interpret its value as ranging from 0.00 to 2.55, instead of using a 4-byte float)

Is there any difference in memory usage if the variable is declared globally or locally.

Let's talk about the stack.
void A() {
    byte a[600];
    ...
}
void B() {
    byte b[400];
    ...
}
void loop() {
    byte xxx[1000];
    ...
}

This program will firstly use at least 1000 bytes of RAM all the time. There is no real difference compared to declaring xxx globally. But then what is critical is which function calls which.
If loop() calls A(), and then loop() calls B(), the program will not use more than 1600 at any time. However, if A() calls B(), or vice versa, the program will use 2000. To illustrate:
loop() [1000]
  └──── A() [1600]
  │    [1000]
  └──── B() [1400]
  └──── A() [1600]
  └──── B() [1400]

versus
loop() [1000]
  └──── A() [1600]
        └──── B() [2000]
  │    [1000]
  └──── A() [1600]
        └──── B() [2000]

Will it matter what the control statement/selection statements are (like if, switch )

Not much difference for a small number of cases. Otherwise it depends on your code. The best way is to just try both and see which is better. But:
switches usually use jump tables which are quite compact if you cover nearly every case in a range (0,1,2,3,4,..,100). ifs usually use a sequence of instructions, which take up more bytes and cycles than a jump table entry, but it makes more sense if you don't have a consecutive stretch of cases.

Usage of Serial monitor. Serial.print()

I don't believe that makes a lick of difference. Serial buffers are tiny (say 64 bytes, or 128 for a bigger board) and I believe they are allocated whether or not you use Serial.
Of course "literal strings like this" and char[] buffers consume memory. You can comment them out (or use #ifdefs) when you don't need them.

Note that your first 5 bullet points are about saving flash rather than saving RAM. The OP was not short on flash. The tables will actually cost RAM, unless you put them in PROGMEM. 2. Re “There is no real difference compared to declaring xxx globally”: that is, unless setup() is memory-hungry. 3. The serial buffers are not allocated if you don't use Serial.

Thanks @EdgarBonet 1. Yes, I was thinking of PROGMEM, sorry. 2. Could you explain this? Isn't setup()'s stack-allocated memory freed after it runs? 3. Thanks I have edited that.

Re explain point 2: setup() and loop() do not usually run at the same time, so their stack usages do not add up. If you make xxx global, it will be allocated even while setup() is running. This should be no concern unless setup() is itself memory-hungry.

Since you asked for traditional ways, I am going to raise a traditional method.  In this case, more than 50 years old.
Generate and analyze a listing.
Methodology:

Compile all the code with debugging turned on (add -g).

Link the code with debugging turned on, producing an ELF executable.  Do NOT convert to an image loadable on the arduino.

use objdump to make a listing.  My usage of this read:
( avr-objdump --headers --source --disassemble --syms program.elf ; \
  avr-objdump --full-contents --section=.final_progmem program.elf ) > program.lst

Your usage may vary based on what you prefer to see.

The point of this is that this allows you to see exactly what is using every byte of your memory.
You may want to play around with different optimizations, until you understand what you are seeing.  -O0 produces the most comprehensible disassembly, while -Os makes the smallest.
One tip based on having done this:  The Arduino libraries are designed for generality, not speed and memory efficiency.


text:
How to setup HC05 Module to be distinguishable
I'm not sure if this is a dumb question, but here goes  :
I am developing an Android app that uses a custom Bluetooth device as a companion. I'm using an HC05 module to interface the device with my app. What I need is a way for me to distinguish my HC05 module from, say, some other HC05 module that might be in range.
The obvious way of doing this would be to set the device name in a certain format. But I was wondering if there was a more better approach to this.
On searching, I found that UUID's are used for a similar purpose (i.e. service discovery), but I couldn't find any further info. Is it at all possible to set a custom UUID for the HC05 module so that I can filter devices in my Android app based on that?

AFAIK not directly, but I don't think you connect to the HC05 just to say "Hey, I'm here". You should have something attached to the HC05 serial port. What you can implement is a sort of identification command (like they always do for AT modems). For instance, when you connect you send "?" (or "ATI" like in modems) and it returns you "ShahiM's Bluetooth companion v1.05" or whatever string you prefer. This way you just have to ask him this. In the same way you can ask for a UUID (note that unique implies flashing a different value on each prototype or using hardware UUID memories)

And, by the way, there's no such thing as a stupid question

Your options are:

As you guessed, you could set the name with AT+NAME=, and only use the names matching some pattern. It would work if you're only user so you just want to ignore other BT devices, but is problematic if you're having multiple independent users (each with its different set of *HC05*s) who might be in range (you could set different pattern for each user, though).
build a database of addresses (read-only with AT+ADDR?), and only access those devices that are belonging to that user. It would avoid problem above with multiple users, but would require some logistics on your part (for example, when you sell user the app and HC05s, in the registration process you'll need to assign exactly which HC05 address that user my access. Or you might want to allow user to pick which devices are his, by having him specify specify PIN for pairing set with AT+PSWD=)
third way is to use custom Inquire Access Code instead of GIAC so only that set of devices is scanned. HC05 allows setting it with AT+IAC=. However, as it is more complex and nonstandard that (2), and you'd probably still need to registration to differentiate which user is allowed which IAC, I'd recommend you do (2) instead.

As frarugi87 recommended in the comments, you need to change the device's name. Changing the device name will allow you to identify it by a custom name that you come up with. To do this you need to use something called AT Commands. Here is a guide that contains many of the system parameters that you can check and change via AT Commands: http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS
Here is a brief summary about how to change the device name, quoted from the above Instructable:
First switch the device into command mode

For the HC-05 module to switch to AT command mode, the HC-05 pin 34
  (often referred to as the Key pin) needs to pulled HIGH but in a
  certain order of events explained below. When the HC-05 enters the AT
  command mode, it will communicate at 38400 baud rate. Follow these
  steps in the stated order to switch to the HC-05 to AT command mode.

Wire the HC-05 and Arduino Uno per instructions.
BEFORE YOU CONNECT THE ARDUINO TO THE USB remove the VCC (power) red wire from the HC-05 so it's not getting any power from the
  Arduino. All other wires are still connected.
Now connect the Arduino Uno to the USB cable extended from your PC.
Make sure the HC-05 module is NOT PAIRED with any other Bluetooth device.
Re-connect the Arduino Uno 5V wire to the HC-05's VCC (5V power) pin.
The HC-05 LED will blink on and off at about 2 second intervals. Now the HC-05 is in AT command mode ready to accept commands to change
  configuration and settings.
To test if everything is wired correctly,  open the Serial Monitor from the 8. Arduino IDE and type "AT" and click SEND. You should see
  an "OK" If you don't see an "OK" check your wiring.

Next run this program on your Arduino
/*

AUTHOR: Hazim Bitar (techbitar)
DATE: Aug 29, 2013
LICENSE: Public domain (use at your own risk)
CONTACT: techbitar at gmail dot com (techbitar.com)

*/

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Finally (the quotes aren't part of the command)

To change device name from the default HC-05 to let's say MYBLUE
  enter: "AT+NAME=MYBLUE"

This answer has been copied from a site. It shouldn't be allowed to collect this bounty.

I disagree. I know about bluetooth chips from past experiences, but I have never worked with the HC-05 so I had to look up how to put it in command mode. Then I summarized the article as it directly relates to the question. I think this should qualify for the bounty as I answered the question.

Joel has given attribution, and he would be told off for posting a link-only answer, so I think this is OK. If another person posts an answer which is accepted by the OP then that answer would collect the bounty.

Yes. I know changing the Device name is possible. My question was whether if there are any other methods.

Why do you need other methods? Are there any limitations, or application specifics that prevent you from changing the name? This will help give me more context for the answer.

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


text:
DHT11 Sensor Code Fatal Error
I recently tried using Hobbyist.co.nz's guide on the DHT11 sensor. I installed the Adafruit_Sensor and DHT11 Sensor libraries,  but it keeps returning with a fatal error.
Here is the code and the error:
#include <dht.h>

#define dht_dpin A0 //no ; here. Set equal to channel sensor is on

dht DHT;

void setup(){
  Serial.begin(9600);
  delay(300);//Let system settle
  Serial.println("Humidity and temperature\n\n");
  delay(700);//Wait rest of 1000ms recommended delay before
  //accessing sensor
}//end "setup()"

void loop(){
  //This is the "heart" of the program.
  DHT.read11(dht_dpin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");
  delay(800);//Don't try to access too frequently... in theory
  //should be once per two seconds, fastest,
  //but seems to work after 0.8 second.
}// end loop()

C:\Users\XXXXXX\Documents\Arduino\sketch_dec19c\sketch_dec19c.ino:2:17:

fatal error: dht.h: No such file or directory
#include <dht.h>

It doesn't look like you are using Adafriut's DHT library.

The examples I can see from Adafruit say
#include "DHT.h"

or
#include <DHT.h>

But you wrote
#include <dht.h>

They aren't the same.
Further, the examples for the Adafruit library show usage like:
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

But you call DHT.temperature and DHT.humidity.
If you are meaning to use the Adafruit library, you have to write your code according to their documentation.
Also of note, you have defined the type of the object as dht and the name as DHT, but for Adafruit, the type is DHT.
EDIT:
The example on the website you note has a downloadable zip file for the DHT library they use. You cannot assume that all libraries for interfacing a certain sensor will all have the same programming interface.

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


text:
A function-definition is not allowed here before '{' token
I'm trying to light up 81 on a 4-digit 7-segment display, but when I try to upload the code to my Uno R3 it gives me this error: "a function-definition is not allowed here before '{' token". I'm new to Arduino and this is my second day using it, so I would like to get help and know how to fix this problem. Here is my code:
int isej1 = 2;
int isej2 = 3;
int vienetas[] = { 12, 11 };
int astuonetas[] = { 13, 12, 11, 10, 9, 8, 7 };

void setup() {
  pinMode (vienetas[2], OUTPUT);
  pinMode (astuonetas[8], OUTPUT);
  pinMode (isej1, OUTPUT);
  pinMode (isej2, OUTPUT);
}

void uz_vien() {
  digitalWrite (vienetas[0], HIGH);
  digitalWrite (vienetas[1], HIGH);
}

void uz_astuon() {
  digitalWrite (astuonetas[0], HIGH);
  digitalWrite (astuonetas[1], HIGH);
  digitalWrite (astuonetas[2], HIGH);
  digitalWrite (astuonetas[3], HIGH);
  digitalWrite (astuonetas[4], HIGH);
  digitalWrite (astuonetas[5], HIGH);
  digitalWrite (astuonetas[6], HIGH);
}

void is_vien() {
  digitalWrite (vienetas[0], LOW);
  digitalWrite (vienetas[1], LOW);
}

void is_astuon() {
  digitalWrite (astuonetas[0], LOW);
  digitalWrite (astuonetas[1], LOW);
  digitalWrite (astuonetas[2], LOW);
  digitalWrite (astuonetas[3], LOW);
  digitalWrite (astuonetas[4], LOW);
  digitalWrite (astuonetas[5], LOW);
  digitalWrite (astuonetas[6], LOW);

void loop() {
  digitalWrite (isej1, LOW);
  digitalWrite (isej2, HIGH);
  void uz_vien();
  delay(5);
  void is_vien();
  digitalWrite (isej1, HIGH);
  digitalWrite (isej2, LOW);
  void uz_astuon();
  delay(5);
  void is_astuon();
}

The importance of proper indentation is clear here...
I thought you were missing a closing curly braces. When you type code, press regularly cmd/ctrl-T to ident your code -- it helps catching mistakes. You are indeed missing one, for is_astuon().
Moreover these lines are wrong too:
**void** uz_vien();
delay(5);
**void** is_vien();
digitalWrite (isej1, HIGH);
digitalWrite (isej2, LOW);
**void** uz_astuon();

The void part is not needed and creates the error.


text:
Value keeps incrementing even though loop has terminated, why?
I use a double called delta and use that to turn off an LCD if delta is larger than the timeout threshold. Once that happens, delta is supposed to set to 0 and then other parts of the program run. However, delta continues to increment and I'm not sure why.
This is causing a problem because delta is used to determine if the device should "sleep". So when I try to wake up the device via button click, delta is always way past the timeout threshold and the device immediately goes back to sleep.
Any thoughts as to why? Thanks in advance.
#include <M5StickC.h>

double BUTTON_PRESS_NEXT_PRESS_TIME= .5; //Time in seconds
double MINIMUM_BUTTON_PRESS_TIME = .05; //Time in seconds
int BUTTON_PRESS_SLEEP = 3; //Time in seconds
int SCREEN_TIMEOUT = 5;
int count;

static int pressCount = 1;
static int nextPress= 1;

static bool buttonIsPressed;

void setup(void) {
  buttonIsPressed = false;
  M5.begin();
  M5.Lcd.setRotation(0);
  M5.Lcd.fillScreen(TFT_BLACK);
  M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Axp.ScreenBreath(100);

  updateScreen();
}

void updateScreen() {
   char tmp[12];

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Lcd.drawString(dtostrf(pressCount,4,0,tmp), 80,60,6);
  M5.Lcd.drawString(dtostrf(nextPress,3,0,tmp), 80,100,6);
}

static void evaluatePress(double d) {
   // Evaluate press
  if (d >= BUTTON_PRESS_NEXT_PRESS_TIME) {
    nextPress++;
    pressCount = 1;

    if (nextPress == 19) {
      nextPress= 1;
    }
  }
  else if (d >= MINIMUM_BUTTON_PRESS_TIME && d < BUTTON_PRESS_NEXT_PRESS_TIME) {
    pressCount++;
  }

  updateScreen();
}

void sleepLoop() {
  bool bIsPressed = false;
  Serial.println("Sleep 1");
  while(1) {
    Serial.println("Sleep 2");
    if (digitalRead(M5_BUTTON_HOME) == LOW && !bIsPressed) {
      bIsPressed = true;
    }

    if (digitalRead(M5_BUTTON_HOME) == HIGH && bIsPressed){
      Serial.println("BREAKY BREAKY");
      M5.Axp.ScreenBreath(100);

      break;
    }
  }
}

void awakeLoop() {
  double delta;
  double old_time;
  double current_time;

  Serial.println("Awake 1");

  while(1) {
    Serial.println("Awake 2");
     //Calculate delta time
    old_time = current_time;
    current_time =  millis();
    delta = delta + (current_time - old_time)/1000;

    if (digitalRead(M5_BUTTON_HOME) == LOW && !buttonIsPressed) {
      buttonIsPressed = true;
      delta = 0;
    }

    if(digitalRead(M5_BUTTON_HOME) == HIGH && buttonIsPressed) {
      buttonIsPressed = false;
      evaluatePress(delta);
      delta=0;
    }

    if(delta > SCREEN_TIMEOUT && !buttonIsPressed) {
      Serial.println(delta);
      Serial.print("BREAK AWAKE");
      Serial.println(M5.Axp.ScreenBreath(0));
      count = 0;
      break;
    }
    else {
      count++;
    }
  }

  delta = 0;
}

void loop() {
  awakeLoop();
  sleepLoop();
}

Sorry, but that's a crazy way of doing a screen timeout. You don't need delta and you certainly don't want it to be a double...  Just record current_time = millis() when an action happens and break when (millis() - current_time) > 5000.

Thanks @Majenko. I've stripped out some code so that the question focuses more directly on the problem. I think I can do what you suggested though and will give it a try. What's wrong with a double?

@Kyle double needs floating point operations for every calculation, which the Arduino does not support in its hardware. Thus this has to be done in software, which is very computation expensive. So a general rule is, to only use a floating point type (float or double), when it is really necessary. millis() uses unsigned long, so why not using the same for the variables?

Here:
void awakeLoop(){
  double delta;
  // The rest of the function body...
  delta = 0;
}

delta is being defined as a variable local to the function awakeLoop()
and with automatic storage. This means the variable is created whenever
the program enters the function, is not implicitly initialized, and is
destroyed when the function returns.
The last statement delta = 0; has no effect, as it is setting a
variable that is going to be destroyed right away. The compiler most
likely got rid of it.
You most likely want the variable to retain its value across invocations
of the function. For this to be the case, it has to be either global
(defined outside the function) or local with the static qualifier. In
both cases, it will have static storage, i.e. its lifetime will be the
whole program run. Also, if you fail to explicitly initialize it, the
compiler will implicitly initialize it to zero.

Thanks @Edgar Bonet. The problem that I'm having is that delta does not actually get set to 0 or destroyed. I know that I shouldn't/don't need to set delta to 0 at the end of the loop, but I added that line because the program is not acting as I'd expect. The line that prints out delta, right below "Brake awake" always prints out a value that I would expect if the loop were to run continually.

@Kyle: That value is meaningless, as delta has not been initialized. Whether it matches your expectations or not is just chance, and you should not count on it.


text:
Automatic water pump Trigger System - I need my code FIXED
int out = LED_BUILTIN;
int strt = 3;
int stp = 9;
void setup() {
  pinMode(out,OUTPUT);
  pinMode(strt,INPUT);
  pinMode(stp,INPUT);
}

void loop() {
  while(true) {
    if(digitalRead(strt) == LOW) {
      digitalWrite(out,HIGH);
      delay(1000);
    }
    if(digitalRead(stp) == HIGH) {
      digitalWrite(out, LOW);
      delay(1000);
    }
  }
}

I'm a beginner so I believe someone would help me out. Actually the mechanism I'm using for turning the state of Pin 3 & 9 is through 3 wires connected to the Pins D3,D9 & 5V in the nano board. Where 5 V is immersed in water and Pin 3 does not touch water Nano's Built in LED is turned on and if the water reaches Pin 9 (while the Pin 3 wire is still submerged under water) the LED goes Off.
In the above code, the Built in LED turns High just fine if Input Pin 3 Reads Low. Although as soon as Pin 3 goes High the LED turns Low and does not wait for Reading input pin 9 which is when the LED should actually turn Off.
In the first IF Clause (For Reading Pin 3(strt) to LOW) I want that part of the code to only set the OUTPUT pin LED_BUILTIN to be set to HIGH & not revert back to LOW if pin 3 is turned to HIGH. But only if the INPUT pin 9 in the second IF Clause reads HIGH then only should the OUTPUT Pin LED_BUILTIN be set to LOW.
Thank You for the helping hand.
This is the Link for the Code that I used(I Modified the code to have two input Wires) : https://www.instructables.com/Water-Level-Alarm-Using-Arduino/

as soon as Pin 3 goes High the LED turns Low  - that makes no sense. The only way the LED can go LOW is if pin 9 reads high.

That is right . That's what was supposed to happen. But as I said earlier when the wire connected to Pin 3 touches the water (ie Pin 3 Goes High) LED goes LOW. But I want nothing to happen if Pin 3 goes High. Only if Pin 3 goes Low should the LED turn on. I hope I'm clear. Please help me!

the while(true){ is redundant .... loop() already does that

change your code so that the led is controled by pin 3 only ... verify that the harware responds as expected by repeatedy dipping pin 3 wire in water (shorten the delay for this)


text:
Grove - Mech Keycap counter
I am using Grove - Mech Keycap as a counter but if I continue pressing the keycap the counter continues to run. Any idea how to program it to increase counter by one only after releasing and pressing again?
#define BUTTON_PIN   8

bool oldState = LOW;
long timecheck;
int i = 1;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop()
{

  // Get current button state.
  bool newState = digitalRead(BUTTON_PIN);

  // Check if state changed from low to high (button press).
  if (newState == HIGH && oldState == LOW) {
    timecheck = millis();
    // Short delay to debounce button.
    delay(200);
    // Check if button is still low after debounce.
    newState = digitalRead(BUTTON_PIN);

    if (newState == HIGH) {
      Serial.println("HIGH");
      Serial.println(i);
      i = i + 1;
    }
  }
}

use the Bounce2 library (or set oldState )

You never change oldState...?

how & to what shell I change the oldState?

when you determine that the state changed ... how else would you remember the state of the system?

Change oldstate to equal newstate when oldstate and newstate differ. That way you can know when oldstate and newstate differ....


text:
Using SMS to send commands to the Arduino. Having problems in data parsing
I'm still inexperienced in programming and i apologize in advance if my mistakes are stupidly obvious. This sketch I'm working on is a basic GSM project using SIM900a Mini and an Arduino UNO that could send a message to a recipient with a press of a button. I created a function so that if i send a command to the GSM, i could change the recipient and check the current recipient through my phone.
One thing to note is that before i resorted to creating this sketch, I created an almost working project with the same concept using SIM800L and an arduino Nano and i used the GSM Library. However, when it was hooked up to a variable Step-up converter for the needed supply of the ~4 V using a 3.7V Li-Po battery, it was damaged because the booster suddenly supplied 12V to the GSM. The SIM800L won't connect to the network anymore after that incident. I resorted to using SIM900a-Mini and it wasn't compatible with the GSM Library i guess because it can't get pass the initialization stage. Though i've seen youtube videos using both the SIM900 and the GSM Library, though i can't seem to make it work even though the two share the same chipset (i think). This current sketch works with some issues. Here's the sketch:
#include <SoftwareSerial.h>
#include <SIM900.h>
#include <sms.h>
#define button 10
SMSGSM sms;

char senderNumber[15], recipientNumber[15] = "No recipient", newRecipient[15], commandkey[30] = {0};
char SmsText[30], smsRecieved[30];;
boolean validRecip, GSMconnected = false;
int buttonState = 0;

void setup(){
  Serial.begin(9600);
  Serial.println("Micro_GSM_Project");
  Serial.print("Initializing Serial:");
  pinMode(button, INPUT);
  pinMode(buzzer, OUTPUT);
  while (!Serial){
    Serial.println("Serial not connected");
  }
  delay(500);
  Serial.println(" Done");
  delay(1000);
  Serial.print("Initializing GSM Module:");
  if (gsm.begin(2400)) {
    Serial.println("\nWaiting for messages");
    GSMconnected = true;
    delay(1000);
  }
  else Serial.print("GSM Connecting");
}

void loop() {
  if (GSMconnected)
    {
    buttonState = digitalRead(button);
    if (buttonState == HIGH)
    {
      activate();
    }
    if (gsm.readSMS(SmsText, 30, senderNumber, 15))
    {
      Serial.print("\nMessage received from: +");
      Serial.println(senderNumber);
      Serial.println(SmsText);
      parseData();

     if (strcmp(commandkey, "CURRENT RECIP") == 0)
        {
          currentRecip();
        }
     else if (strcmp(commandkey, "SET RECIP") == 0)
        {
          changeRecip();
          confirmation();
        }
     else
     Serial.println("Invalid Command");
     sms.SendSMS(senderNumber, "The command you sent is invalid");
    }
  }
}

void activate() {
  delay(800);
  Serial.println("I have become self aware. Run");
  sms.SendSMS(recipientNumber,"I have become self aware. Run");
}

void parseData() {
  char * strtokIndx;
  strtokIndx = strtok(SmsText, ",");  //Read first part of Command either "SET RECIP" or "CURRENT RECIP"
  strcpy(commandkey, strtokIndx);         //store to commandkey variable

  strtokIndx = strtok(NULL, ",");         //Read where the last call left off, separated by a comma
  strcpy(newRecipient, strtokIndx);       //store to newRecipient variable

  Serial.print("Command Selected:");
  Serial.println(commandkey);
}

void currentRecip() {
  Serial.print("Current Recipient is: ");
  Serial.println(recipientNumber);
  delay(1000);
  sms.SendSMS(senderNumber, "Current Recipient is: recipientNumber");// i currently dont know how to log the variable recipientNumber to this string
}

void changeRecip()
    {
  validate();
    if (validRecip == true)
    {
    strcpy(recipientNumber, newRecipient);
    sms.SendSMS(senderNumber, "The Recipient number you have entered is valid");
    Serial.print("Recipient Number: ");
    Serial.print(recipientNumber);
    Serial.println("a");
    Serial.print("Sender Number");
    Serial.println(senderNumber);
    }
    if (validRecip == false)
    {
      Serial.println("Invalid Recipient");
      sms.SendSMS(senderNumber, "The Recipient number you have entered is invalid");
    }
    }

void validate()
  {
  if (strlen(newRecipient) == 13)   //I've put 13 here as a reference because the output strlen of the parsed newRecipient is 13 instead of the 12 characters composing the newRecipient i sent through sms. I think this is the null terminating character used by the strtokIndx? Please correct me if I'm wrong
  {
    Serial.println("Recipient is Valid\n");
    validRecip = true;
  }
  else
  {
    validRecip = false;
  }
}

void confirmation()
{
    if (validRecip == true)
    {
    Serial.println("Recipient Number successfully changed");    //Serial Monitor confirmation (for troubleshooting)
    Serial.print("New Recipient: +");
    Serial.println(recipientNumber);
    Serial.println("Informing Admin...");
    }
    if (sms.SendSMS(senderNumber, "Recipient Number successfully changed\nNew recipient: recipientNumber"))  //same here
    {
    Serial.println("Message Sent\n\n");
    }
    else
    {
    Serial.println("Invalid Recipient");
    sms.SendSMS(senderNumber, "The Recipient number you have entered is invalid");     //uncomment for SMS confirmation, need load
    }
}

These are the current issues with my current code (in order of priority) .

Even though the serial monitor displays the correct new recipient, **the recipient doesn't receive any message when the device is activated.**I think this is because of the data parsing method i used which creates a null character which increases the byte size of the recipientNumber variable. Through strlen, I've found out that the recipientNumber's size is 13 while the senderNumber fetched by the library has a size of 12. Even though the displayed number of characters in the serial are both 12. I tried changing the byte size of the array to 12 but once i did that, whenever i send the command to change the recipient, the program doesnt recognize the parsed command. It comes as blank.
If i send the command "CURRENT RECIP" the serial outputs both the currentRecip() and the "Invalid command". If i put the "CURRENT RECIP" in the else if statement, swapping with the "SET RECIP", the "CURRENT RECIP" command works properly. For some reason, the command which is put in the else if statement works properly. I've tried adding another statement. i honestly don't fully understand what i wrote there myself. Still doesn't work tho.

else if ((strcmp(commandkey, "CURRENT RECIP") != 0) || (strcmp(commandkey, "SET RECIP") != 0){
Serial.println("Invalid Command");
}

The project is supposed to activate at a simple push of a button. However, with my current sketch, it only activates when the button is long pressed. The issue i have here is i dont know where to properly put the activate(). I've tried placing it at the beginning of the loop and inside the if (GSMconnected) statement. However, both have the same result. I still have to press it long enough for the arduino to stop checking for available messages and proceed to the if (buttonState) statement.

if (buttonState == HIGH){
activate();
}

This sketch uses this GSM Library and i implemented the data parsing method from Serial Input Basics. The sketch properly separates the command i send which is "SET RECIP,XX**********" and proceeds to save it to the recipientNumber variable. The button can then be pressed and the GSM sends the message to the newly set recipient. Unfortunately, I am currently in a deadline and i dont think i have to time to scrap this sketch i made and just resort to AT commands. Please feel free to ask about any details i haven't covered. Any help would be appreciated and again i apologize in advance because some issues here might be fixed with just a simple syntax correction. Thank you in advance.


text:
Compile error with Arduino tensorflow lite library
I was reading the article about tensorflow lite on SAMD51 here and tried it and failed to compile.
It was the example from the arduino tensorflow lite lirabry and doesnt seem to compile.
Selected Adafruit M4 boards and failed to compile, but can compile with ArduinoMKRZERO(SAMD21).
Here follows the error message:
Arduino: 1.8.12 (Mac OS X), Board: "Adafruit Grand Central M4 (SAMD51), Enabled, 120 MHz (standard), Small (-Os) (standard), 50 MHz (standard), Arduino, Off"

    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:19:0,
                     from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:58:5: error: unknown type name 'int16_t'
         kiss_fft_scalar r;
         ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:59:5: error: unknown type name 'int16_t'
         kiss_fft_scalar i;
         ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c: In function 'kf_bfly2':
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:48:27: error: 'int16_t' undeclared (first use in this function)
     #  define kiss_fft_scalar int16_t
                               ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:26: note: in expansion of macro 'kiss_fft_scalar'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:8: note: in expansion of macro 'sround'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
            ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:33:9: note: in expansion of macro 'C_FIXDIV'
             C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2);
             ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:48:27: note: each undeclared identifier is reported only once for each function it appears in
     #  define kiss_fft_scalar int16_t
                               ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:26: note: in expansion of macro 'kiss_fft_scalar'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:8: note: in expansion of macro 'sround'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
            ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:33:9: note: in expansion of macro 'C_FIXDIV'
             C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2);
             ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:0:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:51:19: error: 'int32_t' undeclared (first use in this function)
     # define SAMPPROD int32_t
                       ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:47: note: in definition of macro 'sround'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                                                   ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:64:25: note: in expansion of macro 'SAMPPROD'
     #   define smul(a,b) ( (SAMPPROD)(a)*(b) )
                             ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:16: note: in expansion of macro 'smul'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
                    ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:33:9: note: in expansion of macro 'C_FIXDIV'
             C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2);
             ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:19:0,
                     from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c: In function 'kf_bfly4':
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:48:27: error: 'int16_t' undeclared (first use in this function)
     #  define kiss_fft_scalar int16_t
                               ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:26: note: in expansion of macro 'kiss_fft_scalar'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:8: note: in expansion of macro 'sround'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
            ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:61:9: note: in expansion of macro 'C_FIXDIV'
             C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4);
             ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:0:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:51:19: error: 'int32_t' undeclared (first use in this function)
     # define SAMPPROD int32_t
                       ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:47: note: in definition of macro 'sround'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                                                   ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:64:25: note: in expansion of macro 'SAMPPROD'
     #   define smul(a,b) ( (SAMPPROD)(a)*(b) )
                             ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:16: note: in expansion of macro 'smul'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
                    ^
    Multiple libraries were found for "Adafruit_ZeroDMA.h"
     Used: /Users/ansonhe/Library/Arduino15/packages/adafruit/hardware/samd/1.5.4/libraries/Adafruit_ZeroDMA
     Not used: /Users/ansonhe/Documents/Arduino/libraries/Adafruit_Zero_DMA_Library
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:61:9: note: in expansion of macro 'C_FIXDIV'
             C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4);
             ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:19:0,
                     from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c: In function 'kf_bfly3':
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:48:27: error: 'int16_t' undeclared (first use in this function)
     #  define kiss_fft_scalar int16_t
                               ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:26: note: in expansion of macro 'kiss_fft_scalar'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:8: note: in expansion of macro 'sround'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
            ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:109:10: note: in expansion of macro 'C_FIXDIV'
              C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3);
              ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:0:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:51:19: error: 'int32_t' undeclared (first use in this function)
     # define SAMPPROD int32_t
                       ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:47: note: in definition of macro 'sround'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                                                   ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:64:25: note: in expansion of macro 'SAMPPROD'
     #   define smul(a,b) ( (SAMPPROD)(a)*(b) )
                             ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:16: note: in expansion of macro 'smul'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
                    ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:109:10: note: in expansion of macro 'C_FIXDIV'
              C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3);
              ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:19:0,
                     from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c: In function 'kf_bfly5':
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:48:27: error: 'int16_t' undeclared (first use in this function)
     #  define kiss_fft_scalar int16_t
                               ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:26: note: in expansion of macro 'kiss_fft_scalar'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:8: note: in expansion of macro 'sround'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
            ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:160:9: note: in expansion of macro 'C_FIXDIV'
             C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
             ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:0:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:51:19: error: 'int32_t' undeclared (first use in this function)
     # define SAMPPROD int32_t
                       ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:47: note: in definition of macro 'sround'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                                                   ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:64:25: note: in expansion of macro 'SAMPPROD'
     #   define smul(a,b) ( (SAMPPROD)(a)*(b) )
                             ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:16: note: in expansion of macro 'smul'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
                    ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:160:9: note: in expansion of macro 'C_FIXDIV'
             C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
             ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:19:0,
                     from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c: In function 'kf_bfly_generic':
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/kiss_fft.h:48:27: error: 'int16_t' undeclared (first use in this function)
     #  define kiss_fft_scalar int16_t
                               ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:26: note: in expansion of macro 'kiss_fft_scalar'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:8: note: in expansion of macro 'sround'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
            ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:217:13: note: in expansion of macro 'C_FIXDIV'
                 C_FIXDIV(scratch[q1],p);
                 ^
    In file included from /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:16:0:
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:51:19: error: 'int32_t' undeclared (first use in this function)
     # define SAMPPROD int32_t
                       ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:65:47: note: in definition of macro 'sround'
     #   define sround( x )  (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS )
                                                   ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:64:25: note: in expansion of macro 'SAMPPROD'
     #   define smul(a,b) ( (SAMPPROD)(a)*(b) )
                             ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:74:16: note: in expansion of macro 'smul'
      (x) = sround( smul(  x, SAMP_MAX/k ) )
                    ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/third_party/kissfft/_kiss_fft_guts.h:77:10: note: in expansion of macro 'DIVSCALAR'
      do {    DIVSCALAR( (c).r , div);  \
              ^
    /Users/ansonhe/Documents/Arduino/libraries/Arduino_TensorFlowLite/src/tensorflow/lite/experimental/micro/tools/make/downloads/kissfft/kiss_fft.c:217:13: note: in expansion of macro 'C_FIXDIV'
                 C_FIXDIV(scratch[q1],p);
                 ^
    exit status 1
    Error compiling for board Adafruit Grand Central M4 (SAMD51).

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

Please let me know if anyone has any ideas, much appreciated.


text:
Using SMS to receive password, then to choose whether to turn the relay on or off
I'm trying to use SMS messages to turn a relay on/off but before doing that i need to have a password system before allowing the user to turn the relay on/off. Basically, you have to send the password to the GSM via SMS first, then have an option select of ON or OFF, which you also send to the GSM. I can already do the password and ON/OFF of the relay separately, but I'm having trouble trying to combine them together. Here is the code:
String _buffer;
String number = "+639562284415";
String textMessage;
String relayState = "HIGH";

int relay = 24;
int _timeout;

void setup() {
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);

  Serial.begin(9600);
  Serial1.begin(9600);
  delay(1000);
  Serial.print("SIM900 ready...");
  Serial1.print("AT+CMGF=1\r");
  delay(100);
  Serial1.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

void loop() {
  if (Serial1.available() > 0) {
    textMessage = Serial1.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if (passFlag == 0) {
    if (textMessage.indexOf("1231") >= 0) {
      commandList();
      passFlag++;
      if (textMessage.indexOf("ON") >= 0) {
        // Turn on relay and save current state
        digitalWrite(relay, LOW);
        relayState = "on";
        Serial.println("Relay set to ON");
        textMessage = "";
      }

      if (textMessage.indexOf("OFF") >= 0) {
        // Turn off relay and save current state
        digitalWrite(relay, HIGH);
        relayState = "off";
        Serial.println("Relay set to OFF");
        textMessage = "";
      }
    }
  }
}

void commandList() {
  Serial.println ("Sending Message");
  Serial1.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  Serial.println ("Set SMS Number");
  Serial1.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Enter your command!";
  Serial1.println(SMS);
  delay(100);
  Serial1.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}

String _readSerial() {
  _timeout = 0;
  while  (!Serial1.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (Serial1.available()) {
    return Serial1.readString();
  }
}

Basically what happens with this code is that it succeeds with the password entry, but it somehow skips over the ON/OFF option select. Since I used a flag to increment the password entry (so it doesn't endlessly send me the "Enter your command" message), the loop completely stop after loop. I want to use switch case but I don't really know how to use it in this case. I don't really know how to best approach this problem, so if anyone can give some advice I would really appreciate it! BTW I'm using a SIM800L and Arduino MEGA for this

If you first receive a password and then receive a command separately, in my opinion, the password is useless, because the command can be send from another sender and would be aceepted even if the password comes from the first sender. So I would send the command and the password in one message. e.g #<password>#ON or so.

The problem with the code above is that you only look after the pass word or one of the commands if passFlag is 0 (btw the variable is not declared in the code above. So you check for the password that succeeds the give me a command SMS is send and then you test for the command before the command SMS was received. In a later loop run the command SMS will be received but the if statements that test for the command will never be executed, because passFlag>0.  You could try to move the if (textMessage.indexOf("???") >= 0) out of the if (passFlag == 0) { block.

i decided to go with making the password go together with the command, because what you said makes sense to me (password is useless if because command can come from another sender after entering the password). thanks!

That has been a wise decision IMHO. Your welcome.  Cheers.