text:
How to use millis instead of delay?
Sorry if something similar has been answered before...
I am working on a garden timer project that runs on a ESP8266 based NodeMCU and is integrated with Blynk.
I have a waterNow function that activates when I press a button on the Blynk app, it sets pin D5 to HIGH and waits 3 seconds with a delay function, the problem is that with delay the code just halts all other functions until the delay is complete.
After doing some research I found out that the millis function could be used to have a time delay and have the program still run, but I can't get it to work.
How do use the millis function to add a delay?
Any help is appreciated.
Code:-
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include "DHT.h"
#include "LiquidCrystal_PCF8574.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

char auth[] = "ymri204FL9_xZhf6WIRHtQ1qEWOt9zBy";

char ssid[] = "Aihertgtel-Hotspotgfdf-82DB";
char pass[] = "";
int autoSch;
int waterNow;
int morTime;
int afterTime;
int eveTime;
int schTime;
int x;

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(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
}

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()));
  Serial.println(dht.readTempC());
}

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 (eveTime == 1 && String(timeClient.getFormattedTime()) > "15:47:00" && String(timeClient.getFormattedTime()) < "13:48:00") {
   // digitalWrite(14, HIGH);
    for (x; x >  10; x++){
  digitalWrite(14, HIGH);
  delay(1000);
  }
    Blynk.virtualWrite(V5, 255);
    Blynk.syncAll();

  }
  else {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
    Blynk.syncAll();
  }
}

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

}

void waterNowrun() {
  if (waterNow == 1) {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    lcdI2C.selectLine(2);
    lcdI2C.print("Watering Now     ");
    delay(3000); // I want to remove this for millis
    Blynk.virtualWrite(V10, 0);
    Blynk.syncAll();
  } else {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
  }
}
void lcd() {
  delay(300);
  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("Watering Now");
  }
  else
  {

    if (int(timeClient.getHours()) < 6 && morTime == 1 && autoSch == 0) {
      Blynk.syncAll();

      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6");
    } else if (int(timeClient.getHours()) < 12 && afterTime == 1 && autoSch == 0) {
      Blynk.syncAll();

      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 12");
    } else if (int(timeClient.getHours()) < 18 && eveTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);

      lcdI2C.print("Auto Wtr at: 18");
    } else if (int(timeClient.getHours()) >= 18 && morTime == 1 && autoSch == 0) {
      Blynk.syncAll();
      lcdI2C.selectLine(2);

      lcdI2C.print("Auto Wtr at: 6");
    } else {
      Serial.println(timeClient.getHours());
    }

  }

}

void loop()
{
  Blynk.run();
  time_run();
  lcd();
  timeClient.update();

  if (waterNow == 1) {
    waterNowrun();
  }
  if (autoSch == 0) {
    auto_run1();

  } else {
    sch_run2();

  }

}
void setup()
{
  dht.begin();
  lcdI2C.begin(LCD_COLUMNS, LCD_ROWS, LCD_ADDRESS, BACKLIGHT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  pinMode(14, OUTPUT);
  digitalWrite(14, LOW);
  pinMode(16, INPUT_PULLDOWN_16);

  Serial.begin(9600);
  //WiFi.begin(ssid, password);
  Blynk.begin(auth, ssid, pass);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  timeClient.begin();
}

This question comes up regularly. Look at the “Blink without delay” example included with the Arduino IDE to see how you can use millis() for non-blocking time delays and event scheduling.

I have already looked at that, can't make out anything... but will try again

Short hint: You have to keep track of your state. So in the WaterNow function you have to store the millis() value to a variable when you start watering and then compare that value regularly with the current time to find out when the required amount has elapsed.

Does this answer your question? How to use millis() in my code instead of delay()?

Does this answer your question? Is it possible to replace this delay with millis()? (And issue with other millis loop)

Try this search: https://arduino.stackexchange.com/search?q=%5Bmillis%5D+delay

I am assuming after you start watering you want to set V10 to 0 after 3 seconds.
First, you will have to set waterNow to 0 after you start watring. Otherwise waterNowrun() will keep executing.
Second, you need to keep track of the 'watering' state so that you know that you have to start tracking the time.
Third, save the time when the watering started so that you can compare with the current time to see if your '3 seconds' has been passed.
Here is a simple example:
// Global variables
const long int MAX_TIME_THRESHOLD_MS = 3000;
bool WateringStarted = false;
long int WateringStartTime = 0;

... ... ...

void waterNowrun()
{
  if (waterNow == 1)
  {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    lcdI2C.selectLine(2);
    lcdI2C.print("Watering Now     ");

    waterNow = 0;
    WateringStarted = true;
    WateringStartTime = millis();

  }
  else   // <------ Why do you even have else! You only call waterNowrun() when waterNow == 1
  {
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
  }
}

... ... ...

void loop()
{
  ... ... ...

  if(WateringStarted && (millis() - WateringStartTime) > MAX_TIME_THRESHOLD_MS)
  {
    WateringStarted = false;
    Blynk.virtualWrite(V10, 0);
    Blynk.syncAll();
  }

  ... ... ...

}

I haven't run this code and don't have your setup to check it either. But it should give you some idea. Also, check the comments to your question for some more information about millis().

The setup is after the loop

Haha! I meant your actual hardware setup and Blynk app etc.

Oh ok..... I got it solved


text:
Analog read not working while using WiFi
I have an ESP32, the current program running on it uses WiFi but, if I use WiFi and Analog read at the same time, Analog read does not work.
Why does this happen and what's the way around it?
Hardware - ESP32, Pin 25 for the ADC
Code-
#include <WiFi.h>

void setup() {
  Serial.begin(115200);
  WiFi.begin("You really", "Want to know"); // If this line is commented then it works
}

void loop() {
  Serial.println(analogRead(25));
}

What do you mean with “analogRead does not work”? What happens when you try to read an analog value from a pin? Please describe your hardware setup and show some code that demonstrates  the problem.

When WiFi is being used the values from analogRead stay at 0 whether connected to 3.3 or 100 volts

That is not normal behaviour so it's probably caused by your specific setup. Please provide some more information. What about your code and hardware setup? Are you using the correct pin(s). If you have connected an analog port to 100 volts you have probably killed your ESP32.

l'll update the question with the code, "100 Volts" was supposed to sarcastic as it shows   only 0 connected to any voltage

This code is a simplified version, but the problem exists here too

Please be specific regarding the hardware. There's nothing here we can use to help. It might make sense to troubleshoot the wifi issue; without any context my guess would be that it's either failing or looping.

Esp32 Wroom module in a nodemcu form factor, nothing else

... Can you provide a schematic? And be specific about three board? Generalities are not helpful when discussing specific issues. WiFi didn't generally disable analog, which is why I suspect an initialization issue. Have you used WiFi without anything else?

The ESP32 has two ADCs. One of them, ADC2, is actively used by the WiFi.
From the IDF documentation:

Since the ADC2 module is also used by the Wi-Fi, only one of them could get the preemption when using together, which means the adc2_get_raw() may get blocked until Wi-Fi stops, and vice versa.

That means you can't use the ADC on any of the ADC2 channels while WiFi is on: GPIO4, GPIO0, GPIO2, GPIO15, GPIO13, GPIO12, GPIO14, GPIO27, GPIO25 and GPIO26.
But you can use ADC1, which uses pins GPIO36, GPIO37, GPIO38, GPIO39, GPIO32, GPIO33, GPIO34 and GPIO35.

source: Stack Exchange

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

sort: votes


text:
Trying to understand interaction of interrupts, noInterrupts and delays
I'm having trouble understanding how to activate interrupts so that they operate only when they should. With this code, I seem to get erratic performance when I either attach or unattached interrupts, or when I try using noInterrupts.
What I am trying to accomplish is to deactivate the alarm function from running until a slight delay is initiated upon hitting an incorrect key. That would allow leaving the premises without triggering the interrupt. Does noInterrupt only affect the function in which it is placed??
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int PIR_SensorPin = 2;
int LED_OutPin = 11; //green
int Alarm_OutPin = 12; //red
int alarm_count = 0;
volatile boolean trigsensor = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;
int timeout = 10000;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (LED_OutPin, HIGH);
  }
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
  Serial.println ("System Ready");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop()
{
  readKeypad(); // Serial.println ("at keypad");
  if (trigsensor == true) {
    alarm ();
  }
}

///////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  alarm();
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("trigsensor="); Serial.println (trigsensor);
  Serial.println ("at Alarm");
  if (away == true && trigsensor == true) {
    noInterrupts();////////////////////////////////
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW); delay (500);
      digitalWrite (LED_OutPin, HIGH); // delay (1000);
      //   digitalWrite (LED_OutPin, LOW); delay (1000);// End by turning off light
      Serial.println (alarm_count);
    }
  }
  trigsensor = false;
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    tone(10, 900, 100);
    Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  digitalWrite (LED_OutPin, HIGH);
  digitalWrite (LED_OutPin, LOW);
  trigsensor = false;
  away = false;
  readKeypad();
}

///////////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  noInterrupts();
  Serial.println ("@ incorrect PIN ");
  //detachInterrupt(0); Serial.println ("interrupt off 1");
  trigsensor = false;
  away = true;
  digitalWrite (LED_OutPin, HIGH);
  delay(timeout);
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); Serial.println ("interrupt on 2");
  alarm(); Serial.println ("here");
}

Well, yes, I think attaching and detaching interrupts isn't really something that you should do to often. It also won't really make your code very much more readable.
You may have a look at programming (embedded systems) in general. A technique I like to do is making a (non-blocking) state machine. In this way you don't even need interrupts (you can actually have interrupts if you want, though).
Also, it may be worth noting that making your code more readable and understandable is likely going to improve your "idea of what is going on" and thus improve it's reliability. This is commonly done by designing and applying "scope" to your code. You've done well on the keypad functions, giving them a sane name and reasoning. You could've put them in a class, but that's not where the errors are at.
Basically, your alarm has a few states:

Armed
Unarmed
Alarm!
Just activated

From these, you can form a state diagram.
Usually, "events" lead to the state of your system being changed.
For example:

simulate this circuit – Schematic created using CircuitLab
(Sorry for "abusing" the schematic editor (:  )
As you can see, events can be user interaction/sensors/timing, basically anything.
By designing your code in a state diagram, you get an idea of what you want your machine to do, at what moment. And what other states it can go to from there (and when/how).
Your code will become something along the lines of:
setup
enum STATE{
  armed,
  unarmed,
  justActivated,
  alarm
};

STATE systemState = unarmed;
long timeGettingArmed;

loop
switch(systemState){
   case armed:
   if(breakinSensor.check() == HIGH){
      systemState = alarm;
   }else if(keyPad.check() == deactivated){
      systemState = unarmed;
   }
   break;
   case unarmed:
   if(armButton.check() == HIGH){
      timeGettingArmed = millis(); // Or you could just do a delay here.
      systemState = justActivated;
   }
   break;
   case justActivated:
   if(timeGettingArmed + waitTime < millis()){
     systemState = armed;
   }
   break;
   case alarm:
   if(keyPad.check() == deactivated){
     systemState = unarmed;
   }else{
     beep();
   }
   break;
}

Ofcourse you'll have to highly adapt this code to suit your needs, I doubt it will even compile. But it can also be a part of designing your program, try just writing it out in words (or explaining it to someone), before you program it.
*You could make use of the interrupts by checking in the interrupt if the state is "armed" and then setting the state to "alarm". This way you avoid the interrupt messing up any of your logic and having to disable it.
The cool thing of this "non-blocking" (if you don't use delays) state machine is that you can actually add more statemachines to it, and it will seem like the processor does everything at the same time. This is because it skips rather fast through the "i/o checks".

Your approach seems valid, but my issues to date are always getting sidetracked with trying to implement new techniques that I don't fully understand. The result is that I have been working on this project way too long. I will attempt your ideas on my next project.

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


text:
Arduino State Machine code flow
New to FSM, can someone explain how the flow works? If I use a case scenario in a loop, how is an external change detected and brought back to the loop?
Is all of the code/inputs, etc to be included within the case statements?
Still having a few problems. I have modified my code to include some of the suggestions. You can see that I added some print statements to allow me to monitor execution, but I can't get it to obey, such as print "trigger" when the PIR sensor is HIGH. Anyone available to explain my error(s)? I added a void check() just to bypass the keypad (not connected).
//////////////////////////// Initialize & Includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int PIR_SensorPin = 2;
int LED_OutPin = 11; //green
int Alarm_OutPin = 12; //red
int alarm_count = 0;
int switchPIN = 3; // alarm on test
char keypadPIN;
int z = 0;
int i = 0;
int waitTime = 5000;

//////////////////////////// Setup Keypad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// Setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (LED_OutPin, OUTPUT);     // Set pinMode.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (LED_OutPin, LOW);   // Set output pins to LOW for start.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (LED_OutPin, HIGH);
  }
  attachInterrupt (digitalPinToInterrupt (2), trigger, CHANGE); // PIR as interrupt
  // Could make use of the interrupts by checking in the interrupt if the state is "Ready" and
  // then setting the state to "Alarm".
  Serial.println ("System Ready");

  keypadPIN = HIGH;
}

//////////////////////////// State Setup //////////////////////////
enum STATE {
  Ready, //system acknowledges trigger
  Unarmed, //system unarmed via keypad entry setting keypadPIN = LOW
  JustActivated, //PIR-triggered interrupt
  Alarm // confirm system unarmed then goto unarmed state else start alarm
};
STATE systemState = Unarmed;
long timeGettingArmed;

/////////////////////////// Trigger ///////////////////////////////
void trigger() {
  systemState = JustActivated;
}

//////////////////////////// State Machine //////////////////////////
void loop() {
  check ();
  switch (systemState) {Serial.println("switch");
    case Ready:
      if (PIR_SensorPin == HIGH) {Serial.println("PIR_Sensor");
        Serial.println("triggered");
        systemState = Alarm;
      } else if (keypadPIN == LOW) {
        systemState = Unarmed;
      }
      break;
    case Unarmed:
      if (keypadPIN == HIGH) {Serial.println("keypadPIN=HIGH");
        // Serial.println("Unarmed");
        timeGettingArmed = millis();Serial.println(timeGettingArmed);
         systemState = JustActivated;
      }
      break;
    case JustActivated:Serial.println("JustActivated");
      if (timeGettingArmed + waitTime < millis()) {
        Serial.println("Ready");
        systemState = Ready;
      }
      break;
    case Alarm:
      if (keypadPIN == LOW) {Serial.println("keypadPIN=LOW");
        systemState = Unarmed;
      } else {
        beep();
      }
      break;
  }
}

//////////////////////////// Alarm //////////////////////////
void beep() {
  Serial.println("at beep");
  // (sms.SendSMS("8656171435", "*** Motion Detected in Studio! ***"));
  Serial.println ("MOTION detected: SMS Sent");
  for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
    digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
    digitalWrite (Alarm_OutPin, LOW); delay (500);
    digitalWrite (LED_OutPin, HIGH); // delay (1000);
    Serial.println (alarm_count);
  }
  systemState = Ready;
}

void check() {
  if (switchPIN == HIGH) {
    keypadPIN = LOW; // Unarmed
  }
  else {
    keypadPIN = HIGH; // Ready/Armed
  }
}

generally, you don't detect the change in that type of setup: you move one state to the next in a manner that that state behaves correctly after considering the context. for a button click/dblclick() library, i used: ready,1stDown,1stUp,2ndDown,stale states, which vary from the short,click,dblclick outputs. when in one state, check if you need to change to another state, and if not, do nothing. usually it's nothing.

Maybe I wasn't clear. Are the inputs signaling an event change to change a state located within or outside of the case statements?

one case, if needed, sets the state to another case or does nothing

A "state" is just a variable. Anywhere that variable has scope can change the state.

@Majenko: shared mutable state that gets changed in multiple places is the root of all evil, and the reason why redux/flux is so popular. I (and many others) HIGHLY recommend that you only change state in the switch to avoid spaghetti flow as the project grows. It's an adjustment for sure, but i loved it. ;)

@dandavis Not always possible. Especially when you're using interrupts.

@dandavis That "non-state flag" could be argued to be a state in its own right.

I moved the gist of my comments to an answer to allow me to explain these concepts in more detail.

Thanks dandavis. I would like to send you my project for your review.

MCU State Flow

State ( Model )
User/Machine Output ( View )
User/Machine Interruption ( Events )
State Changers ( Controller )
goto 1.

Breakdown of how it works:
#1. State. You start with a known finite state, which is the overall mode of operation for that piece or pieces. For a switch()-driven machine, it's a number, typically named by an integer constant for better readability.
#2. Output. Based on the state, you make certain things happen. These adjustments can be done in the switch(), or in the loop() as they notice state changes. You can also write explicit sub-routines to call from the switch() to keep code tidy. You can read the state from any point in the program, even interrupts if needed.
#3. Events/Interrupts. Lying in wait, these parts spring into action when something happens that the program needs to know. Both human-origin (ex: button press) and machine-origin (ex: SD card error) fall into this group. They can set flags and publish notifications to the controller that something has happened, but they MUST NOT set the state directly. The last point cannot be under-emphasized. If you start "cheating" and updating state outside of the controller, you  create another point of failure and another stop along the debug/enhancement tour.
#4. State Changing switch() (Controller).  This is where the actions meet the state. Only here should you change state to a new one, based on outside flags set by events. If your switch() is at the top of loop(), and you return in each case, you can call loop() from other points in the code to fire a state change immediately, but i like to name it in a void() and call it from loop(). The switch code should be lightweight and never use delay(). Lastly, most of the time a case does nothing, because no outside condition has changed that merits reaction, and it breaks or returns right there. When something important does change, the code below that early-exit conditional performs as a state change event handler.

Why bother
It can be a bit much at first, and seem like it's not worth the 5-10 mins up-front to name constants and write out all the switch bolierplate. I'm a lazy coder, and I still use this because it saves me a ton of time at every point in time besides those first 10 minutes.
Since things can only change in one place, you know exactly where to debug. It's simple to dump the outside values a case examines to the serial (remove before "launch"), rather than finding that chunk of code in the ether. Doing it all in one place makes it trivial to log when and what with each state change. With minor additional code you can even undo state changes, which can be a boon for users. Such actions are not risky because every part of the outside code knows what to do.
It breaks up tedious chains of semi-related action into independent pieces. You won't need lots of nested if()s if you follow the above guidelines. Even if you're not a long-time developer, simply following this pattern and slopping/pasting all the other code together, your program will be better in the end and faster and easier to build along the way.

Thanks. Looks like your idea is proving out well. Gave me another tool.

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


text:
I am building a coin operated machine and am using arduino uno its working but i have to press the switch twice for credit to show on seven segment
int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
volatile byte  num = 0;
int coinPin = 2;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(coinPin), inc_counter, RISING );
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);
  pinMode(pin4, OUTPUT);
}

void display(int num) {
  digitalWrite(pin1, bitRead(num, 1));
  digitalWrite(pin2, bitRead(num, 2));
  digitalWrite(pin3, bitRead(num, 3));
  digitalWrite(pin4, bitRead(num, 4));
}

void loop() {
  Serial.print(num);
  Serial.print("credit(s) towards balance");
  display(num);
  delay(500);
}

void inc_counter() {
  num++;
}

what is your question? ... not all people would ask the same question

Based on the code supplied, you are only updating the display every half second because of the delay(500). You could press the button a number of times in 500mills.
I feel it may be better to update a flag and check that in your loop to increment your value and trigger the display update.
Based on the info provided, this may help in your endeavours.
int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
int coinPin = 2;
int num = 0;
volatile bool coinFlag = false; // When true there is a coin.

void coin_present()
{
    coinFlag = true;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(coinPin), coin_present, RISING);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(pin3, OUTPUT);
    pinMode(pin4, OUTPUT);
}

void display(int num)
{
    digitalWrite(pin1, bitRead(num, 1));
    digitalWrite(pin2, bitRead(num, 2));
    digitalWrite(pin3, bitRead(num, 3));
    digitalWrite(pin4, bitRead(num, 4));
}

void loop()
{
    // If the flag is set increment num and then display value.
    if (coinFlag)
    {
        //We have a coin, reset the flag first.
        coinFlag = false;

        num++;        // Increment value
        display(num); //
        Serial.print(num);
        Serial.println("credit(s) towards balance");
    }

    // No need for a delay as only `coinFlag` being `true` will update the display.
}

Hope this helps in someway.

Nice answer. Code that I can copy+paste into the IDE that compiles makes this answer better than most we receive.

@VE7JRO Thanks, your comment made me aware of the issue and now prompts me to double check!

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


text:
Leonardo with hm-10 doesn't work
I have a hm-10 module attached to Arduino Leonardo board, I'm using a bluetooth terminal app to send some text.
The problem is I can send data from the Serial monitor to my phone but when I send from my phone, there is no output in the serial monitor.
It works fine if I test it on Arduino Uno.
I'm struggling with something that should be simple.
Can someone please help me?
Here is my code:-
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(4, 5);

void setup(){
  Serial.begin(115200);
  Serial.println("Hello!");
  BTSerial.begin(115200);
}

void loop(){
  while (BTSerial.available()){
    byte data = BTSerial.read();
    Serial.write(data);
  }

  while (Serial.available()){
    byte data = Serial.read();
    BTSerial.write(data);
  }
}

Leonardo has Serial1. You don't need to use SoftwareSerial

I GOT IT!! It was problem with the pin settings.
According to SoftwareSerial library documentation, only pins 8,9,10,11,14,15,16 can be used for RX pin. But i used pin 4 for RX.


text:
Is it possible to read extended ASCII from the serial port?
My project requires that Serial.read() be able to accept extended ASCII characters (0x80 <=> 0xFF). For example, I would expect reading the character ¥ to yield the decimal value 157. Instead, the read() command has two successful reads, with the values: 194 and 165. Of course, I could create a lookup table and convert, but this is not a viable option. I am conforming to the Grbl standard protocol, which uses these single-byte extended ASCII characters as interrupts. Such a two-byte structure precludes a simple peek/read approach necessitated by the protocol.
Edit I tried to simplify the question for this context, but failed to account for the fact that the Arduino IDE will send the input as Unicode. Regardless, it still does not work when sending bytes directly. Namely, if I send the byte 0x93 via C# as Serial.Write("\u0093"), the Arduino's Serial.read() does not see any bytes available. Sending normal ASCII, e.g., Serial.Write("\u0018"), works fine.

the serial port is just a pipe ... what you stuff into it is up to you ... normally, the serial port carries 8 bit data (bytes) ... what that data means to you is not known to the serial port ... if you see two bytes then you are probably transmitting UNICODE, not ASCII ... anyway, it has nothing to do with the serial port

@jsotola silly me; I tried to simplify the question by using the IDE. I have edited the question to reflect that it is also not working when I send bytes directly, e.g., using the C# SerialPort class.

Your edited question is now a question about C#, not about Arduino. You have to ask “How do I send 0x93 through a serial port in C#?” in a more appropriate venue.

@EdgarBonet if you have an agnostic way to easily send/receive bytes directly from the serial port, I'm all ears. I'm unfamiliar with any shell-ish way to do so, and thus was using these proxies.

I do not know C#, and I do not know what you mean by “agnostic”. If by “shell-ish” you mean “from a Unix shell”, the following works in bash: echo -ne '\x93' > /dev/ttyACM0. But then, again, this is not about Arduino, it's about the shell/environment/programming language of your choice.

By agnostic, I mean exactly what you're saying — how can this be tested without introducing the corrupting influence of the shell/programming language, etc? Because the shell command is exhibiting the exact same problem as C# (Serial.available() == 0).

See Disable Reset when Com Port Connected/Disconnected

Yes, of course, you can read any byte sequence. As you have experienced,
if you send the byte values 194 and 165, your Arduino reliably reads 194
and 165.
Now, you have to be aware that there are tons of incompatible character
encodings that could all be called “extended ASCII”. I do not know which
one you have in mind. Maybe there is such an encoding where “¥” has the
code point 157. Nowadays, however, almost any modern computer system
uses Unicode, and serializes the characters using UTF-8. The character
“¥” is serialized in UTF-8 as the pair of bytes 194 and 165.
If you want to use the Grbl protocol, send interrupts as bytes, do not
think about them as “characters”.

Ack, of course I forgot to account for the IDE using unicode. Please see the edited question. Also, please note that I defined "extended ASCII" in the OP.

@ZaneClaes: If by “extended ASCII” you mean the byte range 0x80–0xff, that's not what most people call “extended ASCII”. In general, these words are taken to mean any of a myriad character encodings (generally 8-bit encodings) that are ASCII-compatible, and thus “extend” ASCII. If you “expect reading the character ¥ to yield the decimal value 157”, then you are thinking of one such encoding.

the fact that the phrase can have multiple interpretations is precisely why I clarified the exact value range I was talking about ;) The Grbl docs comments call these interrupts "extended ascii," so I was merely copying their convention.


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:
Piezo not loud enough
I'm trying to get 110dB out of a 25khz Piezo Transducer.  This piezo resonates at 25khz and as per the illustration in its datasheet should emit 110dB with 10 volts and 25khz frequency.
Any assistence as to what I'm doing wrong here would be GREATLY appreciated !!
My code is bit-banging it.  With an oscilloscope, I confirmed that I'm getting a nice clean 25khz square wave.
I have attached a step-up circuit to the device and am seeing 10volts across the terminals of the piezo while it is emitting it's 25khz frequency.
However, instead of 110dB, I'm only getting 50dB.
I've tried upping the voltage to 20, and still get the same volume level.  The voltage is adjustable via the screw on the top of the blue capacitor on the Voltage Step Up (pictured below).
I've tried changing the duty cycle having HIGH go for 25microseconds and LOW go for 5microseconds.  I've tried several combinations and a 50/50 duty cycle appears to achieve maximum volume which is 50dB.
Here's how I'm connected:
1.  The inputs of the Step Up are attached to GND and 3.3V pins on the Arduino.
2.  The output+ of the Step Up is connected to 1 pin of the Piezo.
3.  The output- of the Step Up is NOT connected to anything. (tried to connect it to GND but it didn't change anything.
3.  The other pin on the Piezo is connected to D11 on the Arduino.
I'm Running the following code:
 #include<Wire.h>

const int SPK = 11;

void setup()
{
  Serial.begin(9600);
  pinMode(SPK, OUTPUT);
  digitalWrite(SPK, LOW);
}

void loop()
{
  long startTime = millis();
  for (int i = 0; i < 25000; i++)
  {
    digitalWrite(SPK, HIGH);
    delayMicroseconds(15);
    digitalWrite(SPK, LOW);
    delayMicroseconds(15);
  }

  Serial.println(millis() - startTime);
}

UPDATE:
Ok, I am now set up to look like this:

Is this the next step (ie: Adding an Inducer) ?

How have you mounted the piezo? Just like speakers, it's all about the enclosure. Also, solidly mounting it to something, means any deflection of the piezo means movements of air, instead of movement of the piezo if it's just hanging in free air.

The device you pictured seems to be a switch-mode power module which will output 10V DC. Get rid of it before you do any damage.
You don't post any link to data, but I assume you mean the Transducer needs 10V peak-to-peak.
This can easily be accomplished by using 2 digital outputs, connected to the transducer, and driven in anti-phase.
The answer to Push-Pull tone code may be an answer to your problem, but may be overkill. If you just want to output a single tone it is easily done with simple code.
I don't know why you think the transducer outputs 50dB. If it really is doubling the drive voltage will only give 56dB.

Ye HAAA!!!  We're getting closer..  I'm at 85dB now at 1" away from the piezo.  Any ideas how to get 25 more db out of the piezo??  It may not need a full 10 volts to achieve 110db.  We're really close, but I need 110db.  Any ideas how to achieve this?

@Milliways, isn't your anti-phase comment more like 2.5 volts peak-to-peak for a 5 volt Arduino?  That is, if you put an AC coupled scope across the transducer ... I think you would see it deflect up 2.5 volts then down 2.5 volts.

@st2000 the same misinterpretation was made in a comment to  my original linked question. The answer I made then still applies. It is simple circuit theory.

@Milliways, I'm here to learn, so tell me why you are right. The linked question was about an inductive load.  Guessing, a piezo may appear as a capacitive load?  Is that why you are saying it will retain a potential for a total of 5v + 5v = 10v after the switch?  If so would adding a (tuned) capacitor-resistor-circuit in series add to this effect?

@st2000 I am quite willing to help, although this would be better asked as a question on the EE site. Unfortunately I can't give a lesson in circuit theory in comments. Marenko's comment is correct, but it has nothing to do with inductive or capacitative loads. My original Q was about piezo (which is capacitative) - in fact the push-pull is better, because it puts no nett DC across the transducer. You just have to work out the instantaneous voltages at either end then TRANSFORM to a common reference. Why not give it a try - it works, and is common method- previously used in power amplifiers.

I'll put a question on the EE site.  Thanks for the advice. I really appreciate it !!

Alternatively there are COTS parts (Common Off The Shelf) which are simpler to use and may satisfy your requirements.  This is just the 1st one I found (search for "5 volt piezo buzzer").  Of course you have no control over the frequency.  These type of devices are just to get your attention (you didn't say what your application was for).   While it works at 5 volts it is only rated at 85dB @ 10cm.  It appears to contain an internal driver so (apparently) only needs 3 to 15 volts to start making noise.  It is specified to draw 10mA at 12V.  So be careful and measure the current (using a power supply, not from an Arduino) demand at 5 volts.  I think the GPIO pins on an Arduino can only handle less than 40mA.  So stay well below that to be safe.


text:
Switching Many Switches with one Input
I have a situation where I need to select between two signals, lets say 1A or 2B and route it to output 3C. I need to do this six times (2A or 2B to output 2C, 3A or 3B to output 3C, etc.).
These all need to switch based on one output from my chip.
What sort of component do I need for this? I think it's something like a 2:1 spdt multiplexer, but something doesn't seem quite right.
I've been looking at a bunch of data sheets and I cannot seem to find a chip which switches many 2:1 switches based on ONE input. Does such a thing exists? Or am I just way of the mark here? Not sure.
Any help appreciated.
Thanks.

One output from the Arduino can go to many SELECT pins of multiplexers or switches. So where's your problem?

Almost, you will need two 74157 (or similar chips) to switch 8 pairs of TTL level logic signals down to 8 individual signal.


text:
Is it possible to use a slide switch without a resistor?
I understand how pullup and pulldown resistors work with push buttons and I also understand that an analogous idea can be applied to slide switches. Furthermore, I know that some versions of Arduino have an internal pullup resistor that can be used, if you adjust the code properly.
I was wondering, if I can, without using the internal pullup resistor, wire a slide switch without any kind of resistor like so:

As I understand, this should behave exactly the same as using a pull-down resistor. If the switch is on the left side, pin 7 would read LOW and if the switch is on the right side, it would read HIGH.
Is that a problem with wiring the switch like this? Is there a reason why using a resistor would be better?
In my final project I intend to use a Digispark board and I would not like to rely on its internal resistor and I also would like to avoid using an external resistor if I can.

Whats wrong about using the internal pullups? Thats easier than your circuit because you don't need the 5V connection. And for the code its just a pinMode(pin, INPUT_PULLUP) instead of pinMode(pin, INPUT). And a real life switch might have a short time where nothing connected during thr switching action. For handling that you might need to increase the debounce time with your setup.

You may be able to do it, or you may not. It depends on the switch.
There are two classes of slide switch:

Make-before-break
Break-before-make

In the former the contact you are sliding to is connected before the one you are sliding away from is disconnected. This can cause untold problems as you will basically create a short circuit between 5V and GND. Everything will die.
In the latter the contact you are sliding away from is disconnected first, and then the new contact you are sliding towards is connected. That is safer, but it does mean that there is a short period while you're sliding the switch where neither contact is connected. At this time the input pin is floating - just as if you had nothing connected at all (which is in fact the case).
That is of course not a desirable scenario as it's probably the most amount of bounce you will ever see in a switch - bounce you need to eliminate in software to give you a clean signal.
That period of uncertainty is eliminated if you have a pullup or pulldown resistor, since there is never a period where there is no connection, and there's never a period where you risk shorting out power and ground. All you have to content with then is the natural bounce of the contacts as they close.

Now I understand the importance of a resistor. One last question, though. Is there a difference between using a pullup or a pulldown resistor? Or can I use either?

It makes no difference, you can use either.

I'm not sure how common they are, but a Make-before-break switch will still be a problem, even if there's a pullup or pulldown on the center wire.

@PMF only if you continue with the (now pointless) connecting of both power and ground.


text:
How do I optimize this IRremote code?
I am using a ATTINY85 Digispark board with an IR receiver to light some LEDs in my project. The Digispark has a limitation that does not allow it to use the IRremote.h library. I know that there a series of workarounds for that (including a tiny_IRremote library), but I decided to use this simple code I have found online. It turns on/off a led according to a button press in my Remote:
#define led_pin 9
#define receive_pin 4

bool led_state = LOW;
unsigned long int remote_button_code = 835585799;

void setup() {

  pinMode(receive_pin, INPUT);
  pinMode(led_pin,OUTPUT);
  switch_state = digitalRead(switch_pin);

}

unsigned long int receiveIR() {
  // Wait for start pulse
  while(digitalRead(receive_pin) != LOW)

  if(pulseIn(receive_pin, HIGH, 20000) == 0) return 0;

  // Receive pulses
  unsigned long int result = 0;
  for(int i = 0; i < 32; i++) {
    int pulseLength = pulseIn(receive_pin, HIGH, 5000);
    if(pulseLength == 0) return 0;
    if(pulseLength > 1000) result |= (1UL<<i);
  }

  // Stop pulse
  while(digitalRead(receive_pin) != HIGH);

  return result;
}

void loop() {

  if (receiveIR() == remote_button_code){

    led_state^=1;
    digitalWrite(led_pin, led_state);

  };

}

My problem with this code, however, is on the line while(digitalRead(receive_pin) != LOW) (and I think in the line while(digitalRead(receive_pin) != HIGH)), it sticks the code in a loop until it receives a signal from the remote. This means I can not really use anything after the function receiveIR(), because once the code starts executing this function, it will only exit once a signal is received.
My workaround that is to put everything I want to run inside the
while(digitalRead(receive_pin) != LOW){
  }

in the receiveIR() function. Like so:
(this code uses a Sliding Switch to also control the LED)
#define led_pin 9
#define receive_pin 4
#define switch_pin 7

bool led_state = LOW;
bool switch_state;

unsigned long int remote_button_code = 835585799;

void setup() {

  pinMode(receive_pin, INPUT);
  pinMode(switch_pin, INPUT_PULLUP);
  pinMode(led_pin,OUTPUT);
  switch_state = digitalRead(switch_pin);
}

unsigned long int receiveIR() {
  // Wait for start pulse
  while(digitalRead(receive_pin) != LOW){

    if(switch_changed()){

      led_state^=1;
      digitalWrite(led_pin, led_state);

    }

  }

  if(pulseIn(receive_pin, HIGH, 20000) == 0) return 0;

  // Receive pulses
  unsigned long int result = 0;
  for(int i = 0; i < 32; i++) {
    int pulseLength = pulseIn(receive_pin, HIGH, 5000);
    if(pulseLength == 0) return 0;
    if(pulseLength > 1000) result |= (1UL<<i);
  }

  // Stop pulse
  while(digitalRead(receive_pin) != HIGH);

  return result;
}

bool switch_changed(){

  if (digitalRead(switch_pin) != switch_state){

    switch_state ^=1;

    return true;
  }

    return false;

}

void loop() {

  if (receiveIR() == remote_button_code){

    led_state^=1;
    digitalWrite(led_pin, led_state);

  };

}

This workaround does the job, but it is not very elegant. Is there a way to modify the first code, so I can use other functions after I call the receiveIR() function?

move first two lines of receiveIR() into loop() ... do not use while, use if .... use a flag like signalStarted = true to "remember" if receive_pin has detected signal ...  something like this inside loop() ... the if statements are not nested ... if signal is detected and flag is not set, then set flag and start timer .... if flag is set and timer expired, then run receiveIR() ... do other stuff in loop()

forgot one test at the begining of loop() ... if signal not detected  then clear flag ... the if statement order does not really matter


text:
ESP32-DEV is connected to Wifi but not working properly
Hardware:

Board ESP32 Dev Module
Version/Date today's master
IDE name Arduino IDE
Flash Frequency 80Mhz
PSRAM enabled no
Upload Speed 115200
Computer OS Windows 10

Description:
I am doing a project where I want to collect data from different sensors and then display it on my Adafruit IO Dashboard. I have created a separate config.h file where I have stored the WiFi Credentials (in my case I am using Mobile Hotspot as Wifi), and also my Adafruit IO Key.
The code is compiled and uploaded successfully, and in my phone I can see esp32-arduino is connected to my mobile hotspot, nut when I open the Serial Monitor it shows "Connecting....." and also no data is being published on the Adafruit Dashboard

#include "config.h"
#include "max6675.h"
#include "EmonLib.h"

#define CURRENT_CAL 62.6
EnergyMonitor emon1;

#define sound_PIN 34
#define vib_PIN 35
#define smoke_PIN 33
#define current_PIN 39
#define alarm_PIN 25

int thermoDO = 19;
int thermoCS = 23;
int thermoCLK = 5;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

float Normal_Sound_Level= 250;
float Normal_Vib_Level = 5000;
int Normal_Smoke_Level= 20;
int Normal_Temp_Level = 50;
float Normal_Current_Level= 20.00;
float First_Current_Reading=70.00;

boolean is_Relay_on=true;
boolean is_Machine_on=true;
String Machine_Power;
String Machine_Power_Status;
String Alarm_State;
boolean AlarmState=false;
String reason;
int relay_PIN=32;

AdafruitIO_Feed *temperature = io.feed("temperature");
AdafruitIO_Feed *Vibration = io.feed("vibration-intensity");
AdafruitIO_Feed *Smoke = io.feed("smoke-intensity");
AdafruitIO_Feed *Current = io.feed("current");

AdafruitIO_Feed *power = io.feed("power");

void setup() {
pinMode(sound_PIN, INPUT);
pinMode(vib_PIN, INPUT);
pinMode(smoke_PIN, INPUT);
pinMode(current_PIN, INPUT);
pinMode(relay_PIN, OUTPUT);
pinMode(alarm_PIN, OUTPUT);

  Serial.begin(115200);

  while(! Serial);

  Serial.print("Connecting to Adafruit IO");
  io.connect();

power->onMessage(handleMessage);

  while(io.status() < AIO_CONNECTED) {
    Serial.println("Connecting.......");
    Serial.println("If it Takes a Long Time, Check WIFI Username/Password!");
    delay(500);
  }

  Serial.println();
  Serial.println(io.statusText());

  if (is_Relay_on==true){
  power->save(HIGH);
}

 emon1.current(current_PIN, CURRENT_CAL);
}

void loop() {

   io.run();

switch (is_Relay_on) {
    case true:
      digitalWrite(relay_PIN,HIGH);
      Machine_Power="ON";
      AlarmState=false;
      Alarm_State="OFF";

      break;

    case false:
      digitalWrite(relay_PIN,LOW);
      is_Machine_on=false;
      Machine_Power="OFF";
      AlarmState=true;
      Alarm_State="Triggered";

       break;

    default:
      break;
  }

while (( is_Machine_on)==true) {

  float sound_intense = analogRead(sound_PIN);
 if (sound_intense>Normal_Sound_Level){
  is_Relay_on= false;
  reason="((((((Abnormal Sound Values))))))";
}

float Vib_intense = analogRead(vib_PIN);

  if (Vib_intense>Normal_Vib_Level){
  is_Relay_on= false;
  reason="((((((Abnormal Vibration Values))))))";
}

int smoke_intense = analogRead(smoke_PIN);

if (smoke_intense>Normal_Smoke_Level){
 is_Relay_on= false;
 reason="((((((Abnormal Smoke Values))))))";
}

if (thermocouple.readCelsius()>Normal_Temp_Level){
 is_Relay_on= false;
 reason="((((((Abnormal Temperature Values))))))";
}

  emon1.calcVI(20,100);

  float currentDraw   = emon1.Irms-2;
  int supplyVoltage   = 220;

  if (currentDraw<0){
    currentDraw=-currentDraw*0;
  }
else{
  currentDraw=currentDraw;
}

if (currentDraw>=First_Current_Reading){
  currentDraw=0;
}

  if (currentDraw>Normal_Current_Level){
  is_Relay_on= false;
  reason="((((((Abnormal Current Withdrawal Values))))))";
}

Current->save(currentDraw);
temperature->save(thermocouple.readCelsius());
Vibration->save(Vib_intense);
Smoke->save(smoke_intense);

  Serial.println(" ");
  Serial.println("..................................................");
  Serial.println(" ");
  Serial.print("Recieved Machine Power: ");
  Serial.println("ON");
  Serial.println(" ");
  Serial.println("----->Sending----->-----> (((WIFI)))");
  Serial.println(" ");
  Serial.print("Machine Power: "); // Print the voltage.
  Serial.println(Machine_Power); // Print the voltage.
  Serial.print("Alarm State: "); // Print the voltage.
  Serial.println(Alarm_State); // Print the voltage.
  Serial.print("Sound Intensity: "); // Print the voltage.
  Serial.println(sound_intense);
  Serial.print("Vibration Intensity: "); // Print the voltage.
  Serial.println(Vib_intense); // Print the voltage.
  Serial.print("Smoke Density: "); // Print the voltage.
  Serial.println(smoke_intense); // Print the voltage.
  Serial.print("Temperature: ");
  Serial.println(thermocouple.readCelsius());
  Serial.print("Current: ");
  Serial.println(currentDraw);
  Serial.print("Voltage: ");
  Serial.println(supplyVoltage);
  Serial.print("Watts: ");
  Serial.println(currentDraw * supplyVoltage);
  //power->save(HIGH);
 // wait one second (1000 milliseconds == 1 second)

 delay(5000);
 break;
}

if (AlarmState==true) {
 dacWrite(alarm_PIN, 255); // buzzer ON
  delay(600);
  dacWrite(alarm_PIN, 0);
}
else{
  dacWrite(alarm_PIN, 0);
}

while (( is_Machine_on)==false) {

  Serial.println(" ");
  Serial.println("..................................................");
  Serial.println(" ");
  Serial.println(">>>>>>>>>>Stopped Sending<<<<<<<<<<");
  Serial.println(" ");
  Serial.print("Recieved Machine Power: ");
  Serial.println("OFF");
  Serial.print("Machine Power: "); // Print the voltage.
  Serial.println(Machine_Power); // Print the voltage.
  Serial.print("Alarm State: "); // Print the voltage.
  Serial.println(Alarm_State); // Print the voltage.
  Serial.print("Reason: ");
  Serial.print(reason);
  Serial.println(" ");

power->save(LOW);
 delay(1000);
 break;
}

}

void handleMessage(AdafruitIO_Data *data) {
  if(data->toPinLevel() == HIGH){

    Serial.print("Recieved Machine Power: ");
    Serial.println("ON");
       is_Relay_on=true;
         is_Machine_on=true;

  }else{
    Serial.print("Recieved Machine Power: ");
    Serial.println("OFF");
       is_Relay_on=false;
       reason="(((((( Manual Online Shut Down ))))))";

  }
}

This is the config.h:
#define IO_USERNAME    "xyz"
#define IO_KEY         "xyz"
#define WIFI_SSID       "test"
#define WIFI_PASS       "pass"
#include "AdafruitIO_WiFi.h"
AdafruitIO_WiFi io(IO_USERNAME, IO_KEY, WIFI_SSID, WIFI_PASS);

It would help to include all of your code in the question (obfuscate your WiFi and Adafruit credential), or, even better, the minimum code that reproduces the problem. Also, what firmware is running on the ESP?

http://collabedit.com/qfvkd  - You can see the whole code here, cannot paste the whole code in comments because of character limit.

please no code in comments, ever ... add code to the post

Ok I have included the full code as well as that of config.h file.


text:
Smooth Servo movement for robotic arm: An ongoing answer and soluton
This is not and will not be a duplicate.
This is a thread meant to share a solid soliton I figured out with the rest of the community and update it as I optimize it, ad-hoc.
So I had visited StackExchange Arduino community to check if there is a better way to make a servo move smoother, since if we assing a new position to a servo that is attached on an arm, it moves like an attacking karateka.
I found these threads:
Smooth servo control library
(Dat-ha provided a piece of code that I suggest a correction here)
I also checked this:
My Servo Won't Sweep Smoothly
I will self-answer and update this thread, as I make a full arm code working properly and include instructions for the rest of the people to save everyone some time. I still haven't added the capacitor that is suggested on the threads but I will ASAP.

As explained in the answers, the delay function blocks the code from executing until the delay finishes

Your original solution uses blocking code (the for loops with delay() calls in them). Surely that works, but it can easily get you in trouble, when extending the project with more functionalities (since nothing else can be done during the sensor movement). So I would suggest a way to ditch all blocking for loops and delays, so that other code can run during the servo movement. For this we can use millis() and the coding principle from the BlinkWithoutDelay example, that comes with the Arduino IDE.
#include <Servo.h>

Servo servo1;
int set_angle = 0;
int current_angle = 90; // setting starting angle to 90 degrees
unsigned long servo_timestamp = 0;
#define SERVO_INTERVAL    10   // changing the servo position every 10ms, defines the speed of the servo

void setup()
{
    servo1.attach(11);  // connect Servo to pin 11
    pinMode(A0, INPUT); // Connect potentiometer or Joystick x or y pin to A0 input
}

void loop(){
    if(millis()-servo_timestamp > SERVO_INTERVAL){
        servo_timestamp += SERVO_INTERVAL; // increment our timestamp by the servo interval
        // Measure the new set_angle only, if we really want to move the sensor
        int val1 = analogRead(A0); // Read the potentiometer position
        set_angle = map(val1, 0, 1023, 0, 180); // Map the value to be used with servo

        // Increment or decrement the current angle according to the set_angle
        // and don't change it, when we already are at the set_angle
        if(set_angle > current_angle){
            current_angle++;
        } else if(set_angle < current_angle){
            current_angle--;
        }
        // Write the new angle to the servo
        servo1.write(current_angle);
    }
}

For learning more about the non-blocking coding style using millis(), you can google for it and look at the BlinkWithoutDelay example. There are many resources for this on the web. The combination of timestamp and millis() if statement executes the code inside the if statement at the regular interval SERVO_INTERVAL. There we read the potentiometer and calculate the new setpoint for the servo angle. Then we increment or decrement the current angle by 1 depending on the set angle. And then we write that new angle to the servo.
You can change the speed by either changing SERVO_INTERVAL or by in-/decrementing current_angle by more than only 1.
The code outside the if statement still runs at full speed. So in the (a bit less than) 10ms, that the servo code isn't running, you can execute other code. Also this code will react immediately, where a blocking code would first let the servo run to the set position and only then change again.
Note: The above code isn't tested. It's purpose is to show the principle. There might be small errors, that I haven't seen.

Thank you for showing me around. For real. I had no idea this thing existed. So in case we need to do more things than that, my way would be really troublesome indeed, since I would need to add the code in both if statements making it really heavier than it should be.
I think your suggestion is better. Not to mention that this solution makes thing work optimal, while mine is creating delays that WILL interfere with other stuff. When I will find the time I will test it and include your code with reference in the OP. Kudos!

Here are the simulation results of the code from Chrisl

The code (same as the other answer)
#include <Servo.h>

Servo servo1;
int set_angle = 0;
int current_angle = 90; // setting starting angle to 90 degrees
unsigned long servo_timestamp = 0;
#define SERVO_INTERVAL    10   // changing the servo position every 10ms, defines the speed of the servo

void setup()
{
    servo1.attach(11);  // connect Servo to pin 11
    pinMode(A0, INPUT); // Connect potentiometer or Joystick x or y pin to A0 input
}

void loop(){
    if(millis()-servo_timestamp > SERVO_INTERVAL){
        servo_timestamp += SERVO_INTERVAL; // increment our timestamp by the servo interval
        // Measure the new set_angle only, if we really want to move the sensor
        int val1 = analogRead(A0); // Read the potentiometer position
        set_angle = map(val1, 0, 1023, 0, 180); // Map the value to be used with servo

        // Increment or decrement the current angle according to the set_angle
        // and don't change it, when we already are at the set_angle
        if(set_angle > current_angle){
            current_angle++;
        } else if(set_angle < current_angle){
            current_angle--;
        }
        // Write the new angle to the servo
        servo1.write(current_angle);
    }
}

You can tweak the code and see the changes online- Link to the arduino simulation

  #include <Servo.h>
    Servo servo1;
    int previousangle1;
    int dc;
    void setup()
      {
        dc = 10;    // Delay calibration
        servo1.attach(11);  // connect Servo to pin 11
        pinMode(A0, INPUT); // Connect potentiometer or Joystick x or y pin to A0 input
        previousangle1 = 90; // Initialize position to 90 degrees (180 degree servo)
      }

    void loop()
      {

      int val1 = analogRead(A0); // Read the potentiometer position
      int angle1 = map(val1, 0, 1023, 0, 180); // Map the value to be used with servo

      if(angle1>previousangle1)
      {
        for(int i=previousangle1; i<=angle1; i++)
        {
          servo1.write(i); //turn servo by 1 degrees
          delay(dc);        //delay for smoothness
        }
      }
      // Fix: This needed to be an else if
      // Original piece of code had it as a second stand alone if
      else if(angle1<previousangle1)
      {
        for(int j=previousangle1; j>=angle1; j--)
        {
          servo1.write(j);
          delay(dc);
        }
      }
      delay(dc);
      previousangle1 = angle1;
      }

What you need to do now, is make similar code, with different variables for all 4 servos.
I still have to check the addition of a capacitor to make it work even better.
Original code is taken from here:
https://arduino.stackexchange.com/a/29970/76974
I will edit this, adding code for the rest of the servos later on.


text:
Issue communicating with ESP32 (WT32-S1) with my USB FTDI (hw-417-v1.2)
Basically im trying to communicate bewtween my ESP32 (WT32-S1) and my USB FTDI (hw-417-v1.2) when I run it in the Arduino IDE I get the error "Failed to connect to ESP32: Serial data stream stopped: Possible serial noise or corruption." Not too sure why this happens, I've plugged in the WT32 to the FTDI as follows:
WT32 RXD - FTDI TXD
WT32 TXD - FTDI RXD
WT32 GND -  FTDI GND
WT32 5V - FTDI 5V
The FTDI is directly plugged into my PC and I've installed the necessary drivers as far as I know. Fair to mention its communicating serially with my arduino uni using SoftwareSerial. Here is the code ESP32 side:
#include <SoftwareSerial.h>
#define MYPORT_TX 15
#define MYPORT_RX 14

SoftwareSerial myPort(MYPORT_RX, MYPORT_TX);

void setup() {
  Serial.begin(115200);
  myPort.begin(115200);
}

void loop(){
  Serial.println(myPort.read()); // read from software serial interface, write to hardware serial
  myPort.println(Serial.read()); // read from hardware serial interface, write to software serial
}

Code Arduino uno side:
#include <SoftwareSerial.h>

SoftwareSerial serial2(5, 6); // choose pins that are not being used by anything else

void setup() {
  Serial.begin(115200);
  serial2.begin(115200);
}

void loop(){
  Serial.println(serial2.read()); // read from software serial interface, write to hardware serial
  serial2.println(Serial.read()); // read from hardware serial interface, write to software serial
}

The connection from WT32 to Arduino Uno is as follows:
WT32 GND - Uno GND
WT32 IO15 - Uno 5
WT32 IO14 - Uno 6
Main issue as said is the "Failed to connect to ESP32: Serial data stream stopped: Possible serial noise or corruption.", mentioning the rest to give you a full picture.
Cheers!

How did you load that program onto the ESP32 ? Using the same FTDI adaptor ?
The ESP32 is a 3.3 volt device. How are you powering it and what level shifting (if any) are you using between it and the Uno? Are grounds connected between the Uno and the ESP ?

Welcome! I don't suppose you have a 2nd ESP32 that you can try? I sometimes find that if one doesn't work, then another might.

Also, is your IDE set to communicate on 115200 baud? If not, you need to make sure the code matches. Edit: Hmm, though you mention SoftwareSerial works, which is interesting.

6v6gt yes, my ESP32 supports 5.5 volts and you can use both, same with the FTDI, I tried both same result,
Nickbolton i only have one sadly and both are set to 115200 baud, i think this is a hardware issue, buying a new FTDI and new cables

Good luck! Hope that works. Waiting for parts is always the least fun bit.

@PrinceSalmon Can you add a link to your particular ESP32 (WT32-S1) module. This data sheet implies a max voltage of 3.6 volts: http://www.wireless-tag.com/wp-content/uploads/2022/10/WT32-S1-DataSheet-V1.5.pdf

Ive solved my problem, to any other people who have this problem, make sure you use a CP2102 instead, and plug according to this:
CP2101    WT32
TXD ----- RX0
RXD ----- TX0
GND ----- GND
5V  ----- 5V

Then plug the WT32 IO0 pin to GND to enter download mode, I'm personally using an external 5v PS as the WT32 needs quite a lot of power.


text:
What should I do to communicate with GSM module?
Sorry, im a beginner, i tried to program an automatic doorlock using sms. But, I dont understand what happen with this error, what should I do? Add library? The error said that Pstring wasnt declared, but i dont know how to declare this.
#include <LiquidCrystal.h>
#include "SIM900.h"
#include "sms.h"
#include "SoftwareSerial.h"
#include "sms.h"

SMSGSM sms;
boolean started=false;
char buffer[160];
char smsbuffer[160];
char n[20];
int pintu=5;
int buttonState;
int lastButtonState = LOW;
long lastDebounceTime = 0;
long debounceDelay = 50;
boolean st=false;
int buzzer=6;

void setup()
{
  pinMode(pintu,OUTPUT);
  pinMode(buzzer,OUTPUT);

  digitalWrite(pintu,LOW);
 if (gsm.begin(9600))
 {
  started=true;
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
  }
   if(started)
  {
   delsms();
   sms.SendSMS("08970869443","Pintu SMS Menyala");
  }
  else{digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(buzzer,LOW);
  }

   }

   void loop()
   {

   int pos=0;
  if (gsm.begin(9600))
  {
  if (started){
  pos=sms.IsSMSPresent(SMS_ALL);
  if(pos)
  {
   sms.GetSMS(pos,n,smsbuffer,100);
   delay(2000);
    if(!strcmp(smsbuffer,"bukapintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Pintu Dibuka");
    digitalWrite(pintu,HIGH);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    if(!strcmp(smsbuffer,"tutuppintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Kunci Pintu Ditutup");
    digitalWrite(pintu,LOW);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    delsms();
   }
   }
   }
   }

   void delsms()
   {
   for (int i=0; i<10; i++)
  {
     int pos=sms.IsSMSPresent(SMS_ALL);
    if (pos!=0)
   {
    if (sms.DeleteSMS(pos)==1){}else{}
   }
   }
   }

Error message :
     Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

      D:\Kuliah\Project\Skripsi\pintu_sms\pintu_sms.ino: In function 'void loop()':

      pintu_sms:67: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

      pintu_sms:67: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:68: error: 'str' was not declared in this scope

     str.begin();

     ^

    pintu_sms:76: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

    pintu_sms:76: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:77: error: 'str' was not declared in this scope

     str.begin();

     ^

     exit status 1
  'PString' was not declared in this scope

The compiler does not know what PString is. It is not declared in any of the libraries you have included.
You could rewrite to something like this.
strcat(buffer, "Pintu Dibuka");
n = strlen(buffer);
digitalWrite(pintu,HIGH);
sms.SendSMS(n,buffer);

Please change the other block in the same way.
There are more errors. You also need to change "int n[20]" to "int n".
That is a good start.
Cheers!

I tried what you told to me, but still error

or i missed any libraries?

Yes there are more errors of the same type (using PString). You might have intended to include that? Cut-and-pasting code?

Try this library http://arduiniana.org/libraries/PString/.


text:
How to set Delay on GSM shield?
I bought a Gsm module recently(not official arduino shield) and i connect it to Arduino uno. The problem (I guess) is , i can't set delay properly, the terminal send it too fast that i missed it or too slow even i set its baud rate to 4800 (I have tried it with many baud from 4800-to-115200).
I uploaded the code to Git ,with this address.
More details: For example when i enter d in terminal it act like this message came up : +CMTI: "SM",3 and it want to save it but it miss plus at first of it and it save CMTI: "SM",3,
After that it perform this : AT+CMGR=3 the terminal show the message in half size : +CMGR: "REC UNREAD","+9*********2","H/E.3D/1","16/02/28,00:27:02+14" which totally missed body part.
The weird thing is when i put some println on the program it miss more characters , and second weird thing is it missed more character in second run or i push d again.
I have tried to change the delays but no success.How can i fix it ? any help would be appreciated.
Edit:
If i make it simpler, when i use these code i get half message :
#include <SoftwareSerial.h>
SoftwareSerial serialGPRS(7, 8);
void setup()
{
  Serial.begin(19200);
  serialGPRS.begin(19200);
}
void loop()
{
  serialGPRS.println("AT+CMGR=1");
  delay(1000);
  while(serialGPRS.available()!=0)
    Serial.write(serialGPRS.read());
}

like: +CMGR: "REC READ","+9*******",".H/E.3D/1

The SoftwareSerial receive buffer is getting filled up and discarding characters. You are not reading fast enough from the buffer. Adding Serial.println() will slow down your reading even more. The simplest solution to this is to increase the size of the SoftwareSerial buffer from its default size of 64 bytes to 256 bytes (or smaller, depending on what works for you).
On a Windows PC, go to C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial. Open SoftwareSerial.h and change the line:
#define _SS_MAX_RX_BUFF 64 // RX buffer size

to
#define _SS_MAX_RX_BUFF 256 // RX buffer size

Save the file and try your sketch again.

It took so long so i changed the code, And there is no way i can test it ,but thank you.(I cant test it but i click it as accept).


text:
Arduino Mega as a EEPROM Programmer for Winbond W29EE011 memories
I'm trying to use my Arduino Mega as an EEPROM memory writer. For this project, besides my Arduino Mega, I use an SD Card module, an LCD display and two push buttons to handle the events. Inside the SD card I have the binary files to be written into the EEPROM.  Except for the burning process, my sketch seems to be correct. The user selects the memory size option (I'm only using the total memory size of 128kb), the file is written into the EEPROM. Apparently, the file is written. But when I use my other sketch to check the data written into the EEPROM, on the serial monitor, I only see bytes like FF and 0. Nothing else.
I think my problem is really in the process of writing the bytes, because of poor handling of the Output Enable, Chip Select and Write Enable pins. My data and address pin configuration, follows the logic of the Arduino Mega's port handling. PORT as the data pins and PORTC, PORTL and PORTG as the address pins. I will call the data pins dbit and the address pins abit, right? so, following this idea, my configuration with the Arduino Mega's ports looks like this:
Data pins:
dbit0 = 22,
dbit1 = 23,
dbit2 = 24,
dbit3 = 25,
dbit4 = 26,
dbit5 = 27,
dbit6 = 28,
dbit7 = 29.
Address pins:
abit0 = 37,
abit1 = 36,
abit2 = 35,
abit3 = 34,
abit4 = 33,
abit5 = 32,
abit6 = 31,
abit7 = 30,
abit8 = 49,
abit9 = 48,
abit10 = 47,
abit11 = 46,
abit12 = 45,
abit13 = 44,
abit14 = 43,
abit15 = 42,
abit16 = 41.
Here is the EEPROM writer code.(UPDATED)
  #include <avr/pgmspace.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>

unsigned long addr = 0;

int oe = 9;
int cs = 10;
int we = 11;

unsigned long fileSize = 0;

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

pinMode(we, OUTPUT);
  pinMode(cs, OUTPUT);
  pinMode(oe, OUTPUT);
 digitalWrite(we, HIGH);
  digitalWrite(oe, HIGH);
  digitalWrite(cs, HIGH);
 DDRA = B11111111;
  PORTA = 0x00;

  DDRL = B11111111;
  PORTL = 0x00;

  DDRC = B11111111;
  PORTC = 0x00;

  DDRG = B11111111;
 PORTG = 0x00;

Serial.println("Now, erasing chip...");
DDRA = B11111111;
 delayMicroseconds(700);
 writeEEPROM(0x5555, 0xaa);
 writeEEPROM(0x2aaa, 0x55);
 writeEEPROM(0x5555, 0x80);
writeEEPROM(0x5555, 0xaa);
writeEEPROM(0x2aaa, 0x55);
writeEEPROM(0x5555, 0x10);
delayMicroseconds(50);

  delay(2500);

 Serial.println("All right! all done!");
    delay(2500);
     Serial.println("EEPROM Size will set to 0x2."); // just for test
 delay(2500);

PORTA = 0;
  PORTC = 0;
  PORTL = 0;
 PORTG = 0;

  }

  void loop(){

 dumpAndburn();
 while(1);// don't call this function anymore!!!!!!
  }// void loop

   void dumpAndburn(){

fileSize = 0x2; // just for test
  digitalWrite(oe, HIGH);
  digitalWrite(we, HIGH);

 while (addr < fileSize){/*

    https://www.dataman.com/dataman-eprom-memory-size-chart */

protect(); // is this right?
  writeEEPROM(addr, 0Xa5);// test
addr++;

}

  digitalWrite(oe, HIGH);
  digitalWrite(we, HIGH); //write disable
  digitalWrite(cs, HIGH);

  Serial.println("The process is done. Please, turn off the hardware.");

    }//void dumpAndburn

void writeEEPROM(int adr, byte values) {

  digitalWrite(oe, HIGH); // output disable
  delayMicroseconds(0.01);
  PORTA = values;  // this is the DATA
  //delayMicroseconds(0.05);
  PORTC = lowByte(adr); // lower byte of the address (first 8 bits)
  PORTL = highByte(adr); // upper byte of the address (only 5 bits are used, the address is a 13 bit number)
 PORTG = highByte(adr); // upper byte of the address (only 5 bits are used, the address is a 13 bit number)
  delayMicroseconds(0.05);
  digitalWrite(cs, LOW);  //  |CE goes LOW  // Chip enable
 delayMicroseconds(0.07);

   digitalWrite(we, LOW);  //  |WE goes LOW  // Write enable

  delayMicroseconds(0.07);
  digitalWrite(we, HIGH); //  |WE goes HIGH // Write disable
  delayMicroseconds(0.15);
  digitalWrite(cs, HIGH); //  |CE goes HIGH // Chip disable

}

void protect(){
  DDRA = B11111111; // set portA as outputs.
 delayMicroseconds(700);
   writeEEPROM (0x5555, 0xAA);
  writeEEPROM (0x2AAA, 0x55);
   writeEEPROM (0x5555, 0xA0);
    delayMicroseconds(10);

  }

Here is the EEPROM read code.
#include <avr/pgmspace.h> //necessário para Wire.h
#include <Wire.h>  //necessária, por conta do I2C
#include <SPI.h>

int oe = 9;
int cs = 10;
int we = 11;

void setup()
{

  int adr = 0;

pinMode(we, OUTPUT);
  pinMode(cs, OUTPUT);
  pinMode(oe, OUTPUT);
  digitalWrite(we, HIGH);
  digitalWrite(oe, HIGH);
  digitalWrite(cs, HIGH);
 DDRA = B00000000;
  PORTA = 0x00;

  DDRL = B00000000;
  PORTL = 0x00;

  DDRC = B00000000;
  PORTC = 0x00;

DDRG = B00000000;
PORTG = 0x00;

  Serial.begin(115200);
  for(int z=0; z<2; z++){
    delay(1000);
    }

printContents();
  }

  void loop(){

  }

byte readValue (int adr) {
  digitalWrite(we, HIGH); // disable write mode
  PORTC = lowByte(adr); // lower byte of the address (first 8 bits)
  PORTL = highByte(adr);// upper byte of the address (only 5 bits are used, the address is a 13 bit number)
 PORTG = highByte(adr);

  digitalWrite(oe, LOW);
  PORTA = 0;
  byte r = 0;

  delay(1); // we need a little delay to switch from input to output (at least 500 microseconds)
   digitalWrite(we, HIGH);
  digitalWrite(cs, LOW);
  //delayMicroseconds(0.09);
  digitalWrite(oe, LOW);
 // delayMicroseconds(0.045);

  // read the data
  r = PINA;
digitalWrite(we, HIGH);
  delayMicroseconds(1);
  digitalWrite(cs, HIGH);
  digitalWrite(oe, HIGH);
 // delayMicroseconds(0.09);
  return r;
}

void printContents() {
    DDRA = B00000000; //  portA as Inputs ports
  delayMicroseconds(500);
 int adr = 0;
byte value = 0;
byte checkValue;

//adr*=128;//test

while (adr < 0x2 ) { // 0x2 just for tests
    checkValue = readValue (adr);

Serial.print(adr, HEX); Serial.print(" : "),Serial.println(checkValue, HEX);
  adr++;
}

}

Here is the link to the memory datasheet.
link
And when I try to see the content, I get the following results:
0 : 0
1 : 0

why can't retrieve 0: A5 1: A5 ?
Please guys, help me.
Any help will be greatly appreciated.
Thank you.
Best wishes.

Timing is absolutely critical when writing that kind of EEPROM. Your serial prints will be breaking that timing, and you must think in 128 byte pages - load a page at the right speed then delay the right amount of time to trigger a write.

@Majenko , I really appreciate your comment. Thanks a lot! I think I will try to use a char buffer of 128, change the byte writing and see if I get any results.  Thank you very much for this important information.

@jsotola, I'm really sorry about this, but, I can't do it now. I'm going to my house. I need to do this with my notebook. Sorry. Thank you.

Dear friends, I have made an update to the code. I took out the serial printing of the bytes to be written. I based this on a Serial EEPROM design. I created a 128 byte buffer. But is my reasoning correct? because I still don't get the bytes that seem to be written into memory.

If you read the datasheet (page 6) carefully, you will see that "The W29EE011 is shipped with the software data protection enabled. To enable the software data protection scheme, perform the three-byte command cycle at the beginning of a page load cycle", what this means is that you need to write 0xAA to addr 0x5555, 0x55 -> 0x2AAA, and '0xA0->0x5555` before you write the address you want to access first.

BTW, you should format your code and shorten you code when post your question, if your problem is about EEPROM, all the codes about display, button are not relevant.

Thank you, Sir @hcheung, I will try to perform the byte command cycle.

Dear Friends. I have updated my code(and also formatted it). But I still have the same problems. What could I be doing wrong?


text:
Arduino crashing during serial print
I am trying to determine why my Arduino MKR NB 1500 code keeps crashing when the serial monitor is open and I look for data. I removed the string functions to prevent it from causing memory fragmentation, but does not seems to have helped.
#include <ArduinoMqttClient.h>
#include <MKRNB.h>

// Please enter your sensitive data in the Secret tab or arduino_secrets.h
// PIN Number
const char PINNUMBER[]     = "";

// MQTT Broker and Port
const char broker[] = "test.mosquitto.org"; //
int        port     = 1883;

// Pub/Sub Topics - Make it something unique since we are using a public broker
const char subscribeTopic[]  = "channel";
const char publishTopic[]  = "channel";

// To connect with SSL/TLS:
// 1) Change NBClient to NBSSLClient.
// 2) Change port value from 1883 to 8883.
// 3) Change broker value to a server with a known SSL/TLS root certificate
//    flashed in the WiFi module.

NBClient client;
GPRS gprs;
NB nbAccess;
MqttClient mqttClient(client);

int LED = 6; // Onboard LED

// Publish interval
long previousMillis = 0;
long interval = 2000;

void setup() {
    pinMode(LED_BUILTIN, OUTPUT); // Set built in LED pinMode

    //Initialize serial and wait for port to open:
    Serial.begin(9600);
    /* while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }*/

    // attempt to connect to GSM and GPRS:
    Serial.print("Attempting to connect to GSM and GPRS");
    // connection state
    bool connected = false;

    // After starting the modem with GSM.begin()
    // attach the shield to the GPRS network with the APN, login and password
    while (!connected) {
        if ((nbAccess.begin(PINNUMBER) == NB_READY) &&
                (gprs.attachGPRS() == GPRS_READY)) {
            connected = true;
        } else {
            Serial.println("Not connected");
            delay(1000);
        }
    }

    Serial.println("You're connected to the network");
    Serial.println();

    Serial.print("Attempting to connect to the MQTT broker: ");
    Serial.println(broker);

    if (!mqttClient.connect(broker, port)) {
        Serial.print("MQTT connection failed! Error code = ");
        Serial.println(mqttClient.connectError());

        while (1)
            ;
    }

    Serial.println("You're connected to the MQTT broker!");
    Serial.println();

    // set the message receive callback
    mqttClient.onMessage(onMqttMessage);

    Serial.print("Subscribing to topic: ");
    Serial.println(subscribeTopic);
    Serial.println();

    // subscribe to a topic
    mqttClient.subscribe(subscribeTopic);

    Serial.print("Waiting for messages on topic: ");
    Serial.println(subscribeTopic);
    Serial.println();
}

void loop() {
    unsigned long currentMillis = millis();

    // call poll() regularly to allow the library to receive MQTT messages and
    // send MQTT keep alives which avoids being disconnected by the broker
    mqttClient.poll();

    // Enforce Interval
    if (currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;

        // Call a function that handles publishing message
        publishSensorVal();
    }
}

void publishSensorVal() {
    // read the first Analog pin
    int sensorVal = analogRead(0);
    //String speak = "The sensor val is " + String(sensorVal);
    char adc_sv[30] = { 'T', 'h', 'e', ' ', 'a', 'd', 'c', ' '' ', 'v', 'a', 'l', 'u', 'e', ' ', 'i', 's', ' ', '\0' }; //adc_step value
    // Publish our sensor value to the publish topic
    mqttClient.beginMessage(publishTopic);
    mqttClient.print(adc_sv);
    mqttClient.print(sensorVal);
    mqttClient.endMessage();
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1400);                       // wait for a second
    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
    delay(100);                       // wait for a second
}

void handleCommand(String cmd) {
    if (cmd == "on") {
        digitalWrite(LED, HIGH);
    } else if (cmd == "off") {
        digitalWrite(LED, LOW);
    }
}

void onMqttMessage(int messageSize) {
    // we received a message, print out the topic and contents
    Serial.println("Received a message with topic '");
    Serial.print(mqttClient.messageTopic());
    Serial.print("', length ");
    Serial.print(messageSize);
    Serial.println(" bytes:");

    // We want to read each character into a useable String
    String content = "";
    char character;

    // use the Stream interface to print the contents
    while (mqttClient.available()) {
        character = (char)mqttClient.read();
        content.concat(character);
    }

    handleCommand(content); // This function does something with our incoming string

    Serial.println(content);
    Serial.println();
    Serial.println(); // double spacing
}

The output looks as follows when it gets stuck:

I still have memory left on the arduino which should not be the reason for the crash:
Sketch uses 41676 bytes (15%) of program storage space. Maximum is 262144 bytes.
Global variables use 3456 bytes (10%) of dynamic memory, leaving 29312 bytes for local variables. Maximum is 32768 bytes.

how do you know it crashes?

it stops printing data in the serial monitor. I reopened the serial monitor even after that there was no info on it. I reset it fixes the issue.

Where exactly does it stop printing? In the middle of a message? Or inbetween messages? Btw: For defining adc_sv you don't need to set each character like an array element. char adc_sv[30] = "The adc value is "; does exactly the same and is easier to understand.

If it stops sending on the serial line, does it still blink the LED?

The devices prints complete message and then stops. Have never seen where it stopped in between printing a message on the serial monitor

Change the while (mqttClient.available()) loop where it using String.concat() function, it is likely causing heap fragmentation.

@hcheung: I am trying to send 0 to turn off the LED and 1 to turn on the LED and I modified the section to get the data in just char and the handle command to accept char but that leads to the error: ISO C++ forbids comparison between pointer and integer [-fpermissive].

here is the modified snippet:      char character;
// use the Stream interface to print the contents
while (mqttClient.available()) {
character = (char)mqttClient.read();
//content.concat(character);
}
handleCommand(character)

void handleCommand(char cmd) {
if (cmd == "1"){
digitalWrite(LED, HIGH);
}else if(cmd == "0"){
digitalWrite(LED, LOW);
}
}

For comparison of a char, it should be cmd='1', notice the difference between single quote and double quote? if you want to compare with an array or c-style string, you need to learn on how to use  functions such as 'strstr()orstrcmp()`.

{ 'T', 'h', 'e', ' ', 'a', 'd', 'c', ' '' ',  You appear to have a pair of adjacent character literals in your code.  So far as I know this isn't valid. So, you want to check your post for errors in pasting.

yeah i fixed that after I complied the code.

Maybe you can try SafeString https://www.forward.com.au/pfod/ArduinoProgramming/ArduinoStrings/index.html#stringvchar


text:
Problem with DC motor
I've got a circuit with Arduino UNO Rev3, DC motor, button to switch direction of rotation and potentiometer to regulate revs. The problem is that usually when I increase voltage using potentiometer, motor doesn't want to start rotating by itself and it does only when I move its shaft with finger or when I press the button again. I would undrestand that it can be due to friction and that's why moving shaft with finger helps, but why does motor start rotating when I press the button changing direction?
Here is my circuit:

And here is my code:

Please see why we shouldn't post images of text. We don't know much about your motor or how the motor is interfaced to the Arduino.

I might not drive the motor directly off the Arduino like that; even a wee motor can draw more current than the Arduino can handle.

Disconnect that circuit immediately - you are damaging your Arduino

Firstly, you need a motor driver to drive a motor from an Arduino. You cannot drive it directly from IO pins.
Secondly by using a potentiometer like that for controlling the speed you are massively starving the motor of power (not that the Arduino can provide such power, and if it could then the potentiometer would smoke).
Your design should be:

Potentiometer into an analog input to control the speed using PWM
Outputs from the Arduino to control the direction (GPIO x 2) and speed (PWM) to a motor driver (L293 is commonly available)
Motor connected to the motor driver
Power supply suitable for your motor connected to the motor driver

There are many many examples on the web that show you this kind of circuit. Follow one.

Thanks for the answer, but I would like to regulate motor speed manually not by changing PWM value in the program.

Then you need a motor driver that will take an analogue input. You can't just slap a potentiometer in there and hope it'll work.

Thanks, I'll try it. Fortunately I've got L293d.

@Macios216 "Regulating it manually" and "changing PWM values" are separate issues--the means of determining the PWM value is arbitrary. Take the pot value and map it to the PWM value.

First of all, disconnect your Motor which is directly connected to your UNO if you want your Board to be safe and sound.
Arduino or any other microcontroller ICs are not made for directly running High powered loads.
The work of a microcontroller is to produce signals which must be run through a transistor or an IC amplification method to drive high loads.
You are running the Motor directly from UNO pins. What wrong may it go?

If your motor consumes current more than 20mA then the pin where you connected the arduino is to heat up and will burn if you continue further.
Let's suppose your motor consumes current less than 20mA, still it has a high risk that a motor sometimes creates very high voltage and current surge in a specific condition.

If you continue to do so, you will end up burning those pin completely.
So what befits your project seems to be a motor driver IC like L293D or L298N
Instead of a motor,  connect Motor Driver IC logic level input to digital output pin 3 and 4 of Arduino then connect a motor to the output of the Motor Driver IC
More about these ICs can be found in Datasheets


text:
Serial communication problems
When I run this script serial communication just stops after a random period of time. There is no error it just stops outputting data and does not respond to inputs in IDE. Does anyone know a fix for this?. This is not an IDE issue as serial communication also stops without any reported error when reading serial in a python script.
// mpu9250 stuff
#include <MPU9250_WE.h>
#include <Wire.h>
#define MPU9250_ADDR 0x68
MPU9250_WE myMPU9250 = MPU9250_WE(MPU9250_ADDR);
// motor stuff
#include <AFMotor.h>
AF_DCMotor motorA(1);
AF_DCMotor motorB(2);
int lf;
int rf;
void setup() {
  Serial.begin(115200);
  Serial.setTimeout(10);
  // compass stuff
  Wire.begin();
  if(!myMPU9250.init()){
    Serial.println("MPU9250 does not respond");
  }
  else{
    Serial.println("MPU9250 is connected");
  }
  if(!myMPU9250.initMagnetometer()){
    Serial.println("Magnetometer does not respond");
  }
  else{
    Serial.println("Magnetometer is connected");
  }

  Serial.println("Position you MPU9250 flat and don't move it - calibrating...");
  delay(1000);
  myMPU9250.autoOffsets();
  Serial.println("Done!");
  myMPU9250.setSampleRateDivider(5);
  myMPU9250.setAccRange(MPU9250_ACC_RANGE_2G);
  myMPU9250.enableAccDLPF(true);
  myMPU9250.setAccDLPF(MPU9250_DLPF_6);
  myMPU9250.setMagOpMode(AK8963_CONT_MODE_100HZ);
  delay(200);

  // motors
  motorA.setSpeed(50);
  motorB.setSpeed(50);
  motorA.run(RELEASE);
  motorB.run(RELEASE);

}

void loop() {
  xyzFloat angles = myMPU9250.getAngles();
  xyzFloat magValue = myMPU9250.getMagValues();
  Serial.print(magValue.x);
  Serial.print(",");
  Serial.print(magValue.y);
  Serial.print(",");
  Serial.print(magValue.z);
  Serial.print(",");
  Serial.print(angles.x);
  Serial.print(",");
  Serial.println(angles.y);

  //motors
  if (Serial.available()>0){
    String ser = Serial.readString();
    String left = (split(ser, '.', 0));
    String right = (split(ser, '.', 1));
      if (ser.length() > 0){
        int lf = left.toInt();
        int rf = right.toInt();
        Serial.print(lf);
        Serial.print("   ");
        Serial.println(rf);
        motorA.setSpeed(lf);
        motorB.setSpeed(rf);
        if (lf > 0){
          motorA.run(BACKWARD);
          }
        if (lf == 0){
          motorA.run(RELEASE);
          }
        if (lf < 0){
          motorA.run(FORWARD);
          }
        if (rf > 0){
          motorB.run(BACKWARD);
          }
        if (rf == 0){
          motorB.run(RELEASE);
          }
        if (rf < 0){
          motorB.run(FORWARD);
          }
    }
  }

  if(!Serial) {  //check if Serial is available... if not,
    Serial.end();      // close serial port
    delay(10);
    Serial.begin(115200); // reenable serial again
    Serial.println("reset");
  }

}
String split(String data, char separator, int index)
{
    // spliting a string and return the part nr index
    // split by separator

    int stringData = 0;        //variable to count data part nr
    String dataPart = "";      //variable to hole the return text

    for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time

      if(data[i]==separator) {
        //Count the number of times separator character appears in the text
        stringData++;

      }else if(stringData==index) {
        //get the text when separator is the rignt one
        dataPart.concat(data[i]);

      }else if(stringData>index) {
        //return text and stop if the next separator appears - to save CPU-time
        return dataPart;
        break;

      }

    }
    //return text if this is the last part
    return dataPart;
}

You're turning your heap into swiss cheese with all that String abuse.

And here is the obligatory Majenko blog entry about the Evils of Arduino Strings.

add the serial output to your question.