text:
Serial communication of strings
I used this simple code to understand the basics of serial communication. This achieves simple communication between the computer and arduino:
String receive_buffer;
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()>0)  //check for any data received
  {
      receive_buffer = Serial.readString();  //read received data
      Serial.print("received data is: ");
      Serial.println(receive_buffer);        //display received data
  }

}

This works. Now, my next idea was to try communicating between two arduinos. I used this code for the reciever arduino.
The sender arduino contains a motor fitted with an encoder, and using the ppr value I  calculate the rpm of the motor. The code for rpm works perfectly. I now want to communicate this data to the receiver.
Wiring: (RX,TX) of sender connected to (TX,RX) of receiver, and GND is made common.
Now, on arduino.cc, it says that Serial.write() can have String as an input. So, I tried typecasting the rpm value (which was int), into a String, and then send that string to the receiver through Serial.write().
float ppr=512.0;
int encpin=3;
volatile long pulsecount=0;
float revs;
float rps;
int rpm;

extern volatile unsigned long timer0_millis;

void setup()
{
  pinMode(encpin,INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
                                        //when pulse is detected
                                           //interrupt triggered,
                                           //function callled
}
//increments pulse by one
void function(){
  pulsecount+=1;
}

void loop()
{
 revs= pulsecount/ppr ;
 if(millis()>=1000)
  {
    rps= revs;
    rpm=rps*60;
    pulsecount=0; //resets pulsecount

    String strrpm= (String)rpm;

    //Serial.println(rpm);
    Serial.write(strrpm);

   // Serial.println("string rpm");
    //Serial.println(strrpm);

    noInterrupts ();  //resests millis() to 0
    timer0_millis = 0;
    interrupts ();
  }
}

However, I get an error:
43:24: error: no matching function for call to 'HardwareSerial::write(String&)'

The issue is not with typecasting. I tried to simply print strrpm and it worked fine. When tried Serial.write() with a different and simple string, i.e Serial.write("abcdef"); , it still gave the same error.
How then should I should I send my strrpm (string rpm) value to the receiver?

Serial.write() is meant for sending binary data. So if you want to send a string with it, you need to provide a c-string, not the Arduino implementation of the String class. That's done easily with a member function of that class:
Serial.write(strrpm.c_str());

That compiles successfully for me.
Though you should not do it like this. The String class is generally bad on small microcontrollers, especially on the AVR microcontrollers with little memory (like Uno, Nano, Mega, ...), because it causes memory fragmentation (see Majenkos "The Evils of Arduino Strings").
Instead you should just use the corresponding print() functions of the Serial class. They are made for sending human readable strings. No need to first build up a String object. Just do
Serial.println(rpm);

And it will do the string conversion itself without using the String class.

Besides that I have some notes on your code:

The way you use millis() is a bit weird. There is no need to actually reset the millis() value itself. Normally you would hold a timestamp in a variable and then only calculate the difference between millis() and the timestamp. That is also overflow safe. Like this
  unsigned long timestamp = 0;

  ...
  if(millis()-timestamp >= 1000){
      ...
      timestamp+=1000;
  }

That doesn't use an extern variable, it is not resetting the millis() counter (which might mess with other things too, that rely on it) and is somewhat the standard way to do it.

You are using an atomic section for resetting the millis() counter, but not for accessing pulsecount. That is actually the place, where you absolutely need this. pulsecount is of type long, so it will need many instructions to do the calculation for revs. The your interrupt service routine can easily mess with the data in that moment, resulting in garbled data. Move  the calculation into the if statement and use an atomic section like with the millis() counter to read it into a local variable then you can do the calculations. That will keep the time, where interrupts are turned off very short. You can also - instead of turning all interrupts off - just detach the pin interrupt for that time, so that other things are not affected. Like this code:
  void loop(){
      if(millis()-timestamp > 1000){
           // deactivate our pin interrupt, so it cannot mess with the data
           detachInterrupt(digitalPinToInterrupt(encpin));
           // copy pulsecount to local variable for further calculation
           long local_pulsecount = pulsecount;
           // reactivate our pin interrupt
           attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
           // Do calculation and print the value
           ...
           timestamp += 1000;
       }
   }

" Instead you should just use the corresponding print() functions of the Serial class. They are made for sending human readable strings. No need to first build up a String object. Just do Serial.println(rpm)"  But I dont see how this makes the arduinos communicate?

Also, your initial suggestion: the code ccompiles succesfully, and prints the values on the serial monitor of the sender: but the serial monitor of the receiver is blank

Serial.println() will already send the data in human readable form via serial. Thus it is already communication. Please try using Serial.readStringUntil('\n') instead of Serial.readString(). The latter has a 1s timeout. Since you are sending every second there is less than 1s inbetween each transmission. This might cause that function to never exit. The former function call will read only until the newline character, which is automativally added by the println() function


text:
Will the noise from a voltage regulator interfere with IR LEDs and receivers on an Atmega328? (Arduino Uno sketch)
I have a project which uses an IR LED and receiver to communicate with other Arduinos. I am using the Atmega328 out of the Uno, rather than the whole Arduino board and I need it to be battery-powered, so I need to use a voltage regulator to maintain 5V to the chip.
I want to avoid a linear regulator if I can, as they are inefficient, but I'm worried that the other types will cause too much noise on the output and it will interfere with the IR communication.
Should I be concerned about this or am I making a fuss about nothing, I can always use a linear one if I need to.
Thanks in advance.

Depends on the switching frequency of the regulator. If it coincides with the IR carrier frequency, or a multiple thereof, then possibly.

If in doubt add some suitable filtering.

I bought a switching mode voltage regulator (buck-boost) to test it and it works fine, I put a 10uF capacitor across the output to reduce noise but that was just a precaution - I don't know if it was necessary.

source: Stack Exchange

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

sort: votes


text:
Prevent flicker - Lcd with I2C module?
I have a 16x2 LCD with a I2C interface, and a Esp8266 based NodeMCU.
I Have an issue where the second line of the LCD is flickering, but somehow the first line does not flicker.
Why does this happen and how do I prevent it?
My code :-
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include "DHT.h"
#include "LiquidCrystal_PCF8574.h"
#include <EEPROM.h>

#define BLYNK_PRINT Serial
#define DHT_PIN_DATA  12
// LCD definations
#define LCD_ADDRESS 0x27
#define LCD_ROWS 2
#define LCD_COLUMNS 16
#define SCROLL_DELAY 150
#define BACKLIGHT 25
#define DHTTYPE DHT22

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "ymri80lbh9_xZhf6WIRHtQ1qHYOt9zBy";
char ssid[] = "DB";
char pass[] = "bkg88q";
int autoSch;
int waterNow;
int morTime;
int afterTime;
int postNoon;
int eveTime;
int schTime;
int minStep;
int interval;
int count;
int flag = 0;
unsigned long previousMillis = 0;

DHT dht(DHT_PIN_DATA, DHTTYPE);
LiquidCrystal_PCF8574 lcdI2C;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "in.pool.ntp.org", 19800, 600000);
// This function will be called every time Slider Widget
// in Blynk app writes values to the Virtual Pin 1

BLYNK_CONNECTED() {
  Blynk.syncAll();
}

BLYNK_WRITE(V0)
{
  autoSch = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V1)
{
  morTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V2)
{
  afterTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V6)
{
  postNoon = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V3)
{
  eveTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V10)
{
  waterNow = param.asInt(); // assigning incoming value from pin V1 to a variable

}

BLYNK_WRITE(V4)
{
  schTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V7)
{
  minStep = param.asInt(); // assigning incoming value from pin V1 to a variable
}

void setup()
{
  dht.begin();
  lcdI2C.begin(LCD_COLUMNS, LCD_ROWS, LCD_ADDRESS, BACKLIGHT);
lcdI2C.setBacklight(2);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  pinMode(14, OUTPUT);
  digitalWrite(14, LOW);
  Blynk.virtualWrite(V5, 0);
  Blynk.virtualWrite(V8, 0);
  pinMode(2, INPUT_PULLUP);
  Serial.begin(9600);
  EEPROM.begin(512);
  //WiFi.begin(ssid, password);
  Blynk.begin(auth, ssid, pass);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  timeClient.begin();
  Blynk.syncAll();
}

void loop()
{
  Blynk.run();
  time_run();
  lcd();
  butPress();
  //test();
  timeClient.update();
  if (waterNow == 1) {
    waterNowrun();
  } else if (autoSch == 0) {
    auto_run1();
  } else if (autoSch == 1) {
    sch_run2();
  } else {
    Blynk.virtualWrite(V10, 0);
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
    Blynk.syncAll();
  }
  Blynk.syncAll();
}

void lcd() {
  lcdI2C.clear();

  timeClient.update();
  lcdI2C.print(timeClient.getFormattedTime());

  if (autoSch == 0) {
    lcdI2C.setCursor(9, 0);
    lcdI2C.print("Auto");
  } else {
    lcdI2C.print(" Sch");
  }

  if (digitalRead(14) == 1) {
    lcdI2C.selectLine(2);
    lcdI2C.print("Wtr Now           ");
  }
  else
  {

    if (int(timeClient.getHours()) < 6 && morTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a");
    } else if (int(timeClient.getHours()) < 12 && afterTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 12n");
    } else if (int(timeClient.getHours()) < 14 && postNoon == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at:14pn");
    } else if (int(timeClient.getHours()) < 18 && eveTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 18e");
    } else if (int(timeClient.getHours()) >= 18 && morTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a");
    } else {

    }

  }

}

void waterNowrun() {
  interval = minStep * 60 * 1000;
  unsigned long currentMillis = millis();
  Serial.println (currentMillis);
  Serial.println (previousMillis);
  Blynk.syncAll();
  if (((currentMillis - previousMillis) >= interval) || waterNow == 0) {
    previousMillis = currentMillis;
    Blynk.virtualWrite(V10, 0);
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
    Blynk.virtualWrite(V8, 0);
    Blynk.syncAll();
  } else {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    lcdI2C.selectLine(2);
    lcdI2C.print("Wtr Now :");
    lcdI2C.print((minStep * 60) - ((currentMillis - previousMillis) / 1000));
    Blynk.virtualWrite(V8, ((interval / 1000) - ((currentMillis - previousMillis) / 1000)));
    Blynk.syncAll();
  }
}

void sch_run2() {
  if (schTime == 1) {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  } else if (schTime == 0) {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
    Blynk.syncAll();
  }

}

void time_run() {
  Blynk.virtualWrite(V11, int(timeClient.getHours()));
  Blynk.virtualWrite(V12, int(timeClient.getMinutes()));
  Blynk.virtualWrite(V13, float(dht.readTempC()));
  Blynk.virtualWrite(V14, float(dht.readHumidity()));

}

void butPress() {
  if (digitalRead(2) == LOW) {
    if (flag == 0) {

      flag = 1;
      digitalWrite(14, HIGH);
    }
    else {
      digitalWrite(14, LOW);
      flag = 0;
    }
    int y = 10;
    int x = 0;
    if (digitalRead(14) == HIGH) {
      for (x = 0; x < y; x++) {
        delay(500);
        Serial.println("x:  ");         Serial.println(x);
      }
    }else{
      digitalWrite(14, LOW);
      }

  }
}

void test() {
  if (digitalRead(2) == LOW) {
    Serial.println("IDLY BLAA");
    int y = 10;
    for (int x = 0; x < y; x++) {
      delay(500);
      Serial.println("x:  ");         Serial.println(x);
    }
  }

}

void auto_run1() {
  if (morTime == 1 && String(timeClient.getFormattedTime()) > "06:00:00" && String(timeClient.getFormattedTime()) < "06:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  }
  else if (afterTime == 1 && String(timeClient.getFormattedTime()) > "12:00:00" && String(timeClient.getFormattedTime()) < "12:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  }
  else if (postNoon == 1 && String(timeClient.getFormattedTime()) > "14:00:00" && String(timeClient.getFormattedTime()) < "14:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  }
  else if (eveTime == 1 && String(timeClient.getFormattedTime()) > "12:59:00" && String(timeClient.getFormattedTime()) < "13:01:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();
  }
  else  {
    //(String(timeClient.getFormattedTime() == "06:20:00" || "12:20:00" || "14:20:00" || "13:48:00"))
    //waterNowrun();
    /*
      Blynk.virtualWrite(V10, 0);
      digitalWrite(14, LOW);
      Blynk.virtualWrite(V5, 0);
      Blynk.virtualWrite(V8, 0);
      Blynk.syncAll();
    */
  }
}

Don't do lcdI2C.clear(); on each loop. Just overwrite the existing contents. Then it does not flicker.

@PMF I just tried that, now the LCD is frozen

Frozen? As in: "Shows nothing at all"? I don't exactly know what kind of LCD library you use there, but it might be necessary to call the clear() once at startup.

@PMF Shows the information it should show, but does not update

You might need to do a lcdI2C.setCursor(0, 0); where the clear() was, to ensure you start at the top left with updating the lcd.

Now it works...  but there's another small problem- now if I physically disturb the LCD, it displays random characters.
Not a major issue, just want to know why.

I've seen LCDs behave unpredictably with bad cabling or a bad power source. So if moving the LCD causes contact problems, then this could be the cause. Make sure all cables are seated properly.

Alright, I did some digging around and found out it was due to high CPU frequency, case closed

one proposal. Give a good description about the problem you found. The solution you used. Answer your own question. It will be helpful for someone later.

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


text:
ESP12F works indefinitely, then gets stuck in unrecoverable hardware WDT "boot loop"?
I have a sketch running on a number of ESP12F modules (AiThinker). They can work for months on end, can be power cycled, can be moved around, etc. It is a complex sketch with multiple parts and is still using the 2.4.2 core.
What I've seen happen on an increasing number of these is that the modules can get stuck in some kind of boot loop, that I am suspecting is the hardware watchdog kicking in.
On resetting a faulty device the following is printed to the debug port at 74880:
ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

I think this equates to:

External pin reset or wake up from deep sleep
Booting from flash
SDIO High Speed V2 IO / UART1 (I have no been able to find any explaination to what this actually means, and many posts reccomend essentially ignoring!)

About 1.5 seconds later, the following is printed at 74880:
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

The only difference here I think is that (3, 7) has changed to (3,6) which equatest to:

SDIO Low Speed V1 IO / UART1 (again, no idea what this means)

After this, every 5.5 seconds (roughly) the following is printed, this time at 115200:
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

This is the same ouput as before, just output at a different baud rate.
This boot loop will continue indefinitely (I left one in this state for days to see if anything happened). Power cycling it just takes it back to the first debug messages, then just sits back in the boot loop.
No serial output from my actual sketch is ever seen. This, along with the 5.5ish second loop leads me to think that the hardware watchdog is triggering and not even allowing my sketch to run. Does that sound right?
This currently seems to be affecting around 5 out of 50 devices. Most are happily running along without a care. The affected devices can be reflashed, seemingly successfully, and will run as they should, but after about 5-10 power cycles they fall back into this loop. It's like the hardware has been permanently damaged and can never be relied on again!
Has anyone seen this behaviour before? What are people's opinions on what might have caused this? Can bad code permanently corrupt the hardware in the way I think I am seeing?


text:
can we use TCRT5000 sensor instead of IR proximity sensor?
I am planning to make a human following robot which requires two IR proximity sensors.
I already have two TCRT5000 sensor. Can I use it instead of it?

your question is like I am baking an apple cake that requires two apples. I already have two yellow apples. Can I use them instead?

I meant is TCRT5000 different from regular ir proximity sensor?

what's a regular IR proximity sensor?

https://www.amazon.in/VEEROBOT-Infrared-Proximity-Obstacle-Detecting/dp/B0115NCT4U/ref=asc_df_B0115NCT4U/?tag=googleshopdes-21&linkCode=df0&hvadid=397008884140&hvpos=&hvnetw=g&hvrand=11247381740971132298&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9297848&hvtargid=pla-391398992335&psc=1&ext_vrnc=hi

your question is off topic here because it is not about the arduino ... it is also vague, and is not answerable until you provide some operational requirements, such as detection distance

An IR distance sensor is mainly an IR LED and an IR phototransistor.  Thats what the TCRT5000 is. Though the ready to use boards incorporate more electronics to output an analog voltage according  to the signal (rough measurement of distance) and a digital output using a threshold (controllable via the potentiometer). If you use the TCRT5000 you might need to add more electronics to actually get the desired results. Most likely you would need an amp circuit to get a good signal to measure


text:
Making tmrpcm.play("1.wav") depend on LDR feedback?
I have the speaker working with the tmrpcm.play working, but this only plays when the arduino is powered up or reset. Can i make the .wav play in anther other ways?
I wan't the file to play when i open a closet and my LDR resistor is affected by light.
#include <SD.h>                           //include SD module library
#include <TMRpcm.h>                       //include speaker control library

#define SD_ChipSelectPin 4                //define CS pin

TMRpcm tmrpcm;                            //crete an object for speaker library

const int ledPin = 8;
const int buzzerPin = 10;
const int ldrPin = A0;
int ledState = LOW;
int buzstate = 600;
unsigned long previousMillis = 0;

int ldrStatus = analogRead(ldrPin);  //read the state of the LDR value

const long interval = 400;

void setup () {

  tmrpcm.speakerPin = 9;
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(ldrPin, INPUT);

 }
void LedAndBuzzer(){
   unsigned long currentMillis = millis();
  int ldrStatus = analogRead(ldrPin);  //read the state of the LDR value

 if (ldrStatus >= 400) {

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
    digitalWrite(buzzerPin, ledState);
}}
}
void soundon(){
    if (!SD.begin(SD_ChipSelectPin)) {      //see if the card is present and can be initialized

    return;                               //don't do anything more if not
  }
  else {
  tmrpcm.setVolume(6);                    //0 to 7. Set volume level
  tmrpcm.play("4.wav"); }
}

void loop() {

  }

Yes, that is totally possible. You need to write the code for it. What have you tried so far? Do you know how to read an LDR? Have you searched for tutorials?

@chrisl thanks for the respons, yes i have googled a lot, but im quite new to programming and working with the arduino. This is the code (updated the post) that in working on right know.
There is one more element than my original question, i want it to start the led/buzzer loop at the same time as the .wav file is played. Is this posible?

Is tmrpcm.play() a blocking function?

@Fahad i don't know what that means

You said i want it to start the led/buzzer loop at the same time as the .wav file is played. So I was wondering when you call tmrpcm.play() function does it return immediately or does it return after it finishes playing the wave file.

@Fahad tmrpcm.play() is non blocking. It starts playing then tmrpcm.stopPlayback() stops the music and tmrpcm.isPlaying() return the state of the player.

@Dorian great, thanks. @Elisabot, so you want to play the wav file when your LDR is >= 400 and stop the music when less?


text:
Trouble initializing a struct array
The goal for this is to create a struct that includes a name, ID, fileName, and a boolean, then create an array of that structs.
Here's what I came up with:
struct Amiibo
{
  char *aName{};
  char *ID{};
  char *AudioFileName{};
  bool alreadyPlayed{false};
};

Amiibo amii[20] = {

      {"Mario","A5005B00","MARIO",false},                     //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19

};

This gives me the following error:

error: could not convert '{"Mario", "A5005B00", "MARIO", false}' from '' to 'Amiibo'

And the same error for all the other elements of the array.
I tried changing amii[20] to a pointer using *amii[20]. That got me this error:

braces around scalar intializer for type "Amiibo"

I'm not sure what to make of that, since I'm fairly certain this isn't scalar type.
I'd really just like to make a struct array so I can cycle through these at random using a random seed. It shouldn't be that difficult, yet I'm running up against a wall. I'd appreciate any advice you all have to give. Thanks.

If you use default values, you can't use this type of initialization, you have to have proper constructor(s) to get it working. However it'll tricky with that C-strings

Would you mind giving an example of a proper constructor?

struct Amiibo { ... Amiibo(const char* name, const char* id, const char * audio) : aName{ name }, ID{ id }, AudioFileName{ audio } { ; } and another one with 4 parameters... (btw you have to change internal types to const char * too, otherwise it'll yell about discarding qualifier)

Simply omit the default values?!

If you use default values in struct declaration, you have to define also constructors for setting specific elements:
struct Amiibo
{
  const char *aName{};
  const char *ID{};
  const char *AudioFileName{};
  bool alreadyPlayed{false};

  Amiibo() = default;  // default implementation for default constructor

  Amiibo(const char* name, const char* id, const char * audio)  // constructor with three c strings as parameters
  : aName{ name }
  , ID{ id }
  , AudioFileName{ audio }
  { ; }
};

Amiibo amii[] = {
      {"Mario","A5005B00","MARIO"},                           //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19
};

Btw on the older AVRs all those strings will resides also in memory

Thanks a bunch. I may end up just using a switch or something to avoid memory issues.


text:
Project doesn't work after 2 - 3 times, requires frequent turning off and on
I am new to Arduino and I am working on a project. This project inspired me and I tried doing it.
The following code was provided in the description:
int maxPeople = 5; // maximum number of people allowed before the alarm goes off
int sensitivity = 5; //lower values will make it more sensitive and higher values will make it less
sensitive
//---------------------------------------------------

#include <TM1637.h>

int currentPeople = 0;

int buzzer = 8;

TM1637 tm(2,3);

int sensor1[] = {4,5};
int sensor2[] = {6,7};
int sensor1Initial;
int sensor2Initial;

String sequence = "";

int timeoutCounter = 0;

void setup() {
  //Setup code
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  tm.init();
  tm.set(2);

  delay(500);
  sensor1Initial = measureDistance(sensor1);
  sensor2Initial = measureDistance(sensor2);
}

void loop() {
  //Read ultrasonic sensors
  int sensor1Val = measureDistance(sensor1);
  int sensor2Val = measureDistance(sensor2);

  //Process the data
  if(sensor1Val < sensor1Initial - 30 && sequence.charAt(0) != '1'){
    sequence += "1";
  }else if(sensor2Val < sensor2Initial - 30 && sequence.charAt(0) != '2'){
    sequence += "2";
  }

  if(sequence.equals("12")){
    currentPeople++;
    sequence="";
    delay(550);
  }else if(sequence.equals("21") && currentPeople > 0){
    currentPeople--;
    sequence="";
    delay(550);
  }

  //Resets the sequence if it is invalid or timeouts
  if(sequence.length() > 2 || sequence.equals("11") || sequence.equals("22") || timeoutCounter > 200)
 {
    sequence="";
  }

  if(sequence.length() == 1){ //
    timeoutCounter++;
  }else{
    timeoutCounter=0;
  }

  //Print values to serial
  Serial.print("Seq: ");
  Serial.print(sequence);
  Serial.print(" S1: ");
  Serial.print(sensor1Val);
  Serial.print(" S2: ");
  Serial.println(sensor2Val);

  //Display current people count on 4-digit display
  tm.display(3, currentPeople % 10);
  int pos2 = currentPeople / 10;
  tm.display(2, pos2 % 10);
  int pos1 = pos2 / 10;
  tm.display(1, pos1 % 10);
  int pos0 = pos1 / 10;
  tm.display(0, pos0 % 10);

  //If the number of people is too high, trigger the buzzer
  if(currentPeople > maxPeople){
    tone(buzzer, 1700);
  }else{
    noTone(buzzer);
  }
}

//Returns the distance of the ultrasonic sensor that is passed in
//a[0] = echo, a[1] = trig
int measureDistance(int a[]) {
  pinMode(a[1], OUTPUT);
  digitalWrite(a[1], LOW);
  delayMicroseconds(2);
  digitalWrite(a[1], HIGH);
  delayMicroseconds(10);
  digitalWrite(a[1], LOW);
  pinMode(a[0], INPUT);
  long duration = pulseIn(a[0], HIGH, 100000);
  return duration / 29 / 2;
}

The required libraries are installed. I uploaded this on my Arduino nano and it worked fine. I varied the maxPeople and checked, then too it worked correctly. The third I made objects enter and leave the room by crossing the ultrasonic sensors. It seemed to work correctly, the maximum count (maxPeople) got reached and the buzzer went on. Then I made the object leave the room. Instead of decreasing the number in the display (TM1637 4 digit display) kept on increasing.
Then I turned the USB source OFF and tried again. Again it worked correctly once or twice and the same problem persists.
Sometimes even before the max count is reached, while making an object leave, the count gets increased. And sometimes the count in the display stays still at 0000 or oscillate between '''0000''' and '''0001'''.
(I thought it may be a fault in the Arduino or the ultrasonic sensor or the display, but I checked them with other open-source programs, they worked fine.)
I also tried allocating different pins to the buzzer, sensors and display, still the problem persists.
The declared integer sensitivity is never used in the code. Someone has commented. I tried that too, even then it doesn't work properly.
Is there any mistake in the code that causes this problem or something else?  I am stuck on this since last week.
Any help is appreciated.

Edit:
As per @Michel's comment, I tried to change the strings into character arrays.
int maxPeople = 5; // maximum number of people allowed before the alarm goes off
int sensitivity = 5; //lower values will make it more sensitive and higher values will make it less sensitive
//---------------------------------------------------

#include <TM1637.h>

int currentPeople = 0;

int buzzer = 8;

TM1637 tm(2, 3);

int sensor1[] = {4, 5};
int sensor2[] = {6, 7};
int sensor1Initial;
int sensor2Initial;

char sequence[2];

int timeoutCounter = 0;

void setup() {
  //Setup code
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  tm.init();
  tm.set(2);

  delay(500);
  sensor1Initial = measureDistance(sensor1);
  sensor2Initial = measureDistance(sensor2);
}

void loop() {
  //Read ultrasonic sensors
  int sensor1Val = measureDistance(sensor1);
  int sensor2Val = measureDistance(sensor2);

  //Process the data
  if (sensor1Val < sensor1Initial - 30 && sequence[0] != '1') {
    strcat(sequence, "1");
  } else if (sensor2Val < sensor2Initial - 30 && sequence[0] != '2') {
    strcat(sequence, "2");
  }

  if (strcmp(sequence, "12") == 0) {
    currentPeople++;
    sequence[0] = '\0';
    sequence[1] = '\0';
    delay(550);
  } else if (strcmp(sequence, "21") == 0 && currentPeople > 0) {
    currentPeople--;
    sequence[0] = '\0';
    sequence[1] = '\0';
    delay(550);
  }

  //Resets the sequence if it is invalid or timeouts
  if (strlen(sequence) > 2 || strcmp(sequence, "11") == 0 || strcmp(sequence, "22") == 0 || timeoutCounter > 200) {
    sequence[0] = '\0';
    sequence[1] = '\0';

  }

  if (strlen(sequence) == 1) { //
    timeoutCounter++;
  } else {
    timeoutCounter = 0;
  }

  //Print values to serial
  Serial.print("Seq: ");
  Serial.print(sequence);
  Serial.print(" S1: ");
  Serial.print(sensor1Val);
  Serial.print(" S2: ");
  Serial.println(sensor2Val);

  //Display current people count on 4-digit display
  tm.display(3, currentPeople % 10);
  int pos2 = currentPeople / 10;
  tm.display(2, pos2 % 10);
  int pos1 = pos2 / 10;
  tm.display(1, pos1 % 10);
  int pos0 = pos1 / 10;
  tm.display(0, pos0 % 10);

  //If the number of people is too high, trigger the buzzer
  if (currentPeople > maxPeople) {
    tone(buzzer, 1700);
  } else {
    noTone(buzzer);
  }
}

//Returns the distance of the ultrasonic sensor that is passed in
//a[0] = echo, a[1] = trig
int measureDistance(int a[]) {
  pinMode(a[1], OUTPUT);
  digitalWrite(a[1], LOW);
  delayMicroseconds(2);
  digitalWrite(a[1], HIGH);
  delayMicroseconds(10);
  digitalWrite(a[1], LOW);
  pinMode(a[0], INPUT);
  long duration = pulseIn(a[0], HIGH, 100000);
  return duration / 29 / 2;
}

Is there any mistake in this? On uploading this code, the display stops at '0001' and doesn't work further.

It might be worthwhile to get rid of the String type and use a fixed character array. Because of dynamic memory allocation to String you  might get memory gaps, and eventually running out of memory.

@MichelKeijzers Thank you! I just came to know about character arrays. I'll try that and update.

You will need to change quite some things, like defining a constant for the MAX array size, and use functions strcat, strln and strcmp instead of adding, checking the size and comparing.

When using C strings, you have also to keep one \0 for the end symbol, so to store "01", you need 3 bytes., otherwise the strlen/strcmp will not work.

Also I think that with - 30 you want to convert '0' to 0, but then you need to use 0x30 (hex), which is '0', or better: use '0' directlly (with a cast if needed)

Try using 0x30 instead of 30 (assuming you want to convert '0' to 0 (the character zero to the number 0)

@MichelKeijzers Thank you so much for all your help. It works pretty well now. However if someone is moved out (not possible in real, as the minimum count = 0) when the current people = 0, it gets stuck at 0000 and doesn't sense anything further. Can I add something like,
if (currentPeople < 0 ) continue;
in the code? It's not possible to use continue in loops, is there anything similar that can be used?
Kindly post all your comments as an answer, so that I could accept that.

You can use the statement, I'm not sure if it will do what you want but it's a valid statement syntactically wise.
Also, you can probably skip all sequence[1] = '\0'; statements. When the first element is 0, a string is considered to end there and e.g. strcmp does not check further.


text:
How to send a message to my phone that my Arduino system is on when turning on my Arduino
i have installed a GSM shield on the Arduino to create security alarm system using PIR SENSOR when ever there motion I will receive a call to my phone.
but i want to add also a line of code which can make my system send me a txt message stating that my system is turned on so i can make sure that when ever i turn my system on i can doule check by getting a message that says that system is turned on successfully
i dont know how to start doing that.
this is the code i did:
int PIR = 6;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(96000);
 pinMode (PIR , INPUT );
}

void loop() {
  // put your main code here, to run repeatedly:
if (digitalRead (PIR == HIGH)){
  Serial.println("thief detected");
  delay (200);
  Serial.println ("ATD+0197263315;");
  delay(1000);
  Serial.println("ATH");
  delay(1000);

  }
  else digitalWrite (PIR, LOW );

}

if (digitalRead (PIR == HIGH)) is not doing what you think it does.  Look at where your parenthesis are.

can explain more

PIR == HIGH is false, because PIR is 6 and HIGH is 1.  You have digitalRead(false).  digitalRead takes type int.  Converted to int, false is 0.  You have effectively digitalRead(0).

You can send an SMS using the Arduino GSM library. Here is a bare bones sketch that sends one pre-set SMS when it starts up, based on this tutorial:
#include <GSM.h>

#define PINNUMBER "1234"
#define REMOTENUMBER "07123456789"
#define TXTMESSAGE "System started!"

GSM gsmAccess;
GSM_SMS sms;

void setup() {
  boolean notConnected = true;

  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      delay(1000);
    }
  }

  sms.beginSMS(REMOTENUM);
  sms.print(TXTMESSAGE);
  sms.endSMS();
}

void loop() {
}

If you can't or don't want to use the GSM library, it should also be possible to send an SMS by using the SoftwareSerial library to control your GSM shield using AT codes. Here's a tutorial on this approach, which is lighter weight but might be more fiddly to get working, especially if you need a PIN for your SIM card.


text:
Check pin capabilities at compile time
Are there board-independent functions to check pin capabilities at compile time? I.e.

Can the pin be used as output, as in digitalWrite()?
Does the pin support PWM, as in analogWrite()?
Does the pin support ADC, as in analogRead()?
Does the pin support interrupts, as in attachInterrupt()?

I'm looking for functions/macros like e.g. isDigitalOutput(pin) which would return false for input-only pins such as A6 and A7 on a 328P, but true on a Mega where those pins are input/output.

I'm afraid not, Its best to look up documentation or schematics for the board, if you would like to do it by yourself, you can set any pin to any of the states and test whether it works properly, and take some notes

@Coder9390 I wanted to do a check in a library function which requires an analog pin, but I think I'll just drop the idea. No way I'm going to look up every analog pin on every possible board.

maybe a check for a definition of A0 would work

Firmata contains a large list of pin definitions for boards. The official version https://github.com/firmata/ConfigurableFirmata/blob/master/src/utility/Boards.h is a bit outdated, but the most common Arduinos are included

https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/variants/mega/pins_arduino.h#L27

For compatibility with analogWrite() there's digitalPinHasPWM(p) macro which returns 1 when PWM is supported on pin p.
For analogRead() there's analogInputToDigitalPin() which can be used as
#if ((p-PIN_A0 < 0) || (analogInputToDigitalPin(p-PIN_A0) != p))
#error Not an analog pin!
#endif

For attachInterrupt() there is digitalPinToInterrupt(p) which returns NOT_AN_INTERRUPT if the pin p doesn't support interrupts.
I still haven't found anything to test compatibility with digitalWrite().

you asked about compile time

@Juraj Right, A0 is not a macro (PIN_A0 must be used instead).

but the answer is about runtime

@Juraj No, all of the above checks are macros.

sorry, I see. after edit it is a macro


text:
Can I add my Wi-Fi credentials to ESP module remotely?
I am working on Home automation project and I am stuck somewhere on connecting my smart switch board to internet through my home WIFI. Actually I want to connect my ESP module with my home Wi-Fi remotely.
I was think of something like creating a hotspot through my switch board and connecting the hotspot to my phone, after that I need to send my Wi-Fi credential through that hotspot from my phone to  to ESP. But I dont know actually how to implement it. I didn't find something similar like that so I came here.
If you guys have some different way or you know how to do it , then give me some information about it.

https://github.com/tzapu/WiFiManager


text:
Delay coding not working as expected
Added second attempt at bottom of code, Please check it, works with out lag time but never turns Vacuum off?  This project is pretty well explained in the code description. My main problem is I need a delay for ditialWrite(vacPin,LOW);.  With this part included the stepper doesn't react a quickly as before 2/3 sec lag, & the ACS712 current sensor does not read at all in the console screen.
I have tried different operatives, statements, and relocating the code in different spots with no luck!
I think this has a simple fix, but it has alluded me!. Hope this is clear enough, any help would be appreciated.
/*This version works as is **EXCEPT** the Delay vac 4 sec has to be turned off. See ########### area for Problem.
/*Auto Blast gate project:  for dust collection in wood shop.
  Arduino Nano
  ACS712 current sensor
  DRV8825 stepper driver
  Nema 17 stepper
  Each tool will be monitor by a current sensor and when that analog port exceeds a given threshold
  1. Rotate the stepper to a predetermined position to align ports for that tool.
  2. After the gate is align a digital pin will drive relay to turn on Vacuum system.
      Vacuum will stay on as long as sensor exceed the threshold while tool is running.
      **When tool stops vacuum will continue for 4 seconds to clear remaining dust.**
  3. If the same tool is used next, the Stepper will remain in it's current position.
      But the vacuum system should still operate the same.
  4.  currently using buttons to simulate tools and also one ACS712 for testing  */

// defines pins numbers
const int stepPin = 3;
const int dirPin  = 2;
const int enPin  = 8;
const int vacPin = 4; //simulate Vacuum relay

int ca = 0;  //currentAngle
int na = 0;  //angle
int stepPerAngle = 5 / 9; // full step = 1.8 or could have used "*1.8"
int   numstep;
int analogValue = 0;

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

  // Sets the 3 pins as Outputs
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(enPin, OUTPUT);
  pinMode(vacPin, OUTPUT); //Just added this for vac

  //set values for 2 outputs
  digitalWrite(enPin, LOW);
  digitalWrite(dirPin, HIGH);
  digitalWrite(vacPin, LOW); //just add this for vac

}

void loop() {
  int n;
 analogValue = 0;

  // Assign button degrees
  if      ( analogRead(A0) > 600) {
    analogValue = (analogRead(A0));
    Serial.print("AO = ");
    Serial.println(analogValue);
    na = 0;

  }
  else if ( analogRead(A1) > 600) {
    analogValue = (analogRead(A1));
    Serial.print("A1 = ");
    Serial.println(analogValue);
    na = 45;
  }

  else if ( analogRead(A2) > 600) {
    analogValue = (analogRead(A2));
    Serial.print("A2 = ");
    Serial.println(analogValue);
    na = 225;
  }

  else if ( analogRead(A3) > 600) {   //=tool on
  analogValue = (analogRead(A3));
    Serial.print("A3 = ");
    Serial.println(analogValue);
    na = 270;

  }

 /*###########################################################
 **this is where I need help.  The first if statement works as it should.
 when those 2 condition are met the vacPin goes high.** */

  if(analogValue > 600 && ca==na) {
    digitalWrite(vacPin, HIGH);
  }

/* **this part is not working correctly.  If the delay is remove it works as the "else if" statment reads.
  I need the delay so when a tool is stopped, the vacuum continues for a few secounds to clear remaining saw dust** */

else if (analogValue < 600) {
   delay (4000); **/*  with this on:
             the stepper does not start as quickly as before,
             the analog will not read the ACS712 sensor at all,  only the buttons*/**
    digitalWrite(vacPin, LOW);
  }

//################################################################################

  if ( ca != na ) {

  //2nd SCENARIO
  if (na - ca > 0 && na - ca <= 180)
    { digitalWrite(dirPin, HIGH);
      n = ((na - ca) * 5 / 9);
      numstep = n;
      ca = na;

    }

    //3rd SCENARIO
    else if (ca - na > 0 && ca - na > 180)
    { digitalWrite(dirPin, HIGH);
      n = ((na + 360 - ca) * 5 / 9);
      numstep = n;
      ca = na;
    }

    // 4th SCENARIO
    else if (na - ca < 0 && na - ca <= 180)
    { digitalWrite(dirPin, LOW);
      n = ((ca - na) * 5 / 9);
      numstep = n;
      ca = na;
    }

    //5th SCENARIO
    else if (na - ca > 0 && na - ca > 180)
    { digitalWrite(dirPin, LOW);
      n = ((ca + 360 - na) * 5 / 9);
      numstep = n;
      ca = na;
  }

    for (int x = 0; x < numstep; x++) {

      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);  //speed
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);

    }

    delay(200);
  }

}

#################################################
if(analogValue > 600 && ca==na) {
    digitalWrite(vacPin, HIGH);
  }

/* this part is not working correctly.  If the delay is remove it works as the "else if" statment reads.
  I need the delay so when a tool is stopped, the vacuum continues for a few secounds to clear remaining saw dust */

// another variation to the section in question
else if (analogValue < 600 && vacPin==HIGH) {
   delay (4000);
/*  written this way it works but never turn Vacuum off?*/
    digitalWrite(vacPin, LOW);
  }

Thanks for your reply,  I rewrote another way  if(analogValue > 600 && ca==na) {
digitalWrite(vacPin, HIGH);
}
/* this part is not working correctly.  If the delay is remove it works as the "else if" statment reads.
I need the delay so when a tool is stopped, the vacuum continues for a few secounds to clear remaining saw dust */
else if (analogValue < 600 && vacPin==HIGH) {
delay (4000); /*  written this way it works but never turn Vacuum off?*/
digitalWrite(vacPin, LOW);
}   This way works but never turns vacuum off after its on?

// another variation to the section in question
else if (analogValue < 600 && vacPin==HIGH) {
delay (4000); /*  written this way it works but never turn Vacuum off?*/
digitalWrite(vacPin, LOW);
}

Sorry again! I did read your comments and have no idea why part of my reply didn't show up and the rest doesn't show the way it looked when entered.  I'm interested in your input but afraid to try again in a reply.  What I learning is I need to go to a nonblocking delay.

then I'll say it again ... please, do not put code into comments ... add code, and any new info, to your post

I guess I'm a slow learner, I finally get what your telling me about the code (not in comments) I thought you were telling me not to put comments in the code! At this point I can't find your original question.  Learning this system is about as hard as the coding itself "for me".  Thanks for you patience.

It's not exactly clear what you're trying to do, but I think you want to start the vac and start the stepper, then 4 seconds later stop the vac. The 4 second delay forces the rest of your code to wait (doing nothing) during the 4 seconds.
Look at the Arduino IDE example program, BlinkWithoutDelay. The technique used there is what you need to use instead of delays, to allow your program to manage multiple things at once. This technique is called non-blocking; any time part of your program waits for something to happen blocks the code from doing anything else until that 'something' completes.
Search for non-blocking programming to read more. There are plenty of articles on the web, including in Arduino Stack Exchange that discuss that.
Update (following your 2021-05-05, 20:48Z update):
Here is an answer I wrote to similar question in which I wrote about non-blocking programming in more detail. The short answer is that you can't use delay() when you need to monitor or control several things simultaneously. Delays keep anything else from happening until they expire which is what is keeping your stepper from advancing as you intended. You need to do something like:
if the tool is running,
  ; // do nothing
else,
  save the time;    // this is the tool-stopped time
  move the stepper; // I assume the stepper completes in < 4s
end

if the tool is stopped and the vac is running,
  if (current_time - saved_time) >= 4000,
    stop the vac;
  end;
end;
// and let loop() keep running

Notice that this never waits for the tool or the fan. It just checks quickly and often, whether something needs to be done; if so, it does it; and in any case it continues on.
Because this is in your loop function, this code runs over and over again, so eventually, when 4 seconds has passed (in the case of the vac), the vac will get stopped, but meanwhile, the stepper has been able to run and any other small tasks needing doing will have an opportunity. The important point is, your code never hangs around waiting for anything to happen; it just very rapidly checks everything that could need to be {started, stopped, accelerated, ...}, if/when something is ready to be done, it does it, but it moves on immediately, in either case.

Thanks,  I will read up on that,    Your interpretation of what it does is close. When tool detected, move the stepper to position, turn on vacuum, when tool is turn off, vacuum remains on for 4 sec.   Thanks again I'll check it out.

https://www.instructables.com/Simple-Multi-tasking-in-Arduino-on-Any-Board/

That instructables presents the same ides, now structured in a nicer way. Note the important point: Each task gets many, frequent opportunities to execute. They decide whether or not they need to use any one of those opportunities, but they never wait. "Do or not do; there is no wait" to paraphrase Yoda.

I don’t know where to start but, this worked PERFECTLY! I need to work on stepper speed and ramp Length to smooth out, or jumpers on the DRV8825 expansion bd. Other than that, I want to understand the library! I went to the readme and it explained the thing it can do, but I don’t know how to utilize on my own. I noticed your name and written by are the same! Am I talking to a person or a company? Thanks again
Thanks for everyone else that help as well and I need to study some of those solutions as well!
MicroBahner
May 8
This would be my suggestion with MobaTools:
/*This version works as is EXCEPT the Delay vac 4 sec has to be turned off. See ########### area for Problem.
Auto Blast gate project:  for dust collection in wood shop.
Arduino Nano
ACS712 current sensor
DRV8825 stepper driver
Nema 17 stepper
Each tool will be monitor by a current sensor and when that analog port exceeds a given threshold

Rotate the stepper to a predetermined position to align ports for that tool.
After the gate is align a digital pin will drive relay to turn on Vacuum system.
Vacuum will stay on as long as sensor exceed the threshold while tool is running.
When tool stops vacuum will continue for 4 seconds to clear remaining dust.
If the same tool is used next, the Stepper will remain in it's current position.
But the vacuum system should still operate the same.
currently using buttons to simulate tools and also one ACS712 for testing
*/
// suggestion with MobaTools for driving the stepper and timer fuction
#include <MobaTools.h>

// defines pins numbers
const int stepPin = 3;
const int dirPin  = 2;
const int enPin  = 8;
const int vacPin = 4; //simulate Vacuum relay
const int stepPer360Degree = 200; // Number of steps for one revolution ( adjust to your needs )
MoToStepper stepper ( stepPer360Degree, STEPDIR );
MoToTimer vacTimer; // for delayed switch off
const long runOnTime = 4000;
int na = 0;  //angle
int analogValue = 0;
void setup() {
Serial.begin(9600);
// Setup the stepper
stepper.attach( stepPin, dirPin );
stepper.setSpeedSteps( 1000, 20 ); // sets Speed and ramplength
stepper.attachEnable( enPin, 100, LOW ); // Disable after 100ms. enabled is LOW
pinMode(vacPin, OUTPUT); //Just added this for vac
//set values for 2 outputs
digitalWrite(vacPin, LOW); //just add this for vac
}
void loop() {
analogValue = 0;
// Assign button degrees
if      ( analogRead(A0) > 600) {
analogValue = (analogRead(A0));
Serial.print("AO = ");
Serial.println(analogValue);
na = 0;
}
else if ( analogRead(A1) > 600) {
analogValue = (analogRead(A1));
Serial.print("A1 = ");
Serial.println(analogValue);
na = 45;
}
else if ( analogRead(A2) > 600) {
analogValue = (analogRead(A2));
Serial.print("A2 = ");
Serial.println(analogValue);
na = 225;
}
else if ( analogRead(A3) > 600) {   //=tool on
analogValue = (analogRead(A3));
Serial.print("A3 = ");
Serial.println(analogValue);
na = 270;
}
// position stepper if needed
if ( stepper.read() != na ) stepper.write( na );
// start vac if tool is on and stepper is in position
if (analogValue > 600 && !stepper.moving()) {
digitalWrite(vacPin, HIGH);
}
if ( vacTimer.expired() ) {
// switch off vac if timer expires
Serial.println( "Vac = off");
digitalWrite(vacPin, LOW);
}
if (analogValue < 600 && digitalRead( vacPin ) && !vacTimer.running()) {
// start timer to switch off vac after time
Serial.println( " start vac run-on-time" );
vacTimer.setTime( runOnTime );
}
}
If you want to give it a try, the library can be installed by means of the library manager ( enter mobatools in the search field )


text:
Arduino UNO R3 not detected by Arduino Create Agent
So I just got my Arduino Uno R3 and tried to use it with Arduino Web IDE. I installed (and reinstalled) Arduino Create Agent and was expecting it autodetect my board, but it did not happen. Below is a picture of my board link. One light is solid and the other is flashing. In device manager I see USB serial with exclamation mark. Do I need to installed any drivers? This page says that I do not need to:
getting started
Any thoughts?
P.S. I also openned debug console, but there is nothing useful, it keeps scrolling: Network Port and Serial Port.
P.P.S. I tried two different USB cables, still no luck
P.P.P.S. I installed desktop IDE, selected Arduino Uno and tried to upload, but got back error message:
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

Serial port not selected.

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

In device manager I see USB serial with exclamation mark ... what does the exclamation mark mean?

Install driver for the CH340 USB chip on your Uno

I never used the Web IDE, but can you find a "Serial port" setting anywhere? The message Serial port not selected indicates that it does not know which port to use. Since you could have connected more than one Arduino, you have to tell it which serial port it should use (typically COM3 or COM4)

@PMF How can I tell it which port to use?

@Juraj Thank you, but how can I install it on Uno if I cannot connect it to computer?

@user1700890 If the port is visible in device manager, it is shown there. You should see something like "USB Serial CH340 (COM4)".

Thank you, All! Indeed, it looks like I need to install CH340 USB driver on my Windows 10. I tried my Arduino with Ubuntu and it worked almost perfectly. Too bad Windows comes without this driver.


text:
Can internal and external pull up/pull down resisters be used together?
What happens if a sketch uses code like pinMode(18,INPUT_PULLDOWN) to configure internal pull-down (or pull-up) resistors, but is used in a circuit where external resistors are also present?
Are there likely to be any problems, conflicts or unexpected behaviour, e.g. if software sets a pull-down, but there is an external pull-up, or visa versa?
I am using an ESP32 (which has both internal pull-ups and pull-downs available on most GPIO pins), but I would appreciate a general answer. To clarify, I am not after the pros and cons of using external resistors (which is discussed in other questions), but the potential pitfalls of using both, especially if they are pulling in opposite directions.

The main risk if you use both internal and external pullup/down resistors working in opposite directions is that the input will be left at an intermediate voltage that is not guaranteed to be read as high or low. Furthermore a little noise on the input might flip a read from high to low or vice versa. There is no risk of damaging the input however

It is dependent on the value of the resistors. The "resistors" in microprocessors are generally of a high value and have a large value tolerance. Sometimes it is desirable to hold a pin in a specific state until the system initializes it to possibly a different state.

It is actually beneficial for the chip to have an additional pull-up or pull-down. It can help to reduce noise and to protect from ESD on the pin coming in. The internal resistors can only take a very small amount of current and an external can take some of the current in case an ESD event is happening.
The downsides of an external resistor are (not complete list):

space requirements
cost (although very low cost)
slightly increased power consumption

If these are not a problem for you, an external resistor is a good idea.
Here is a video (not me), that explains the ESD-part it in more detail.
EDIT:
I just re-read your question and saw that you asked about mixing pull-up and pull-down. That you should normally not do as jksemple said.

When you add the external resistor it will be connected to the internal pull resistor (up or down) depending on configuration. The pull resistor will either be series or parallel with the external resistor. In series it will behave as a voltage divider, in parallel it will increase the current required to cause the pin to change state. Mixing will not harm the computer as the pull resistor is designed to be connected to the opposite polarity externally. With the data sheet and the value of your resistor you can calculate the current and or voltage. You do not want to use external pull up and pull down resistors on the same pin. It may work but it is best to do the calculations to see if it will give you a viable value.

pinMode(18,INPUT_PULLDOWN) ? There is no such thing! you use a resistor for that. only pullup internal available_

it is. some Arduino platforms use MCU with internal pulldown


text:
Is my BMA421 locked up?
I have been trying to set up the BMA421 motion sensor in a nrf52 based smart watch, using the datasheet for the BMA423, which has the same interface. I had got the sensor working well with the original source code, but I was trying to set it up myself. It is connected via I2C, address 0x18.
I made some mistakes in my original code. I was trying to initialise the chip with a 6Kb byte stream (as in the original source), in chunks of 64 bytes. I didn't resend the register at the start of each data chunk, so ended up writing bytes to random registers.
Unfortunately, I have managed to get the sensor into an unrecoverable state - it now returns 0xFF to all reads, and doesn't respond to a soft-reset code (register 0x7E=0xB6). Even exhausting the watch battery to power cycle the chip doesn't seem to help.
I have found someone with a similar issue on the Borsch Sensortec forum, so I am hoping that a complete battery discharge works.
Does anyone have any other suggestions?

Are you using I2C or SPI? SPI doesn't have addresses, but every slave has a chip select pin. I2C on the other hand has addresses and no chip select pin.

Sorry, have corrected - it is I2C.

Currently my plan of action is discharge the battery and then leave for a week to see if I can reset the chip. Not optimistic.

A suggestion from another source was that I have put the device into SPI mode and disconnected it from the I2C bus - that would certainly explain the result.

good point. From the "drain battery" I guess, that the hardware is mostly integrated, so that you cannot just try connecting SPI and configuring it again over that?

That is sadly correct. This is an off the shelf smartwatch which is not amenable to being opened! Once it has been kicked off the I2C bus, there is no way back until a power cycle. I am asking here, because I have a working Arduino firmware running on it to test out peripherals. The positive is that if I have switched it into SPI mode, I am unlikely to have overwritten the NVRAM!

The BMA421 was not locked. An erroneous write to the wrong register had switched it to the (non-existant) SPI interface. The solution was to power cycle the sensor.


text:
How to connect multiple MPU-9250 IMU sensors to a single Arduino Uno?
The datasheet says the I2C bus limits itself to only two MPU-9250 sensors. How can I control multiple (>2) MPU-9250 through a single Arduino Uno? Is it possible to add another bus?
Please, help.

this has been asked mamy times ... search this website for multiple I2C

Try this one : https://forum.arduino.cc/t/two-mpu-9250-on-arduino-uno/455724

I2C is a bus, it's sole purpose is to connect multiple devices together (1 master, multiple slaves)


text:
How to make ultrasonic and light sensors detect whether a person moving in or out
I am trying to make a circuit that will be used for turning on a light whenever there are 1 or more people in a room. I need to add to a variable counter when someone enters and subtract when someone leaves. However, I do not know how to use the ultrasonic sensor for this purpose. What can I do?

Google. If you know how to use the Ultrasonic sensor and know the C++ basics, this will be very easy.

How do you find out whether the person is entering or exiting

Is there some distance change thing

You'd have to place two Sensors next door, and if both are triggered, someone got in or out. You can check whether the person went in or out by looking what Sensor was triggered first.

thanks for the help

but it will always detect some distance so I need to check if the distance is less than a certain amount

Yes, you have to expermient a little bit with it to find the best value.

Unless the person swings his hand around

Then you'd have to use a camera + Raspberry Pi.

Let us continue this discussion in chat.

See this tutorial on the Arduino Projecthub, that project was already made. Here is a tutorial how to use a Ultrasonic sensor.


text:
ESP8266 Arduino Json object array deserialisation into struct
I'm trying to de serialize an array of JSON objects into a struct.
Following the instructions given by the Arduino JSON assistant, I managed to produce this helper function:
void JsonPreprocessor(const char* buf)
{
  StaticJsonDocument<96> filter;

  JsonObject filter_ResponseData_Metros_0 = filter["ResponseData"]["Metros"].createNestedObject();
  filter_ResponseData_Metros_0["Destination"] = true;
  filter_ResponseData_Metros_0["ExpectedDateTime"] = true;
  filter_ResponseData_Metros_0["Deviations"] = true;

  StaticJsonDocument<512> doc;

  DeserializationError error = deserializeJson(doc, buf, DeserializationOption::Filter(filter));

  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  JsonArray ResponseData_Metros = doc["ResponseData"]["Metros"];
  for (int i = 0; i < MAX_ELEMENTS; i++)
  {
    strcpy(dep_arr[i].destination, ResponseData_Metros[i]["Destination"]);
    strcpy(dep_arr[i].destination, ResponseData_Metros[i]["ExpectedDateTime"]);
  }
}

The function writes into an array of structs declared like this:
struct Departure {
   char* destination;
   char* departure;
   int  deviation;
} depart;

struct Departure dep_arr[MAX_ELEMENTS];

And the JSON passed as a constant character array to the preprocessor function. Uploading and running this function keeps crashing my ESP8266 without any debug output. Without posting the whole json object, which is long enough as is without the filters, My object array in JSON looks similar to this after filtering:
{
  "ResponseData": {
    "Metros": [
      {
        "Destination": "Destination_1",
        "ExpectedDateTime": "2021-04-29T05:15:30",
        "Deviations": 1
      },
      {
        "Destination": "Destination_2",
        "ExpectedDateTime": "2021-04-29T05:21:30"
      },
      {
        "Destination": "Destination_2",
        "ExpectedDateTime": "2021-04-29T05:30:30"
      },
      {
        "Destination": "Destination_1",
        "ExpectedDateTime": "2021-04-29T05:36:30"
      },
      etc...
    ]
  }
}

In my test code I've defined my MAX_ELEMENTS macro to be 3.
I'm at a complete loss due to not having any debug output. I'm using ArduinoJson6 and my code is written and compiled on Arduino IDE 2.0.0-beta.5

No memory is allocated for the strings.
You should declare your struct like so:
struct Departure {
   char destination[32];
   char departure[32];
   int  deviation;
} depart;

This assumes the max length for both strings is 31 characters.
Then, pass the max size to strlcpy():
strlcpy(dep_arr[i].destination, ResponseData_Metros[i]["Destination"], 32);
strlcpy(dep_arr[i].destination, ResponseData_Metros[i]["ExpectedDateTime"], 32);

If your strings are very long, you can use a String instead of char[].
See the example JsonConfigFile.ino, it shows all of this.


text:
Can data be stored in program storage space instead of dynamic memory?
I'm declaring an array at top level like so:
constexpr byte a[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; // whatever data
I'm referencing the array in such a way that it's not optimized away. When compiling this from the Arduino IDE it informs me that it's using 1474 bytes of program storage space and 194 of dynamic memory. Curiously enough if my array is twice the size (20 elements) there are 10 more bytes of both program storage and dynamic memory used (1484 and 204 respectively).
Can I convince the compiler somehow to store all this in program storage space only? Any qualifiers or options I should be using instead? (and why would it take up space in both memory spaces anyway?!)
I'm using an arduino uno.

You have to use PROGMEM or newer AVRs like Atmega4809 with "flat" memory model (all different types of memories are mapped into the same memory space and accessible by the same pointers)

https://www.arduino.cc/reference/en/language/variables/utilities/progmem/

These feel like answers more than comments so if you think the same post it as such so I can accept it; progmem is not seamless but it does the job


text:
How to set 60 min beeper?
I am trying to make a device that will register latency and number of shocks for passive avoidance behavior in drosophila. My device has two buttons green and red. I press green when I put a fruit fly into the test tube. When drosophila enters the shock compartment I press the red button to give electric shock through Grass stimulator. My Arduino registers latencies or elapsed time from pressing green button and subsequent presses red button and the number of shocks (presses of the red button). This part works just fine, however, I want to have a 60 sec beeper as the test runs only 1 min. This part does not work. The beeper counts 60 seconds from the starting of the device,  not from the press of the green button.  I am not sure what I am doing wrong.
Here is the code:

#include <LiquidCrystal.h>

/*
  Super-basic stopwatch using millis();
*/

unsigned long start, finished, elapsed;
unsigned long startTime;
unsigned long endTime;
unsigned long duration;
byte timerRunning;
int switchPin = 3;              // switch is connected to pin 3
int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int buttonPresses = 0;          // how many times the button has been pressed
const int buz = 13;
unsigned long delayStart = 0; // the time the delay started
//bool timerRunning = false; // true if still waiting for delay to finish
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd (9, 8, 7, 6, 5, 4);

void setup()
{
  lcd.begin(16, 2);
  //lcd.setCursor (0,0);
  //lcd.print("resetting");
  lcd.setCursor (3,1);
  lcd.print("resseting");
  delay(3000);
  lcd.clear();
  lcd.setCursor (0,0);
  lcd.print ("Latency= ");
lcd.setCursor (0,1);
lcd.print ("Shocks= ");
  Serial.begin(9600);
  pinMode(2, INPUT); // start button
  pinMode (2, INPUT_PULLUP);
  pinMode (buz,OUTPUT);
  pinMode(switchPin, INPUT);    // Set the switch pin as input
  digitalWrite(buz, LOW); // turn buz off
  delayStart = millis();   // start delay
  //delayRunning = true; // not finished yet
  buttonState = digitalRead(switchPin);   // read the initial state
  Serial.println("Press 'Green' for Start/Reset, 'Red' for Shocks");
}

void displayResult()
{
  float h,m,s,ms;
  unsigned long over;
  elapsed=finished-start;
  h=int(elapsed/3600000);
  over=elapsed%3600000;
  m=int(over/60000);
  over=over%60000;
  s=int(over/1000);
  ms=over%1000;
  Serial.print("Elapsed time: ");
  Serial.println(elapsed);
  Serial.print("Latency: ");
  Serial.print(m,0);
  Serial.print("m ");
  Serial.print(s,0);
  Serial.print("s ");
  Serial.print(ms,0);
  Serial.println("ms");
  Serial.print("Shocks: ");
  Serial.print(buttonPresses);
  Serial.println(" time(s)");
  lcd.setCursor (8,0);
  lcd.print(m,0);
  lcd.print("m");
  lcd.print(s,0);
  lcd.print("s");
  lcd.print(ms,0);
  lcd.setCursor (7,1);
  lcd.print(buttonPresses);

}

void loop()

    {float h,m,s,ms;

  if (digitalRead(2) == HIGH);{ // button pressed & timer not running already
  start=millis();
  lcd.setCursor (7,1);
  lcd.print("           ");
  buttonPresses=0;
  lcd.print(buttonPresses);
    Serial.println("Started");
    lcd.setCursor (8,0);
    lcd.print("           ");
    lcd.print("Start...");
  lcd.print(buttonPresses);
  lcd.setCursor (8,0);
    lcd.noBlink();

  delay(300);

  // Turn on the blinking cursor:

  lcd.blink();
    delay(200); // for debounce

  }

  if (digitalRead(3)==HIGH)
  { lcd.noBlink();
  lcd.setCursor (9,0);
   lcd.print("        ");
    finished=millis();
    delay(200); // for debounce
    buttonPresses++;
    displayResult();
    delay(200);}

    if (timerRunning && ((millis() - delayStart) >= 60000)) {
    //timerRunning = false; // // prevent this code being run more then once
    digitalWrite(buz, HIGH); // turn buz on
   // tone(buz, 1000); // Send 1KHz sound signal...
  delay(1000);        // ...for 1 sec
  noTone(buz);     // Stop sound...
  delay(1000);        // ...for 1sec
    Serial.println("Turned buz on");
    lcd.setCursor (10,1);
    lcd.print("1min");
  }}

Check the blink without delay example. Set a variable when you start the test, and check against the current time (minus 60 seconds) to start the beeper.

your code is really badly formatted, which can easily lead to errors ... for example, you should not have two braces }} next to each other

The best place to start, is with the BlinkWithoutDelay example in the IDE.
Once you master that concept, you may be tempted to start several different timers. With enough timers, your code will start to look like a bowl of spaghetti.
Next, you could build a generic function which would help to reduce the "spaghetti code".
I would favour an OOP approach.
// Sketch uses 910 bytes (2%) of program storage space.
// Global variables use 18 bytes (0%) of dynamic memory.
// Arduino Uno, IDE 1.8.9
class MillisTimer{

  private:

    unsigned long m_timeInMilliSeconds;
    unsigned long m_previousMillis;
    byte m_timerActive;

  public:

    MillisTimer(unsigned long timeInMilliSeconds):
      m_timeInMilliSeconds(timeInMilliSeconds){
      m_timerActive = 0;
      m_previousMillis = 0;
    }

    bool Update(){
      if(m_timerActive && (millis() - m_previousMillis >= m_timeInMilliSeconds)){
        m_previousMillis += m_timeInMilliSeconds;
        return 1;
      }
      else{
        return 0;
      }
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_previousMillis = millis();
    }

};

// Make a copy of the object to work with.
MillisTimer SixtySecondTimer(60000);

void setup(){

  // Call this function from a button click
  // to start the 60 second timer.
  SixtySecondTimer.Start();

  // Timer complete indicator.
  pinMode(LED_BUILTIN, OUTPUT);

}

void loop(){

  // Call the update function as fast as possible.
  if(SixtySecondTimer.Update()){
    digitalWrite(LED_BUILTIN, HIGH);
    SixtySecondTimer.Stop();
  }

}


text:
Adafruit soundboard with esp32
Board: ESP32 Development Board
I am trying to get the adafruit soundboard code to work on my ESP32.  I have installed espSoftwareSerial but I keep getting errors with their sample code.
I receive
testcode:13:50: error: use of deleted function 'SoftwareSerial::SoftwareSerial(const SoftwareSerial&)'
SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);

    /*
      Menu driven control of a sound board over UART.
      Commands for playing by # or by name (full 11-char name)
      Hard reset and List files (when not playing audio)
      Vol + and - (only when not playing audio)
      Pause, unpause, quit playing (when playing audio)
      Current play time, and bytes remaining & total bytes (when playing audio)

      Connect UG to ground to have the sound board boot into UART mode
    */

    #include <SoftwareSerial.h>
    #include "Adafruit_Soundboard.h"

    // Choose any two pins that can be used with SoftwareSerial to RX & TX
    #define SFX_TX 5
    #define SFX_RX 6

    // Connect to the RST pin on the Sound Board
    #define SFX_RST 4

    // You can also monitor the ACT pin for when audio is playing!

    // we'll be using software serial
    SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);

     // pass the software serial to Adafruit_soundboard, the second
    // argument is the debug port (not used really) and the third
    // arg is the reset pin
    Adafruit_Soundboard sfx = Adafruit_Soundboard(&ss, NULL, SFX_RST);
    // can also try hardware serial with
    // Adafruit_Soundboard sfx = Adafruit_Soundboard(&Serial1, NULL, SFX_RST);

    void setup() {
      Serial.begin(115200);
      Serial.println("Adafruit Sound Board!");

      // softwareserial at 9600 baud
      ss.begin(9600);
      // can also do Serial1.begin(9600)

      if (!sfx.reset()) {
        Serial.println("Not found");
        while (1);
      }
      Serial.println("SFX board found");
    }

    void loop() {
      flushInput();

      Serial.println(F("What would you like to do?"));
      Serial.println(F("[r] - reset"));
      Serial.println(F("[+] - Vol +"));
      Serial.println(F("[-] - Vol -"));
      Serial.println(F("[L] - List files"));
      Serial.println(F("[P] - play by file name"));
      Serial.println(F("[#] - play by file number"));
      Serial.println(F("[=] - pause playing"));
      Serial.println(F("[>] - unpause playing"));
      Serial.println(F("[q] - stop playing"));
      Serial.println(F("[t] - playtime status"));
      Serial.println(F("> "));

      while (!Serial.available());
      char cmd = Serial.read();

      flushInput();

      switch (cmd) {
        case 'r': {
          if (!sfx.reset()) {
            Serial.println("Reset failed");
          }
          break;
        }

        case 'L': {
          uint8_t files = sfx.listFiles();

          Serial.println("File Listing");
          Serial.println("========================");
          Serial.println();
          Serial.print("Found "); Serial.print(files); Serial.println(" Files");
          for (uint8_t f=0; f<files; f++) {
            Serial.print(f);
            Serial.print("\tname: "); Serial.print(sfx.fileName(f));
            Serial.print("\tsize: "); Serial.println(sfx.fileSize(f));
          }
          Serial.println("========================");
          break;
        }

        case '#': {
          Serial.print("Enter track #");
          uint8_t n = readnumber();

          Serial.print("\nPlaying track #"); Serial.println(n);
          if (! sfx.playTrack((uint8_t)n) ) {
            Serial.println("Failed to play track?");
          }
          break;
        }

        case 'P': {
          Serial.print("Enter track name (full 12 character name!) >");
          char name[20];
          readline(name, 20);

          Serial.print("\nPlaying track \""); Serial.print(name); Serial.print("\"");
          if (! sfx.playTrack(name) ) {
            Serial.println("Failed to play track?");
          }
          break;
       }

       case '+': {
          Serial.println("Vol up...");
          uint16_t v;
          if (! (v = sfx.volUp()) ) {
            Serial.println("Failed to adjust");
          } else {
            Serial.print("Volume: "); Serial.println(v);
          }
          break;
       }

       case '-': {
          Serial.println("Vol down...");
          uint16_t v;
          if (! (v=sfx.volDown()) ) {
            Serial.println("Failed to adjust");
          } else {
            Serial.print("Volume: ");
            Serial.println(v);
          }
          break;
       }

       case '=': {
          Serial.println("Pausing...");
          if (! sfx.pause() ) Serial.println("Failed to pause");
          break;
       }

       case '>': {
          Serial.println("Unpausing...");
          if (! sfx.unpause() ) Serial.println("Failed to unpause");
          break;
       }

       case 'q': {
          Serial.println("Stopping...");
          if (! sfx.stop() ) Serial.println("Failed to stop");
          break;
       }

       case 't': {
          Serial.print("Track time: ");
          uint32_t current, total;
          if (! sfx.trackTime(&current, &total) ) Serial.println("Failed to query");
          Serial.print(current); Serial.println(" seconds");
          break;
       }

       case 's': {
          Serial.print("Track size (bytes remaining/total): ");
          uint32_t remain, total;
          if (! sfx.trackSize(&remain, &total) )
            Serial.println("Failed to query");
          Serial.print(remain); Serial.print("/"); Serial.println(total);
          break;
       }

      }
    }

    /************************ MENU HELPERS ***************************/

    void flushInput() {
      // Read all available serial input to flush pending data.
      uint16_t timeoutloop = 0;
      while (timeoutloop++ < 40) {
        while(ss.available()) {
          ss.read();
          timeoutloop = 0;  // If char was received reset the timer
        }
        delay(1);
      }
    }

    char readBlocking() {
      while (!Serial.available());
      return Serial.read();
    }

    uint16_t readnumber() {
      uint16_t x = 0;
      char c;
      while (! isdigit(c = readBlocking())) {
        //Serial.print(c);
      }
      Serial.print(c);
      x = c - '0';
      while (isdigit(c = readBlocking())) {
        Serial.print(c);
        x *= 10;
        x += c - '0';
      }
      return x;
    }

    uint8_t readline(char *buff, uint8_t maxbuff) {
      uint16_t buffidx = 0;

      while (true) {
        if (buffidx > maxbuff) {
          break;
        }

        if (Serial.available()) {
          char c =  Serial.read();
          //Serial.print(c, HEX); Serial.print("#"); Serial.println(c);

          if (c == '\r') continue;
          if (c == 0xA) {
            if (buffidx == 0) {  // the first 0x0A is ignored
              continue;
            }
            buff[buffidx] = 0;  // null term
            return buffidx;
          }
          buff[buffidx] = c;
          buffidx++;
        }
      }
      buff[buffidx] = 0;  // null term
      return buffidx;
    }
    /************************ MENU HELPERS ***************************

I bet the Adafruit Soundboard code is not for an ESP32. But you don’t have to use SoftwareSerial on an ESP32! It has plenty of “real” (hardware) serial ports. Use Serial1 or Serial2 instead. For some simple example code see here. You would also have to change the RST pin into a pin that is actually available on the ESP32 (GPIO4 isn’t).


text:
Brushless Motor "twitches" on its own when connected to battery
I've been trying to make a Bluetooth slider app that can control the spin speed of a brushless motor. The transmitter I am using is Arduino Mega. The problem I'm having is that my motor will start twitching at very random times even though my Arduino code specifies ESC.write(0), meaning the ESC should remain completely still.
Furthermore, I've noticed that the twitching begins the exact moment I connect my HM10 Bluetooth module to the Arduino. The motor is still able to be controlled by the slider on my app, however, even when the slider is set at zero, the motor turns on its own! I will attach a video to the problem in this link.
A couple of things I've noticed that may be of interest: when the ESC bullet connectors touch each other, there are audible sparks as well as burn holes.
Here is my arduino code

/*
   -- New project --

   This source code of graphical user interface
   has been generated automatically by RemoteXY editor.
   To compile this code using RemoteXY library 2.4.3 or later version
   download by link http://remotexy.com/en/library/
   To connect using RemoteXY mobile app by link http://remotexy.com/en/download/
     - for ANDROID 4.7.12 or later version;
     - for iOS 1.4.7 or later version;

   This source code is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
*/

//////////////////////////////////////////////
//        RemoteXY include library          //
//////////////////////////////////////////////

// RemoteXY select connection mode and include library
#define REMOTEXY_MODE__SOFTSERIAL
#include <SoftwareSerial.h>

#include <RemoteXY.h>

#include <Servo.h>

Servo ESC; //create servo object

// RemoteXY connection settings
#define REMOTEXY_SERIAL_RX 10
#define REMOTEXY_SERIAL_TX 11
#define REMOTEXY_SERIAL_SPEED 9600

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,2,0,0,0,60,0,11,13,1,
  4,0,23,16,17,64,2,26,2,0,
  31,5,22,11,2,26,31,31,79,78,
  0,79,70,70,0,129,0,5,7,18,
  6,17,76,69,68,0,129,0,15,85,
  37,6,17,83,101,114,105,97,108,32,
  111,117,116,112,117,116,0 };

// this structure defines all the variables and events of your control interface
struct {

    // input variables
  int8_t slider_1; // =0..100 slider position
  uint8_t switch_1; // =1 if switch ON and =0 if OFF

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

int power = 8;
int ledPin = 2;

void setup()
{
  RemoteXY_Init ();

  digitalWrite(LED_BUILTIN, HIGH);
  // TODO you setup code

  pinMode (LED_BUILTIN, OUTPUT);
  pinMode (power, OUTPUT);
  pinMode (ledPin, OUTPUT);
  //pinMode (7, OUTPUT);
  //int ledMapping;

  ESC.attach(6, 1000, 2000); //attach ESC to output from pin 6

  Serial.begin(9600);
}

void loop()
{
  RemoteXY_Handler ();

  //Serial.println(RemoteXY.slider_1);
  digitalWrite(power, HIGH); //supply power to Bluetooth module through pin 8
  //digitalWrite(7, HIGH);
  int ledMapping = map(RemoteXY.slider_1, 0, 100, 0, 255);
  //Serial.println(ledMapping);
  analogWrite(ledPin, ledMapping);

  int spinMapping = map(RemoteXY.slider_1, 0, 100, 0, 180); //map the slider to the servo
  if (RemoteXY.switch_1 == 1){
  ESC.write(spinMapping); //write to the ESC the value of mapped slider
  }
  else if (RemoteXY.switch_1 == 0){
  ESC.write(0);
  }
  Serial.println(spinMapping);

  if(RemoteXY.switch_1 == 1){
  digitalWrite(LED_BUILTIN, HIGH);
  }
  else if (RemoteXY.switch_1 == 0){
   digitalWrite(LED_BUILTIN, LOW);
  }

  // TODO you loop code
  // use the RemoteXY structure for data transfer
  // do not call delay()

}

But I don't think it is the problem. The reason is because even though I have ESC.write(0) when the LED switch is off, the ESC still turns (as is apparent in the video) randomly and twitches.
Any help would be greatly appreciated. I am trying to use this as a prototype for an eletric skateboard, but obivously if the motor is turning on its own even when it should be stopped, it is very dangerous to use.

please include the actual code instead of a link .... also add a schematic diagram of the circuit

what is your question? ... this is a Q&A site

Here is my arduino code, which I don't think is the problem. The reason is because even though I have ESC.write(0) when the LED switch is off ... how do you know that the led is off? ... the LED code is in a different if statement from the motor code ... also the LED could light very briefly, and you would never see it ... your code contains no debugging functions that could be used to confirm your thinking

you also have no way of knowing what data passes between the android device and the arduino ... write a simple sketch that does not have any motor functions, but logs the data that is received from android ... until you prove the quality of the connection between the two devices, it is kind of pointless to be thinking about the motor

@jsotola thanks for the responses. I should clarify: I've been using RemoteXY, which is an app that allows the Arduino to communicate with a smartphone via Bluetooth. I know that the slider_1 variable is set to zero (since the built_in LED turns on and off when the slider is set on and off), so the code should enter the else if (slider_1 ==0)  {ESC.write(0)} section. I'm suspect that it does, however perhaps a faulty connection may be causing the ESC to deliver power to the motor regardless of  the logical statements in the code?

faulty connection may be causing the ESC to deliver power to the motor ... start thinking about testing individual components ... test the "bad connection" theory ... write code that runs the motor for one or two seconds, stops motor for five seconds, and repeats

look at blinkWithoutDelay example code ... modify it so that the LED is turned off every second, or two, no matter what state it is in .... turn the LED on using if(RemoteXY.switch_1 == 1){ .... that will tell you if there are any phantom button presses .... basically, only a button press turns on the LED, and only a timeout turns it off .... chances are very high that the LED will stay on long enough for you to see it, if a phantom button press is received

try detaching the ESC instead of ESC.write(0)

Could you please expand on your answer. Like quickly explaining how to detach ESC and how that will have an effect.


text:
Arduino UNO With On / Off Module Switch + Battery Advice
So I have the following connected and the programming works fine when connect by USB
The Parts

1 Arduino UNO
1 Laser Module (KEYS)
1 Rocker Switch Module (Standard 3 PIN)
2 Variation Motors (KEYS)
1 Speaker Module (BIG SPEAKER MODULE)
2 Push Button Modules (Standard 3 PIN)
1 SD Card Reader Module (Generic)
1 3V 1800 amh Battery

The Problem 1
I want to make an On/Off Switch but it doesn't work.
Battery Powers The Arduino Like This: (WORKS)
https://postimg.cc/JHmTwFKc
Battery Powers The Arduino Like This: (NOT WORKING)
https://postimg.cc/V0RKzFVy
PROBLEM 1: Why doesn't this work when it does for the Nano I have here:
https://postimg.cc/SnXHfwPJ
Secondly Here are some pictures of the setup I have
Battery - Rocker
https://postimg.cc/KK6qfjMW
Rocker - Arduino
https://postimg.cc/hXH6y2FM
https://postimg.cc/4HJrvnCg
Wide View Of Project
https://postimg.cc/3WY5Qfkc
The Problem 2
I need advice on what size battery to use the project for 1-2 hours I think I need (5v,7v,9v) but would like some help with which would be best suited or any suggestions you have
What I think it is but need help

The Wiring is wrong (but I have tested it all and its working fine)
The Rocker Module is passing 3V to the UNO (Not enough Power)
The Battery is not powerful enough (I need a bigger battery)
NOOB Problems as its my first project

What I need help with

What battery to use?
Making the On/Off switch work

Thanks for the HELP!!!
BONUS
Here is the code used:
    #include <pcmConfig.h>
    #include <pcmRF.h>
    #include <TMRpcm.h>

    #include <SPI.h>
    #include <SD.h>

    //SD card pin
    #define SD_ChipSelectPin 10
    //soundplayer object
    TMRpcm tmrpcm;

    int led = 13;
    //pin numbers
    int buttonpin = 3;
    int lazerpin = 4;
    int buttonpin2 = 5;
    int motorPin = 6;
    int motorPin2 = 7;

    //other values
    int t = 0;
    int val;
    int val2;
    int ammoUsed = 0;
    int prestate = 0;
    int prestate2 = 1;
    int canReload = 0;

    void setup()
    {
      //pin modes
      pinMode(led, OUTPUT);
      pinMode(lazerpin, OUTPUT);
      pinMode(buttonpin, INPUT);
      pinMode(buttonpin2, INPUT);
      pinMode(motorPin, OUTPUT);
      pinMode(motorPin2, OUTPUT);

      Serial.begin(9600);
      if (!SD.begin(SD_ChipSelectPin))
      {
        return;
      }
      else {
        //setup sound
        tmrpcm.speakerPin = 9;
        tmrpcm.quality(1);
        tmrpcm.setVolume(5);
        //play setup sound (user knows the gun is ready)
        playSound(0);
        tmrpcm.disable();
        tmrpcm.stopPlayback();
      }
    }

    //method to call sounds depending on the input
    void playSound(int t) {
      tmrpcm.disable();
      tmrpcm.stopPlayback();

      if (t == 0) {
        tmrpcm.setVolume(5);
        tmrpcm.play("0.wav");
        delay(2980); //time of clip
      }
      else if (t == 1) {
        tmrpcm.setVolume(6);
        tmrpcm.play("1.wav");
        delay(660); //time of clip
      }
      else if (t == 2) {
        tmrpcm.setVolume(5);
        tmrpcm.play("2.wav");
        delay(950); //time of clip
      }
      else if (t == 3) {
        tmrpcm.setVolume(6);
        tmrpcm.play("3.wav");
        delay(620); //time of clip
      }
      else if (t == 4) {
        tmrpcm.setVolume(5);
        tmrpcm.play("4.wav");
        delay(660); //time of clip
      }

      tmrpcm.disable();
      tmrpcm.stopPlayback();

      return;
    }
    void loop()
    {
      val = digitalRead(buttonpin); // check the state of the button
      val2 = digitalRead(buttonpin2); // check the state of the button

      //reload gun
      if (val2 == HIGH && prestate2 == 0 && canReload == 1)
      {
        //reset ammo and play sound with vibrate
        ammoUsed = 0;
        canReload = 0;
        digitalWrite(motorPin, HIGH); //vibrate
        digitalWrite(motorPin2, HIGH); //vibrate
        playSound(3);
        digitalWrite(motorPin, LOW);  //stop vibrating
        digitalWrite(motorPin2, LOW);  //stop vibrating
        prestate2 = 1;

      }
      else if (val2 == LOW)
      {
        //reload let go
        prestate2 = 0;
      }

      //Shooting the gun 1-4 normal. 5 is louder and longer.
      if (val == LOW) // if button is pressed, turn LED on
      {
        digitalWrite(lazerpin, LOW);
        digitalWrite(led, LOW);
        prestate = 0;
      }
      else if (val == HIGH && prestate == 0)
      {
        if (ammoUsed != 5)
        {
          ammoUsed ++;

          if (ammoUsed > 0) {
            canReload = 1;
          }
          else {
            canReload = 0;
          }

          //turn on lazer and virbate
          digitalWrite(lazerpin, HIGH);
          digitalWrite(led, HIGH);
          digitalWrite(motorPin, HIGH); //vibrate
          digitalWrite(motorPin2, HIGH); //vibrate

          //play sound
          if (ammoUsed == 5) {
            playSound(2);
          }
          else {
            playSound(1);
          }
          //after sound lazer and vibrate turn off
          digitalWrite(motorPin, LOW);  //stop vibrating
          digitalWrite(motorPin2, LOW);  //stop vibrating
          digitalWrite(lazerpin, LOW);
          digitalWrite(led, LOW);

          prestate = 1;
        }
        else {
          //no ammo just vibrate and play sound with no lazer
          digitalWrite(motorPin, HIGH); //vibrate
          digitalWrite(motorPin2, HIGH); //vibrate
          playSound(4);
          canReload = 1;
          digitalWrite(motorPin, LOW);  //stop vibrating
          digitalWrite(motorPin2, LOW);  //stop vibrating
          prestate = 1;

        }
      }

    }

Please link to the switch product, that you used. An image is not enough here. We beed to know, how the board uses the switch. Is it just a breakout board for the 3 switch pins or are there other electronics on it? Also please put the images directly in the question, not on an external site. And some of the images are not in focus or rather dark. Please provide good in-focus pictures, so that we can actually see something in them

Good starting project, You need to understand how a switch works, your first does not work you short the battery, draining it very fast. You need only two connections to the switch. Run ground to ground, battery to center pin and arduino to NO pin. Let us know if that works. You can view a few basic electronics tutorials, that will help. Remember we all started the same place you are. Most important have fun!

https://www.geekbuying.com/item/Arduino-2-Mode-Rocker-Button-Switch-Module-Compatible-With-RPi-STM32-343528.html this is the rocker

can confirm its definitly the 2 mode rocker that is wrong.......... as i have just tried it with a push switch to test it. and works fine haha. I tried what you said and the rocker switch does work either (SIG/VCC/GND) connect battery to VCC and SIG to arduino still nothing

So here is the deal (I Kinda Solved It) so I took apart a 9V battery pack with a flip switch in it..... soldered some wired to it and now it works perfectly...... haha
but I would still like the know the reason why the rocker switch module doesn't work.
the only thing I can think of is the Voltage or Amp passed from the Switch Module isn't enough to power the board (as I tried 3 different rocker switches and all acted the same)
Thanks for the help


text:
Inconsistent values from NTP client
Hardware- ESP8266 Based NodeMCU
I am using NTP Client for time in my alarm project.
I am facing an issue where NTP client is not returning proper values, in the sense that it works properly for the first few hours- returning the time every second, however after some time the values go haywire.
First few hours:-
21:00:45
21:00:46
21:00:47
21:00:48

After sometime:-
06:00:02
06:00:45
06:00:49

What could be the cause of this and how do prevent it?

don't use NTP library on esp. esp has 'built-in' ntp functions. see the esp8266/NTP-TZ-DST.ino in IDE examples menu

returning the time every second ... maybe the NTP server starts to ignore your request

@jsotala I'm only using timeClient.getFormattedTime and timeClient.update() , in my loop, I have found out that timeClient.update() does not return anything until the update interval is over, which in my case is about 10 mins


text:
Multiple variable shared between threads?
I got 4 threads running on ESP32 (dual core):

1 thread running on 1st core which is related to the WiFi.
1 thread running on 2nd core which is related to the touchscreen.
1 thread running on 2nd core which is related to the display.
1 thread running on 2nd core which is related to the sensors.

Some of the threads execute almost instantly, while for instance the one handling the sensors can take a few seconds per interaction, and no blocking should occur meanwhile for the rest of the threads.
Anyway, with the growing of the program, a lot of variables started to be involved in data transfers between the cores, and since the whole thing is about to be redone, I have the following questions, to clear the things up for myself, since I found quite a lot of confusing, even contradictory information in examples and explanations on the internet:

Is the "volatile" keyword really sufficient for exchange of data between threads (no ISR)?
Should "volatile" always be between "noInterrupts()" and "interrupts()", even when there is no ISR function?
What approaches should be used when exchanging a lot of variables between the threads (currently about 40 variables, but the number will probably grow)?
Is xQueueSend / xQueueReceive blocking in case it is put all around the threads with different variables?

probably happened during copy.

Is the "volatile" keyword really sufficient for exchange of data
between threads (no ISR)?

No - "volatile" just tells the compiler that the variable may change value due to something other than the immediate code being generated and informs the code-generator not to rely on the value remaining static when it would otherwise expect so. When copying the value to a register for instance, it would normally expect that register value to continue to represent the value of the variable in memory but if the variable is volatile, that assumption doesn't hold. This would be used to indicate that an ISR might change it at any time; that the variable is an input register and may be changed from the outside at any time; or that another thread may change it, again, at any time (assuming pre-emptive multi-threading or multi-tasking).
Should "volatile" always be between "noInterrupts()" and "interrupts()", even when there is no ISR function?

No - volatile just describes an attribute about the variable over time

What approaches should be used when exchanging a lot of variables between the threads

Use a semaphore here. A thread that wants access to one of - or the collection of - shared variables asks for the semaphore. The RTOS either returns it immediately, or (because another thread already holds it) suspends the task until it becomes available, and returns it then. The thread holding the semaphore may access the variables (or whatever shared resource this semaphore controls), then returns the semaphore on completion. Semaphores are usually built in to the RTOS.
(As I'm not familiar with your particular RTOS, I'll leave your fourth question for someone who is).

Thank You for the points JRobert. I am using FreeRTOS ( Espriff IDF )