text:
Is there a way for keypad to stop the buzzer while it is running?
I am new to arduino, currently I am looking for a way to make the keypad able to stop the buzzer making a siren alarm when password are keyed in wrong and able to move into password screen by pressing any button on the keypad. From all the videos i have seen, only 1 fits the way i want it to work.
https://www.hackster.io/thehack904/motion-sensing-alarm-with-keypad-password-53f05c
Below is the code I have completed with but i want to try adding a siren alarm function that is able to stop using keypad. Can anyone please teach me how to use a keypad to stop the buzzer and move into master key screen.
//Libraries
#include <LiquidCrystal.h>
#include <Keypad.h>

/*-------------------------------KEYPAD---------------------------------------*/
const byte numRows = 4; //number of rows on the keypad
const byte numCols = 4; //number of columns on the keypad
char keypressed;
char keymap[numRows][numCols] =
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
//Code that shows the the keypad connections to the arduino terminals
byte rowPins[numRows] = {2, 3, 4, 5};//Rows 0 to 3
byte colPins[numCols] = {6, 7, 8, 9};//Columns 0 to 3
//initializes an instance of the Keypad class
Keypad myKeypad = Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);

/*-------------------------------CONSTANTS------------------------------------*/
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5); //LCD
const int buzzer = 10;        //Buzzer/small speaker
int solenoidPin = 11;         //Solenoid

/*-------------------------------VARIABLES------------------------------------*/
String password = "0"; //Variable to store the current password
String master_key = "999"; //Variable to store the master key
String tempPassword = ""; //Variable to store the input password
int doublecheck;    //Check twice the new passoword
boolean armed = false;  //Variable for system state (armed:true / unarmed:false)
boolean input_pass;   //Variable for input password (correct:true / wrong:false)
boolean storedPassword = true;
boolean changedPassword = false;
boolean checkPassword = false;
int i = 1; //variable to index an array
unsigned char WrongAttempts = 0; //global variable to keep the number of wrong attempts done at the code.

/*----------------------------------------------------------------------------*/
void setup() {
  lcd.begin(16, 2); //Setup the LCD's number of columns and rows
  pinMode(solenoidPin, OUTPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(9600);
}

void loop() { //Main loop
  unlockTheDoor();
}
/********************************FUNCTIONS*************************************/
void unlockTheDoor() {
lockAgain: //goto label
  digitalWrite(solenoidPin, HIGH);       //Switch Solenoid OFF
  tempPassword = "";
  lcd.clear();
  i = 6;
  noTone(buzzer);
  while (!checkPassword) {
    lcd.setCursor(0, 0);
    lcd.print("Open the door:  ");
    lcd.setCursor(0, 1);
    lcd.print("PASS>");
    keypressed = myKeypad.getKey();   //Read pressed keys
    if (keypressed != NO_KEY) {   //Accept only numbers and * from keypad
      if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
          keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
          keypressed == '8' || keypressed == '9' ) {
        tempPassword += keypressed;
        lcd.setCursor(i, 1);
        lcd.print("*");       //Put * on lcd
        i++;
        tone(buzzer, 800, 200); //Button tone
      }
      else if (keypressed == 'A') {
        changePassword();
        goto lockAgain;
      }
      else if (keypressed == 'D') {
        break;
      }
      else if (keypressed == '*') { //Check for password
        if (password == tempPassword) { //If it's correct...
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("Correct Password");
          lcd.setCursor(0, 1);
          lcd.print("Door is unlocked");
          tone(buzzer, 100);   //Play a tone while door is unlocked
          delay(100);        // ...for 0.1 sec
          noTone(buzzer);     // Stop sound...
          digitalWrite(solenoidPin, LOW);      //Switch Solenoid ON
          delay(5000);
          WrongAttempts = 0;
          changePassword(); {
            setLocked (true); ///.......to lock again
            tone(buzzer, 1000); // Send 1KHz sound signal...
            delay(100);        // ...for 0.1 sec
            noTone(buzzer);     // Stop sound...
            delay(1000);
            lcd.clear();
            goto lockAgain;
          }
          if (keypressed == '#') {
            setLocked (true); ///.......to lock again
            tone(buzzer, 1000); // Send 1KHz sound signal...
            delay(100);        // ...for 0.1 sec
            noTone(buzzer);     // Stop sound...
            delay(1000);
            lcd.clear();
            goto lockAgain;
          }
        }
        else {           //if it's false, retry
          tempPassword = "";
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("*Wrong Password*");
          tone(buzzer, 500, 200);
          delay(300);
          tone(buzzer, 500, 200);
          delay(300);
          WrongAttempts++;  //ADDED
          Attempts();
        }
      }
    }
  }
}

//Change current password
void changePassword() {
retry: //label for goto
  tempPassword = "";
  lcd.clear();
  i = 1;
  while (!changedPassword) {      //Waiting for current password
    keypressed = myKeypad.getKey();   //Read pressed keys
    lcd.setCursor(0, 0);
    lcd.print("CURRENT PASSWORD");
    lcd.setCursor(0, 1);
    lcd.print(">");
    if (keypressed != NO_KEY) {
      if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
          keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
          keypressed == '8' || keypressed == '9' ) {
        tempPassword += keypressed;
        lcd.setCursor(i, 1);
        lcd.print("*");
        i++;
        tone(buzzer, 800, 200);
      }
      else if (keypressed == '#') {
        break;
      }
      else if (keypressed == 'D') {
        goto retry;
      }
      else if (keypressed == '*') {
        i = 1;
        if (password == tempPassword) {
          storedPassword = false;
          tone(buzzer, 500, 200);
          newPassword();          //Password is corrent, so call the newPassword function
          break;
        }
        else {              //Try again
          tempPassword = "";
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("*Wrong Password*");
          tone(buzzer, 500, 200);
          delay(300);
          tone(buzzer, 500, 200);
          delay(300);
          WrongAttempts++;  //ADDED
          Attempts();
          goto retry;
        }
      }
    }
  }
}

String firstpass;
//Setup new password
void newPassword() {
retry: //label for goto
  tempPassword = "";
  changedPassword = false;
  lcd.clear();
  i = 1;
  while (!storedPassword) {
    keypressed = myKeypad.getKey();   //Read pressed keys
    if (doublecheck == 0) {
      lcd.setCursor(0, 0);
      lcd.print("SET NEW PASSWORD");
      lcd.setCursor(0, 1);
      lcd.print(">");
    }
    else {
      lcd.setCursor(0, 0);
      lcd.print("One more time...");
      lcd.setCursor(0, 1);
      lcd.print(">");
    }
    if (keypressed != NO_KEY) {
      if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
          keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
          keypressed == '8' || keypressed == '9' ) {
        tempPassword += keypressed;
        lcd.setCursor(i, 1);
        lcd.print("*");
        i++;
        tone(buzzer, 800, 200);
      }
      else if (keypressed == '#') {
        break;
      }
      else if (keypressed == 'D') {
        goto retry;
      }
      else if (keypressed == '*') {
        if (doublecheck == 0) {
          firstpass = tempPassword;
          doublecheck = 1;
          newPassword();
        }
        if (doublecheck == 1) {
          doublecheck = 0;
          if (firstpass == tempPassword) {
            i = 1;
            firstpass = "";
            password = tempPassword; // New password saved
            tempPassword = ""; //erase temp password
            lcd.setCursor(0, 0);
            lcd.print("PASSWORD CHANGED");
            lcd.setCursor(0, 1);
            lcd.print("----------------");
            storedPassword = true;
            tone(buzzer, 500, 400);
            delay(2000);
            lcd.clear();
            break;
          }
          else {
            firstpass = "";
            newPassword();
          }
        }
      }
    }
  }
}

void setLocked(int locked) {
  if (locked) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("*** LOCKED ***");
  }
  else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("*** UNLOCKED ***");;
  }
}

void Attempts() {
  if (WrongAttempts >= 3) { //UPS....
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("TO UNLOCK PLEASE");
    lcd.setCursor(0, 1);
    lcd.print("INPUT MASTER KEY");
    digitalWrite(buzzer, HIGH);
    delay (5000);
    master();
  }
}

void master() {
lockAgain: //goto label
retry: //label for goto
  tempPassword = "";
  lcd.clear();
  i = 6;
  noTone(buzzer);
  while (!checkPassword) {
    lcd.setCursor(0, 0);
    lcd.print("***MASTER KEY***");
    lcd.setCursor(0, 1);
    lcd.print(">");
    keypressed = myKeypad.getKey();   //Read pressed keys
    if (keypressed != NO_KEY) {   //Accept only numbers and * from keypad
      if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
          keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
          keypressed == '8' || keypressed == '9' ) {
        tempPassword += keypressed;
        lcd.setCursor(i, 1);
        lcd.print("*");       //Put * on lcd
        i++;
        tone(buzzer, 800, 200); //Button tone
      }
      else if (keypressed == 'D') {
        goto retry;
      }
      else if (keypressed == '*') { //Check for password
        if (master_key == tempPassword) { //If it's correct...
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("Correct Password");
          lcd.setCursor(0, 1);
          lcd.print("Door is unlocked");
          tone(buzzer, 100);   //Play a tone while door is unlocked
          delay(100);        // ...for 0.1 sec
          noTone(buzzer);     // Stop sound...
          digitalWrite(solenoidPin, LOW);      //Switch Solenoid ON
          delay(5000);
          WrongAttempts = 0;
          changePassword(); {
            setLocked (true); ///.......to lock again
            tone(buzzer, 1000); // Send 1KHz sound signal...
            delay(100);        // ...for 0.1 sec
            noTone(buzzer);     // Stop sound...
            delay(1000);
            lcd.clear();
            unlockTheDoor();
          }
          if (keypressed == '#') {
            setLocked (true); ///.......to lock again
            tone(buzzer, 1000); // Send 1KHz sound signal...
            delay(100);        // ...for 0.1 sec
            noTone(buzzer);     // Stop sound...
            delay(1000);
            lcd.clear();
            unlockTheDoor();
          }
        }
        else {           //if it's false, retry
          tempPassword = "";
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("*Wrong Password*");
          tone(buzzer, 500, 200);
          delay(300);
          tone(buzzer, 500, 200);
          delay(300);
          WrongAttempts++;  //ADDED
          Attempts();
        }
      }
    }
  }
}

Almost always for these types of questions the answer is to use a state machine.  Basically you endlessly loop checking if inputs have occurred which will move you to a different state.  And, as much as it might pain you, YOU SHOULD NOT USE DELAYS in a state machine.  State machines are not usually the 1st project a new programmer should tackle.  But if you want, I can make a more formal attempt at explaining a state machine in an answer below.

Yes, please. Thank you.

Ok, keep in mind not many here will write complete software solutions as an answer.  My self included.  What most will do is to explain or point to resources to answer the question.  I will essentially tell you to start over and completely define what you want to do then write your own code using a state machine.  Hence why I said this is not necessary the best approach for a new programmer.

I have to say, now that I read the questions several times, it is not clear what you want to do. I think, you want to stop the buzzer from ever making noise.  Hows about just removing it from the project?

you have the wrong idea about the interaction between a microcontroller, a keypad and a siren .... the siren is never controlled by the kepad ... it is always controlled by the microcontroller .... the keypad only supplies keypresses to the microcontroller ... what is done as a result of those keypresses is determined by the program ... so, all you need is to detect a sequence of kepresses .... whether the siren is active during those keypresses is irrelevant to the detection of the key sequence .... start by writing a key sequence detect program

My plan was to create a siren alarm using buzzer, and after 3 unsuccessful attempts the siren will activate until a keypad button was pressed. And it will stop the alarm and direct the screen to enter password function. Everything is working perfectly without the siren, but I do wish I could make it happen.

So ANY keypress should silence the alarm? Briefly, or indefinitely? It might make sense to silence the alarm to give the user a chance to enter a correct password, and then re-activate the alarm if they fail again. You need to describe what you want to do in detail before you can hope to implement it however.

Making it briefly is better like a count down of 10 seconds. If password incorrect just go back into alarm state again. I did not thought of this part.

Consider defining exactly what you want your Arduino application to do using a state machine approach.  Drafting a state machine diagram allows a developer to visualize the inputs to the state machine, the number & types of states necessary and the outputs of the state machine.  The following diagram from the above wikipedia.org link has two states:

A "Locked" and an "Unlocked" state.  You see that a "Coin" is necessary to change from the "Locked" to the "Unlocked" state.
For the number-coded-lock in the question there are likely many more state to consider.  For instance, there may be a state for each button number entered.  The correct number will advance to the next state.  The incorrect number will revert to the state where the state machine expects to see the 1st number in the code.  If all the numbers in the code have been entered correctly, the last state will likely be the state that unlocks the device. A buzzer may have a state of its own.  While in the buzzer state the buzzer will be making noise.  An input to the state machine indicating that 1/2 second has elapsed could be used to exit from the buzzer state.
In this way any desired behavior can be created.  In addition, by using a state diagram, the intentions of the final program are made clear.  And any logical errors are exposed before code creation.


text:
Function pointer call results in InstrFetchProhibited (ESP32)
I have the following issue which I'm unable to resolve by myself. Perhaps one of you could point me to issues in my code which I don't see.
There is a class called communicator which handles an MQTT connection. I use PubSubClient as a MQTT client. The constructor of communicator looks like the following. Besides connection arguments, it also receives an array of structs SubscriptionHandler. These structs define which topics should be subscribed to and also point to a callback method. When a communicator receives a MQTT message, it compares the topic to the known ones and calls the appropriate callback.
Communicator(char * mqttBrokerIP, uint16_t mqttBrokerPort, char *mqttUsername, char * mqttPassword, char * mqttClientHostname, SubscriptionHandler subscriptionHandlers[], int lenHandlers);

SubscriptionHandler. is defined like this:
typedef void (*callback)();

struct SubscriptionHandler
{
    char *Topic;
    callback Callback;
};

I tried the following: In the main file, I defined two methods for demonstration purposes:
void enableHandler()
{
  Serial.println("enable handler");
}

void disableHandler()
{
  Serial.println("disable handler");
}

The communicator is created in the setup()-Method:
SubscriptionHandler handlers[] = {{&strEnable, enableHandler},
                                    {&strDisable, disableHandler}};

callback (in communicator.h) typedef void (callback)();
strings : String strEnable = ("test/" + hostname + "/command/enable"); and the same for disable. Those are also defined in main.cpp –
As soon as the communicator receives a MQTT message, the ESP32 crashes with the following message:
Guru Meditation Error: Core  1 panic'ed (InstrFetchProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x3ffc9306  PS      : 0x00060c30  A0      : 0x8017e97c  A1      : 0x3ffb1ed0
A2      : 0x3ffc9306  A3      : 0x3ffc9306  A4      : 0x3ffc9306  A5      : 0x3ffc1318
A6      : 0x3ffb1f44  A7      : 0x00000000  A8      : 0x800d4df0  A9      : 0x3ffb1eb0
A10     : 0x0000000d  A11     : 0x0000000b  A12     : 0x3ffc24a4  A13     : 0xa98b32f8
A14     : 0x3ffc1318  A15     : 0xff000000  SAR     : 0x00000004  EXCCAUSE: 0x00000014
EXCVADDR: 0x3ffc9304  LBEG    : 0x400014fd  LEND    : 0x4000150d  LCOUNT  : 0xffffffff

Backtrace: 0x3ffc9306:0x3ffb1ed0 0x4017e979:0x3ffb1f00 0x400e280e:0x3ffb1f20 0x400d4f3e:0x3ffb1f70 0x400d5cff:0x3ffb1f90 0x400e4c45:0x3ffb1fb0 0x400889dd:0x3ffb1fd0

Therefore, something is wrong with how I use the function pointer (or somewhere which I don't even think about). Could anyone give me a hint where I could start?

What is callback defined as? And the str... variables - what are they?

callback  typedef void (*callback)();
strings** : String strEnable = ("test/" + hostname + "/command/enable"); and the same for disable.
Those are also defined in main.cpp

And those strEnable a strDisable strings? If it's char array, you shouldn't have & here and for better readability it should be before function names.

You're passing the address of a String object to a char * pointer. That's very bad.

have you seen this? https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/

@Majenko, I was indeed unsure about this. But this mqtt lib uses this data type, therefore I thought about using it too. Is there a better way?

@jsotola, the thing is I'm subscribing to multiple topics and I want to call method x of class y when i receive something on topic z. Publishing&Subscribing works on the examples I tried before. But calling the function after receiving a message and determine which function to call crashes.

I found the issue. After moving SubscriptionHandler handlers[] = ... out of the setup()-method, the function calls work. Perhaps handlers gets overwritten after leaving the setupfunction scope. Could anyone validate my suspected reason?

Anything in local scope (defined in a function) is gone after the function ends. Even if you store a pointer to it somewhere. It's gone.

source: Stack Exchange

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

sort: votes


text:
How to use existing (non-arduino-specific) library with subfolders in Arduino IDE?
I have a generic c++ library that i'd like to use in an arduino project without making changes to the library code.
The library contains subfolders and files in the library include other files of the same library with includes of the form
#include "libraryroot/subfoldername/header.h"

I tried putting 'libaryroot' into C:/Users/Username/Documents/Arduino/libraries but while I can include headers that lie directly inside 'libraryroot' using #include <filename.h> (not #include <libraryroot/filename.h>), Arduino fails to find the headers these files include
How can I make use of such a library in Arduino without having to change the library?

Check out Platform IO for visual studio code. It is a much better IDE and will let you this type of thing more easily.

@Juraj I already read this but I still didn't figure out how it can be done

To utilize subfolders with any name in an Arduino library, you must use the 1.5 library specification.
In libraries folder in your sketch folder, create a folder for the library. In this folder create a src subfolder and put the library source code into that subfolder. Then create a library.properties file in the root folder of the library with some dummy information. Fill the includes key with the main .h file of the library.
Documents/
  Arduino/
   libraries/
     FooLib/
      src/
       subfoldername/
        header.h
        some.h
        some.cpp
       foolib.h
       foolib.cpp
      library.properties

In code then use in #include the path with src folder as starting location.
#include <subfoldername/header.h>

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


text:
Solar powered ESP8266. WiFi module usage optimizations
Above all, I am quite new to the ESP8266 and micro controllers development as a whole. I am now working on a project which is quite simple for now. It basically looks like this:

As you can see, I have an ESP8266 and some input peripheral. Everything works perfectly fine for the moment, I can read the inputs from the motion sensor and 4x3 keypad. And, respectively I can output on the relay and the 5mm LED. In order to make it a real IOT, I have connected it to the internet via Thinger.IO. So, I have my ESP8266 constantly connected to this platform and I can track it anytime, from anywhere.
This is great. But, my optimal goal is to power my configuration from a solar panel and make it independent of the electricity distribution network.
The average working current of the whole system is about 313mA (10000 mAh battery gets completely drained for 32 hours. Its output is 5V, 2.1A).
So, I am now in a search of the best solar panel to fit my needs. An ultimate one would have the following maximal dimensions: 30x35 cm. I am not sure there's a single panel that I can use but I am interested to hear your opinion in this.
Another aspect, that I'd like to optimize is the constant internet connectivity. Basically, I need to have my configuration connected to the internet only when keypad input was made or motion sensor detected something. During the rest of the time, I don't need to be connected to the internet and I assume WiFi module could be suspended somehow. Currently, my code uses SmartConfig and is looks like this:
#include <ESP8266WIFI.h>

void connectToWifi() {
  WiFi.mode(WIFI_STA);
  WiFi.beginSmartConfig();

  while(!WiFi.smartConfigDone()){
    delay(500);
  }
}

void setup() {
  connectToWifi();

}

void loop() {

}

Everything works well. But, as I said, I'd like to be able to start/stop the WiFi module. I tried using the following API:
void toggleWifi(bool isWakeUpCall) {
  if(isWakeUpCall)
    WiFi.forceSleepWake();
  else
    WiFi.forceSleepBegin(30000000);

  delay(500);
}

but without much of a success. Once it gets into this portion of code, it gets completely disconnected and doesn't get connected anymore. I am now struggling with it.
I've read about the sleep modes offered by the ESP8266 but I don't think they are suitable for my case because I can not simulate external interrupt (or maybe I can?).
I am really curious to hear your opinion on this. :)

As a solar panel you can use a MEGSUN 10W 12V Mono Solar Panel or similar. They are smaller than what you specified and should be plenty for powering an ESP.

As described here the ESP8266 can be waken up using Timer Wake Up or external interrupt. The idea is simple: almost everything inside the ESP is powered down (including Wi-Fi and/or System clock or even the CPU) with only a timer running which was told when to activate before the ESP went to sleep. After the desired amount of time has passed the timer triggers GPIO 16 or D0 and if that is connected to the reset pin of the ESP is resets and starts executing code again until it goes to sleep again. For your case you can configure your motion sensor to output a LOW when motion is detected and connect is to a GPIO pin and the reset pin, so it will trigger a restart when motion is detected and in the startup sequence you look at the pin where the sensor is connected and do what you have to do. For the keyboard to work you can have the timer set to reset every 5 seconds, so you would have to hold a button for 5 seconds waiting for the ESP to wake up and accept your input or you could make a dedicated button for waking up the ESP if you want to enter the code. In that case the you don't need a timer, since as you described the ESP only has to do anything if the keyboard is activated or if the motion sensor is triggered and since they can be connected as external interrupts they will wake up the ESP if needed. I would recommend to check out this link for further details about the code and hardware.

I have already read a lot of articles regarding Deep Sleep but I am not sure I can achieve that with my current setup. The reason is simple - all of my GPIOs are currently occupied (It is not only what you can see on the diagram. I decided to leave the most important ones there). So, keypad input and motion detection are equal in my use-cases. You can either input on the keypad or you could receive a signal from the motion detection sensor. I don't think 5 seconds timer would be convenient for my case. Because I need to "teach to hold for 5 sec." my end-user which I don't think is a good idea.

@user60623 In that case you can use a regular Arduino to handle all the IO and use an ESP only when you needed to push the stuff to the cloud. Also, if you are expecting a proper answer provide everything you have not only the "important ones" since solutions are highly specific to the project schematics. And since on the diagram above I saw free pins I assumed you have headroom.

Connecting a motion sensor to the reset pin could be problematic. It would cause the ESP to reset every time the motion sensor detected motion, even if it wasn't finished restarting from the last reset. You'd really need some logic that would latch the motion sensing trigger for some time, or until the ESP released the latch. You could build a latching motion sensor trigger with a 555 timer and a few discrete components.


text:
Esp32: upload eeprom file
I'd like to flash the eeprom sector with content so that the eeprom already holds data when it boots the first time.
How do I upload such an eeprom file like I would do with avrdude on an atmega? Is there a tool that can be installed in the arduino IDE like the data uploader?

esptool can download and upload any region of the esp flash

@Juraj I can't find any dedicated command line option. Like, for my atmega I would use something like -U eeprom:w.... Do I have to find the address offest myself and if so, where? Actually, where do I find the actual partition table the arduino IDE uses?

I said "flash". the esptool command is read_flash and write_flash. I don't write an answer, because I never tested that.

The ESP8266 has no EEPROM.
Instead the flash memory is partitioned into different areas for different purposes. One of those areas is set aside for "EEPROM Emulation" data.
To upload to that area you first need to know where that area is in the flash memory, and that is dependent on what partitioning scheme you are using at the moment.
Once you have worked that out (look in the partition scheme files in the core for more information) you can then use esptool to upload data to the right area of flash.

@Juraj I did, yes, but technically I am also correct saying it has no flash, since it relies on an external flash chip :)


text:
Arduino - manually ceate objects (e.g. WiFi library)
By default, if i include the WiFi library, the object WiFi will be registered globally. How can i disable this behavior without changing the library file itself? (removing the definition "extern ...")
Or is there a way to delete the objects right after the inclusion? I just want to create the object manually when needed to save memory.

it shouldn't be in build result, if it is not used

you can check the .map file for code excluded and code included in the final build

I am not sure, if it would save enought memory to be worth the problems (it is just few bytes, buffers are created anyway), but lets say so.
Then you need modify the library to not creating the object, as it is allocated statically and cannot be removed later (and reclaim its memory). To protect all other projects it would be probably best to use special #define to disable it only in memory critical projects - so the Wire.h should contain something like
#ifndef EXCLUDE_WIRE
extern TwoWire Wire;
#endif

and your program (critical.ino) should start with
#define EXCLUDE_WIRE
#include <Wire.h>

and then somewhere in loop / other function use
TwoWire Wire;

as local variable. If you need to call other functions with it, then you have to send its address as a parameter.
Anyway you will not save nearly any memory, as nearly all variables in TwoWire ((and namely buffers) are static and so class variables and so are common for all instacies of TwoWire and allocated automatically if there is (possibly used) any instance of TwoWire anywhere in your program.
So it would be better to create your own library to use the same functionality, but make sure, that all such variables are instance variables and properly created and released at the right time. This would also allowe for changing the buffer sizes, if needed.
As it is under LGPL 2.0+ you are legally allowed to do that (provided you fullfill all licence conditions).

Thanks.I already thought i've to go that way. Even if this makes much more work, i can also strip down everything i don't need. My sketch space is is also running on limit ;)

Note that if you don't use the global Wire variable, it will be stripped away by the linker and will not use any memory. There is strictly no point in modifying the library source to remove it.

@elebb: You may be able to save some memory by stripping unused functionality from the library methods that you do use, and by removing unused data members. You will not, however, save anything by removing unused methods or global variables: the linker already does that for you. Essentially, the Arduino IDE is already applying this optimization technique.

If I understood it correctly, that the intended use was to have NOT one global Wire object all the time, but create it in case you need to use it and destroy it afterwards to save RAM, while other part of program will in other time use that same RAM for something else and then free it. Just the same way, as the same byte in RAM is used as part of local integer variable in one function and in other time as say local char variable of totally unrelated function, in other time it could be part of return address of third function, while in mean time it is just part of free RAM for stack.


text:
Serial.write without a receiver
I'd like to send  a monitoring information (temperature) to a serial receiver periodically. The problem is I don't know if there is any monitoring service (serial receiver) and how fast it is reading. I only need the latest value. The problem is that serial.write will block if the buffer is full. If I skip writing if the buffer is full, a receiver will only get old data on the first connect. How can I replace data in the buffer or make sure there is only one dataset in the buffer?

The problem is that serial.write will block if the buffer is full.

Only until the bytes get sent out through the TX pin.

If I skip writing if the buffer is full, a receiver will only get old data on the first connect.

No it won't. There is no "old" data.

How can I replace data in the buffer or make sure there is only one dataset in the buffer?

You don't need to.
You are showing a fundamental misunderstanding of how serial works.  When you send data it just twiddles the TX pin in the right way with the right timing. If there is something connected to it that understands that twiddling at the speed it's being twiddled then it interprets it as serial data. If there's nothing to see that twiddling it still twiddles.  The "blocking" is only if you try and send more data than the serial port can physically send out in the time you're sending it.
If a serial port transmits in a forest and there is no one there to hear it, yes, it still makes a noise.


text:
Use Arduino Libraries in PlatformIO?
I'd like to use Arduino libraries installed in C:\Users\Username\Documents\Arduino\libraries in a PlatformIO project. Is it possible? if so, how?

I'd start with documentation, for example lib_extra_dirs looks promising


text:
Arduino long distance cable tester
We have a 50 pair cable running about 1.5-2 KM with some services running on different pairs. One pair has recently become intermittent and is losing connection for 1-2 seconds at random. It might happen a few times an hour, so I jumped the service onto another pair. There is a modem connected to the pair for communication between two sites.
When resistance tested with a multi meter with a loop in one end it was reading 330 Ohms. When using an oscar meter it was reading -2.4db which is the same readings for other pairs.
I would like to use an Arduino to monitor the line resistance for a few days and see if there are any spikes or breaks in the line. I was going to use an analog input as a multimeter by using a known resistor and the looped pair as the other resistor.
Does anybody think this will not work?
How else could I go about this?

Sure, no reason that wouldn't work. For best results you want a known resistor of about the same resistance as, or a little below, the one you are measuring.
However, if what you are seeing is an actual open circuit then there's little benefit to measuring the resistance - you may as well just treat it as a switch or button, give it a large pullup, and use a digital input (or even an interrupt) to give a simple "OK / ERROR" signal.

It does not appear to be an open circuit i think. But i was worried the 5v dc wont get around the line and back with voltage drop?

The voltage drop is dependent on the current and the resistance, and the current is dependent on the resistance and the voltage...  (simple Ohm's Law). If you use a 100Ω resistor that's 430Ω with 5V across it, which gives you 11.6mA flowing through the cable.

Thanks. I will try tomorrow. When i connect 12v to the line i only read 8v coming back on my multimeter which is confusing me.

That statement makes no sense. If you have a closed loop there is no "coming back" to measure.

Picture this. Positive lead connected to one wire of the pair. Pair looped/shorted at far end. Mete probe connected to returning wire and other probe to negative lead of power supply. Reading 8v.

That's not how you measure voltage. You measure voltage across something, not through it.

Effectively Im measuring the voltage between the power supply pos and neg. But with the cable pair acting as an extension of the positive lead . Not through anything. I was expecting to see 12v.

You would see 12v minus the voltage drop over the resistance of the wire caused by whatever current the meter was drawing. Since that is an unknown value the voltage measured is meaningless.

For data communications the problem is often more complicated than DC resistance. Data signals are AC, and subject to impedance, (not simple resistance) inductance, and capacitance, as well as RF interference. A pair that's fine for slow on/off switching of DC signals may not be fine for higher frequency data signals.
You can also get intermittent shorts between wires in one pair and other pairs, even if the connection between the wires in the test pair are fine.
Back in the day I worked for a company that sold and serviced mini-computers to the US House of Representatives. The house offices would run serial cables up through walls and ceilings, and also under carpets. We had some flaky cables, and finally figured out that the offices would run the cables under the carpet, but over carpet tack strips. As people walked over the carpet, it would sometimes cause the tack strips to poke through the insulation, causing shorts and RF noise in the cables, which would mysteriously go away later.
Checking DC resistance will let you find breaks in your wires, but you can't assume that if the DC resistance looks good, the pair is good.
I would suggest using a simple voltage divider and one of the input lines on the Arduino for simple resistance testing, but that will only get you so far.
What you really want is a signal generator and an oscilloscope. You should send test signals (With voltages and signal patterns that resemble your data signals) down one pair at a time, and look at the signals on the far end, checking all the pairs. You should see your test signal come through, with the wave pattern still recognizable on the target pair, and no significant leaking of the signal to other pairs.


text:
Help with arduino code
Thank you for seeing my post.
I am trying to write a code that lets "A" displayed on row 1 and row 0 alternately on the LCD. starting from (0,1) then (1,0)  then (2,1), then (3,0) etc..
when it reaches the last point is becomes "B" and bouncing back the other way until reaching the starting point when it becomes "A" again and repeat again..
I wrote this code but I got stuck at the end, I don't know how to bounce it back:

// include the library code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);   // initialize the library with the numbers of the interface pins

int x = 0;
int y = 1;

void setup()
{
    lcd.begin(16, 2);
    lcd.clear();
}

void loop()
{
    {
        {
            while (x < 15)
            {
                lcd.setCursor(x, y);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x = x + 1;
                lcd.setCursor(x, y - 1);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x + x++;
            }
        }
        {
            while (x = 15)
                lcd.setCursor(15, 0);
            lcd.print("B");
            delay(2000);
            x--;
        }
    }
}

Learn to use a for loop. It's much easier. And don't confuse assignment (=) with comparison (==) operators.

To me it seems, as if you have no knowledge about C/C++. ( I might be wrong. ;-) )
If you plan to do more programming projects, I advice you to learn the basics of this programming language before proceed with the projects. It would be hard thinking about an algorithm, if you don't know the tools to implement it.
In case you just need this once for a (let's say arts project [or homework ;-)] ), I add some example code. At the moment I have no chance to test the code. So it's blind written, and there might be typos. In about 8 hours I will have access to a test setup then I'll correct it if necessary.
#include <LiquidCrystal.h>

// Here you setup your LCD display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// you initialize the position where the next character
// will be displayed (0,1) (x,y)
int x = 0;
int y = 1;
// setup is only done once
void setup()
{
    // initialize the lcd lib to be used with a 16x2 LCD
    lcd.begin(16, 2);
    // erase all character from the display
    lcd.clear();
}

// the loop is executed again and again and ...
void loop()
{
    // move forward
    // as long as the position is less than 15
    // you allow x = 0, 1, 2, ... ,15 because
    // you increase two times in each loop step
    while (x < 15)
    {
        lcd.clear( );

        lcd.setCursor( x, y );
        lcd.print( "A" );
        delay( 250 );

        // step to the next position
        x = x + 1;
        // toggle y
        y = toggle( y );

        lcd.clear();
        lcd.setCursor( x, y );
        lcd.print( "A" );
        delay( 250 );

        // step to the next position
        x = x + 1;
        // toggle y
        y = toggle( y );
    }

    // now move backward
    // x is still 15 and you want to go backwards until x == 0
    while ( x > 0 )
    {
        lcd.clear( );

        lcd.setCursor( x, y );
        lcd.print( "B" );
        delay( 250 );

        // step to the next position
        x = x - 1;
        // toggle y
        y = toggle( y );

        lcd.clear( );
        lcd.setCursor( x, y );
        lcd.print( "B" );
        delay( 250 );

        // step to the next position
        x = x - 1;
        // toggle y
        y = toggle( y);
    }
}

// this is a subroutine that toggles y = 0 <-> 1
int toggle( int yval )
{
   // I use a ternary operator
   // in case y == 1, I return 0 and a 1 otherwise
   return ( yval == 1) ? 0 : 1;
}


text:
ADC register always returning high
Regardless of whatever voltage at A0, the software is always returning high (1023)
volatile unsigned char* ADmux = (unsigned char*) 0x7C;
volatile unsigned char* ADCSRa = (unsigned char*) 0x7A;
volatile unsigned char* ADCSRb = (unsigned char*) 0x7B;
volatile unsigned char* ADCh = (unsigned char*) 0x79;
volatile unsigned char* ADCl = (unsigned char*) 0x78;
int Voltage;

void adc_init()
{
  *ADmux = 0x00; // setting entire register to 0's notably setting Refs1 and refs0 to 0's meaning reference voltage is AREF
  *ADCSRa = 0b10000111; //Sets most significant bit to 1, which is the ADC enable bit, and the 3 least signifcant bits are the prescalar, which is 128

}

unsigned int adc_read( unsigned char adc_channel)
{
  *ADmux = *ADmux | 0b00000000;// set mux bits to 0 to test A0 regardless of whatever adc_channel is
  *ADCSRa = *ADCSRa | 0b01000000; // set ADSC bit high to start conversion

  while(*ADCSRa & 0b01000000);//wait until ADSC goes low, indicated conversion is complete

  return ADC; //return bits in the adc registers
}

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   adc_init(); // initializes the adc
}

void loop() {
  // put your main code here, to run repeatedly:

  Voltage = adc_read(0b00000); // calls on adc_read

  Serial.print(Voltage); // prints voltage reading
  Serial.write("\n");

}

And here is a schematic of the circuit:

simulate this circuit – Schematic created using CircuitLab
I have combed over chapter 26 of the atmega2560 document and the descriptions of each register, but I am at a loss. Why is the contents of the adc registers always filled with 1's regardless of the voltage at a0?

what do you read if you remove R1?

@jsotola it still reads 1023

What IDE do you use, if any? Make sure MUX5, at ADCSRB:3 is set to 0, as well as ADTS2:0 at ADCSRB 2:0 to enable free running mode.

I got the program to work by setting refs0 to 1. So this means that the reference voltage switched from AREF to AVCC. Does anyone know why this small change makes it work? Isn't AREF 5V by default?

@towe I'm using the default Arduino IDE.

First, let me give a couple of suggestions on the programming style.
There is no point in defining your own variables for accessing the
hardware registers: the avr-libc does that for you, you just have to
#include <avr/io.h>. Actually, you don't have to #include anything:
the Arduino IDE automatically #includes Arduino.h, which in turn
#includes avr/io.h.
Next, the same avr-libc also defines macros for the bit names, so you
don't have to explicitly write binary numbers in your own code (which is
error-prone). And a couple of utility macros that you can use to make
the code a little bit more readable. For example:
void adc_init()
{
    ADMUX  = _BV(REFS0);  // ADC reference = AVCC
    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADPS2)   // set prescaler to 128
           | _BV(ADPS1)   // ditto
           | _BV(ADPS0);  // ditto
}

unsigned int adc_read(unsigned char adc_channel)
{
    ADMUX   = _BV(REFS0) | (adc_channel & 7);  // select channel
    ADCSRA |= _BV(ADSC);  // start conversion

    // Conversion is complete when ADSC goes low.
    loop_until_bit_is_clear(ADCSRA, ADSC);

    return ADC;  // return the adc data register
}

Now, let's answer your actual question. When you set both REFS0 and
REFS1 to 0, the voltage reference is stated to be “AREF, internal V
REF turned off”. The implication is that you are supposed to bring your
own voltage reference and connect it to the AREF pin. Otherwise AREF is
left as a floating input. This is illustrated in the schematic of the
ADC. Here is the relevant part:

As you see here, REFS0 is used to connect AREF to one of the other
possible references: either AVCC or the internal bandgap. If REFS0 is
zero, the transistor depicted above is off, and AREF is left floating.

What are the resistance values for R1 and LDR1? Their ratio will determine the voltage at A0. If the ratio of their resistances is too high (for example, 100:1) then any light measured by LDR1 would only result in a small change in the voltage being measured. If the difference is extreme enough, the voltage could also appear to be constantly low or high. If you have a multimeter available, checking the voltage of that divider circuit could help determine what's going on.
https://learn.sparkfun.com/tutorials/voltage-dividers/all


text:
i2c man in the middle
I'm developing a bridge, or man in the middle for touch controller and a system board connected with I2C.  The connection is:
Touch Controller(slave)---I2C---(master)STM32(slave)---I2C---(master)ARM Board
The original i2c cable is cut in half and STM32 is sitting in the middle.
The point it letting common communication through and just sometimes after an external trigger injecting a click event. (It's for automated testing.) The TC is the only I2C device on the bus.
Have someone done something similar?
The protocol is simple. The ARM board writes two bytes address.Then reads several(3-259) bytes.
I'm trying to request data from TC after receiveEvent() from master, but I don't know how many bytes shall I request. It also takes time for the answer.
Any ideas?

How is this question Arduino related? Perhaps, you are on the wrong channel. ;-) There is also a better chance of getting help if you provide some code. For me it is complete unclear how the communication TC<--> ARM is done on the protocol level. One guess: It seems the ARM initiates the communication. It sends the TC address to the bus. The ARM orders the TC to write and then provides a clock signal. The TC send the data bytes using the clock. If there is no data left it send a Stop signal.

Let the STM pass a read request from the ARM to the TC. Let the STM read data from the TC and send it to the ARM. If the data is not yet available the STM drives the clock line to LOW that pauses the ARM until there is data. If the TC sends a stop (interrupt) send a stop to the ARM too. If you have data to inject, you can inject it as long as the ARM started the communication and STM has not send the stop flag.

Possibly the only requirement is that the touch controller supports clock stretching. I think generally it's possible, but I see now specific question or code. So, have you allready tried anything?

I've tried passing SDA and SCL trough with interrupts. But the bus frequency is 340kHz and the introduced latency to high. Then I was trying requesting slave in receiveEvent() from master. It hangs the whole system I'll try the trick with driving the SCL down as Peter suggests. Or implementing part of the touch protocol. And I've ordered an I2C multiplexer as fail save solution.


text:
Publish chipid to mqtt using ESP32-CAM
I have been trying to push the data of temp, humidity, and pressure from a sensor to MQTT using ESP 32Cam, and was able to do using the following code:
pressure = bme.readPressure();

//Convert the value to a char array
char preString[16];
dtostrf(pressure, 1, 2, preString);
Serial.print("Pressure: ");
Serial.println(preString);
client.publish("esp32/pressure", preString);

When I started off with the following code for getting the mac address:
chipid=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes).
Serial.printf("ESP32 Chip ID = %04X",(uint16_t)(chipid>>32));//print High 2 bytes
Serial.printf("%08X\n",(uint32_t)chipid);//print Low 4bytes.

But when I tried to publish the Chip id, that I was getting on the serial monitor, to the MQTT, an error came up with this:
call of overloaded 'String(uint64_t)' is ambiguous
Here's my code that I tried:
char macValue[16];
String(ESP.getEfuseMac()).toCharArray(macValue,16);
client.publish("esp32/ChipID", macValue);

You would be better off formatting it nicely instead of relying on String...
char macValue[17]; // Don't forget one byte for the terminating NULL...
uint64_t mac = ESP.getEFuseMac();
sprintf(macValue, "%016x", mac);
client.publish("esp32/ChipID", macValue);

However, I'm not certain that sprintf can cope with a 64 bit value like that directly. If not, you can split it:
char macValue[17]; // Don't forget one byte for the terminating NULL...
uint64_t mac = ESP.getEFuseMac();
uint32_t hi = mac >> 32;
uint32_t lo = mac;
sprintf(macValue, "%08x%08x", hi, lo);
client.publish("esp32/ChipID", macValue);

since a MAC address is 6 bytes long, you only need 12 hex digits, so macValue[13] is enough and either %012x or %04%08x as the sprintf format


text:
Switch Case Return , Return not printing
I am trying to get the value of a key pressed and set it to return a value to use in a loop.  In the code below the Print(t) does not show anything
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char hexaKeys[ROWS][COLS] = {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[ROWS] = {5, 4, 3, 2};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys),rowPins,colPins,ROWS,COLS;

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

void loop()
{
    int t;
    switch (customKeypad.getKey())
    {
    case 'A':
        t = 8;
        break;
    case '2':
        t = 9;
        break;
    }
    return t;
    Serial.print(t);
}

Please show your wiring

You misunderstand the use of return.  The loop function is declared void.  That means it doesn't return anything.  If you simply remove that return statement completely then your code will do what you want.
The return stops the loop.  It throws away the value since the loop is defined as returning void, and code execution never reaches the print statement.  Writing anything in a function after a return statement is useless.


text:
Converting each digit in an integer to its respective ASCII characters
For example what would be the process of converting the integer 1023 into ascii characters of
0x31 (1)
0x30 (0)
0x32 (2)
0x33 (3)
Not looking for any library functions (I know of Serial.print() and what not). I am trying to serially communicate an integer to the serial monitor, and I'd like to know what the process would be for an algorithm to take an integer and make each digit its corresponding ascii character

Is this what you are trying to do? http://www.cplusplus.com/reference/cstdlib/itoa/

If you search "c++ implementation itoa" you can find examples for this

how about float value? can float value convert using itoa()?

To convert a whole number to a char array in one go use the itoa function. That sounds like what you actually need.
To convert one digit from decimal to ascii just add '0', the ascii value for a 0. If you just want to try to understand what's going on, it's something like this.
char result[4] = {0};
int num = 345;

int digit = num % 10;  // get the 5 off the end
result[2] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 5
digit = num % 10;   // get the 4 off the end
result[1] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 4
digit = num % 10;   // get the 3 off the end
result[0] = digit + '0';  // convert to ascii and store

Serial.print(result);  // prints "345"


text:
How do I download a sketch to an Arduino semi-permanently?
I will be working with Arduino(s), and I would like to find a way to download the sketches to the board semi permanently, in a way that I can remove the USB from the board, apply power, and still have the Arduino execute the code
I am planning to use Mega2960, Uno, and Nano. If there are any differences between the uploading process,
please let me know.
P.S., I am using boards produced by Elegoo, not by Arduino, if that makes a difference.

But... that is basically what happens when you press the "upload" button... it programs your compiled code into the board.

When I unplugged the Mega, it stopped functioning, although it still had power from a 9v battery. I also tried hitting the reset button.

Then you either have something in your code or circuit that is broken.

Oh well... I currently don’t have access to the code currently, as the Mega was at a Robotics Club that I visit.

@Nutmeg, your post is what is called an XY problem ... you asked for help with what you think is a solution to an observed problem, instead of asking for help with the actual observed problem

@jsotola, what caused it to be an XY problem?

as i said, you did not ask for help with the problem that you observed (Mega stopped functioning) ... you asked about making the sketch semi-permanent (misguided solution to the problem)

A 9V block battery should never be used with an Arduino board. It is only meant for low power applications and cannot provide enough current. So I guess the code stops working, because the Mega does not have enough power and browns out

Oh, ok. The kit I was using from Elegoo just came with the kit.

Download the Arduino software (IDE, or Integrated Development Environment).

In our case, we only need to download and run Windows Installer and follow the pop up instructions.  When asked if you want to install the Arduino driver, just press Yes.

Connect your Arduino Nano board to your computer.

In this step, Windows should automatically find the proper Arduino driver and install it, and your Nano board should be ready to use.  If not, please refer to the above mentioned instruction for details on installing the drivers.  Some compatible Nano boards such as DCCduino manufactured by a Chinese company use different USB-to-Serial chips so they require to install different drivers, but the installation should be quite straight forward once you have downloaded the proper drivers from internet.

Launch the Arduino application.
Open the blink example.

Open the LED blink example sketch: File > Examples > 01.Basics > Blink.
For those who are not familiar with Arduino sketch, a sketch is simply a program with various instructions telling Arduino board what to do.

Select your board.

You’ll need to select what type of Arduino board you are using.  In our case, simply select Tools > Board > Arduino Nano w/Atmega328.

Select your serial port

You also need to select the serial device of the Arduino board: Tools > Serial Port.  Usually the port number will be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your Arduino board and re-open the menu; the entry that disappears should be the Arduino board. Reconnect the board and select that serial port.

Upload the program to Nano board

Now, simply click the “Upload” button in the environment. Wait a few seconds – you should see the RX and TX leds on the board flashing. If the upload is successful, the message “Done uploading.” will appear in the status bar.
A few seconds after the upload finishes, you should see the pin 13 (L) LED on the board start to blink (in orange). If it does, congratulations! You’ve gotten Arduino up-and-running.
Disconnect from your computer and connect to a power supply to see the blinking light.


text:
Code running on UNO doesn't run on MEGA
the code posted below runs perfectly on UNO, but the loop only runs for twice or thrice (figured this out by printing out "TEST" on the Serial Monitor) on the Arduino mega. Someone can tell me what's wrong with this? It's a 4wd robot which runs on RF Joystick. The circuit has a RF receiver connected to digital pin 2. Also, I noticed that when all the functions are removed from the loop, it runs perfectly.
However, as my suspicion that the board is not functioning properly, I tried uploading other programs to the MEGA and they run flawlessly.Including the "ESP8266 as a shield controlled using the Blynk app version" of this code.
#include <VirtualWire.h>
#include <AFMotor.h>
int RF_RX_PIN = 2;// RF signal from joystick
void(* resetFunc) (void) = 0;
AF_DCMotor rb(4);//means rightside,back wheel
AF_DCMotor lb(3);//leftside, back wheel
AF_DCMotor rf(1);
AF_DCMotor lf(2);
  int xh,xl,yh,yl;
  uint8_t z;
  uint8_t button;

void setup()
{
  Serial.begin(9600);
  vw_set_rx_pin(RF_RX_PIN);  // Setup receive pin.
  vw_setup(2000); // Transmission speed in bits per second.
  vw_rx_start(); // Start the PLL receiver.
  pinMode(servopin,OUTPUT);
  pinMode(13,OUTPUT);
  rf.run(RELEASE);
  lf.run(RELEASE);
  lb.run(RELEASE);
  rb.run(RELEASE);
  digitalWrite(13,HIGH);
}

uint8_t buffer[VW_MAX_MESSAGE_LEN]; // buffer array for data recieve over serial port
uint8_t buflen = VW_MAX_MESSAGE_LEN;
int x=0;
int y=0;
int state=2;

void loop()
{
  Serial.println("TEST");
  if(vw_get_message(buffer, &buflen)) // non-blocking I/O
  {
    decode();
  if ((x==0 && y==0) || z==1){rstop();}
  else {
  Serial.print(x);
  Serial.print(" ");
  Serial.println(y);
  godirection(x,y);
  }
  }else{
    state=2;
    rstop();
  }
}

void decode()
{
  if((buffer[0]!=0x7E)||(buffer[4]!=0xEF))
  {
  resetFunc();
  }
  uint8_t i = 0;
  x = buffer[1]<<2;
  y = buffer[2]<<2;
  z = buffer[3]>>3;
  button = buffer[3]&0x07;
   if (x>600){
    x=1;
  }else if (x<=600 && x>=400){x=0;}
  else {x=-1;}
  if (y>600){
    y=1;
  }else if (y<=600 && y>=400){y=0;}
  else {y=-1;}
}

void clearBufferArray()              // function to clear buffer array
{
  for (int i=0; i<VW_MAX_MESSAGE_LEN;i++)
    { buffer[i]=0;}                  // clear all index of array with command NULL
}
void godirection(int x,int y) {
     if (x==0){
      if (y==1){forward();}
      else if (y==0){rstop();}
      else if (y==-1){backward();}
     }
     else if (x==1){
      if (y==1){srf();}
      else if (y==0){right();}
      else if (y==-1){srb();}
     }
     else if (x==-1){
      if(y==1){slf();}
      else if (y==0){left();}
      else if (y==-1){slb();}
     }
}

void rstop (){
  if (state==0){
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
  delay(75);
  rf.run(RELEASE);lf.run(RELEASE);lb.run(RELEASE);rb.run(RELEASE);
  rf.setSpeed(0);lf.setSpeed(0);rb.setSpeed(0);lb.setSpeed(0);
  state=2;
}
else if (state==1){
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
  delay(75);
  rf.run(RELEASE);lf.run(RELEASE);lb.run(RELEASE);rb.run(RELEASE);
  rf.setSpeed(0);lf.setSpeed(0);rb.setSpeed(0);lb.setSpeed(0);
  state=2;
}
else if (state==2){
    rf.run(RELEASE);lf.run(RELEASE);lb.run(RELEASE);rb.run(RELEASE);
  rf.setSpeed(0);lf.setSpeed(0);rb.setSpeed(0);lb.setSpeed(0);
}
}

void forward(){
  state=1;
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}

void backward(){
  state=0;
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}

void right(){
  state=2;
  rf.run(BACKWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}
void left(){
  state=2;
  lf.run(BACKWARD);rf.run(FORWARD);rb.run(FORWARD);lb.run(BACKWARD);
  rf.setSpeed(200);lf.setSpeed(200);rb.setSpeed(200);lb.setSpeed(200);
}

void srf(){//srf means slanted right forward
  state=1;
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  rf.setSpeed(50);lf.setSpeed(200);rb.setSpeed(50);lb.setSpeed(200);
}

void srb(){
  state=0;
  Serial.println("SRB");
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  rf.setSpeed(50);lf.setSpeed(200);rb.setSpeed(50);lb.setSpeed(200);
}

void slf(){
  state=1;
  rf.run(FORWARD);lf.run(FORWARD);lb.run(FORWARD);rb.run(FORWARD);
  lf.setSpeed(50);rf.setSpeed(200);lb.setSpeed(50);rb.setSpeed(200);
}

void slb(){
  state=0;
  rf.run(BACKWARD);lf.run(BACKWARD);lb.run(BACKWARD);rb.run(BACKWARD);
  lf.setSpeed(50);rf.setSpeed(200);lb.setSpeed(50);rb.setSpeed(200);
}

where in the program does it stop?

the whole thing stops just I couldn't find a specific place it did. the serial monitor just stops after printing two or three "TEST" s. I think the loop iteration stops. However, if all the functions such as rstop, and decode are removed, it runs again. but it is not specific to any function.

then figure out where is stops exactly

it just stops when it meets a function :(… I figured it.. any function... when it meets one.. it freezes. but any other code with any function works perfectly fine. only in this code

You need to put in a lot more print statements to figure out exactly where the program is halting.  Put a print statement at the beginning and end of each function. then you'll see which function is causing the crash.

You also need to fix your indentation. The way your rstop() function is indented, it looks like the first closing brace ends the function and the else if (state==1) code is outside any function. The body of the first if statement should be indented, and the closing brace that ends the if statement should be on the same line as the if statement. There are quite a few bad uses of indentation that make your code very hard to read.

There is a servopin variable you configure as OUTPUT. Where does it come from? From the header files? If it is not declared anywhere, i don't believe that code compiles. Or did you delete some code, and this is not all you have done?

Im sorry please ignore the servopin,,, I removed the variable declaration to make it easier to focus on this problem for you guys... forgot to delete that line


text:
Arduino IDE with ATtiny85 error "multiple definition of `__vector_5"
I am having a problem compiling the code for my ATtiny85 circuit.
I am using the timer/counter0 in normal mode so that when it overflows it triggers the TIMER0_OVF_vect ISR. When I have that ISR in my code, it wont compile and gives this error:
wiring.c.o (symbol from plugin): In function `__vector_5':
(.text+0x0): multiple definition of `__vector_5'
sketch\Glove_heater_v1.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board ATtiny25/45/85.

Maybe I just need to use a different name for the ISR?
My Code:

//Red LED on PB0
//Blue LED on PB1
//Pushbutton PB2
//Battery voltage divider PB3
//Mosfet control PB4

#include <avr/io.h>
#include <stdint.h>
#include <avr/interrupt.h>

volatile uint8_t checkVoltage = 0;

void setup() {

   DDRB = 0b0010011; //set PB0,PB1,PB4 as output, PB2,PB3 as input
   PORTB = 0b00000011; //set PB0,PB1 HIGH so LEDs are off, other pins LOW

   //Setup TC0 for overflow interrupt trigger
   TCCR0B |= 0b00000101; //clk/1024 prescaler
   TIMSK |= 0b00000010;  //set TOIE0 enable overflow interrupt
   sei();
}

void loop() { //do nothing in this test code

}

ISR(TIMER0_OVF_vect){ //Timer/counter0 interrupt check voltage
   checkVoltage = 1;
}

Any ideas are appreciated!

Arduino uses it for counting millis

The error message was:

wiring.c.o [...]: multiple definition of `__vector_5'
  Glove_heater_v1.ino.cpp.o [...]: first defined here

__vector_5 is TIMER0_OVF_vect. So you have one definition of this
ISR in your sketch, and another one in wiring.c. This wiring.c is part
of the Arduino core. As KIIV puts it in a comment, it uses
TIMER0_OVF_vect for timekeeping (millis(), micros() and
delay()).
You have two options for solving this:

you can use the other timer (Timer 1) in your sketch, and leave Timer
0 for the Arduino core
since you are not using the Arduino core anyway, you can get rid of it
by simply defining main() in your sketch instead of setup() and
loop().

Ah I see, thank you very much for the explanation. The final code uses both timers so, I will avoid using the Arduino core in this case.


text:
millis() function works with inline code and gives output but when creating own library it doesn't works
I am creating library for GPS to use in my project. I am using Adafruit GPS and its library to create my own library in which I am using millis() function to display the GPS Location after 1 minute (60s). So when I created my inline code the function works very well and also displays location after 60s. But I created header and cpp file for my own library, in which it doesn't gives any error but the results(location) is not displayed. Doesn't shows any output. So I printed the time which is 0 (attached the output screenshot)
My code updates the GPS every 30s and prints the location every 1 minute.It also checks the if old location is equal to new location in every 1minute.
I think there is problem with my libaray or with the millis() function. I am new to Arduino programming , please help me with this.
My inline code is:
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(11, 10);
Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true
uint32_t timer = millis();
float old_lat,old_lon,new_lat,new_lon;

void setup()
{

  Serial.begin(9600);
  delay(1000);
  Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand("$PMTK220,30000*1F");
  mySerial.println(PMTK_Q_RELEASE);
}

void loop()                     // run over and over again
{
  char c = GPS.read();
  if (GPS.newNMEAreceived()) {
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

if (GPS.fix) {

      old_lat = GPS.latitudeDegrees;
      old_lon = GPS.longitudeDegrees;
      if (timer > millis())  timer = millis();
      if (millis() - timer > 60000) {
        timer = millis();
          Serial.println("Location 1 minute:");
          displaytime();
          new_lat = GPS.latitudeDegrees;
          new_lon = GPS.longitudeDegrees;

          if (new_lat == old_lat){
            new_lat = old_lat;
          }
          else{
            new_lat = GPS.latitudeDegrees;
          }
          Serial.print("Final Latitude: ");
          Serial.println(new_lat,6);

          if (new_lon == old_lon){
            new_lon = old_lon;
          }
          else{
            new_lon = GPS.longitudeDegrees;
          }
          Serial.print("Final Longitude: ");
          Serial.println(new_lon,6);

}
}
}

void displaytime(){
    Serial.print("\nTime: ");
    if (GPS.hour < 10) { Serial.print('0'); }
    Serial.print(GPS.hour, DEC); Serial.print(':');
    if (GPS.minute < 10) { Serial.print('0'); }
    Serial.print(GPS.minute, DEC); Serial.print(':');
    if (GPS.seconds < 10) { Serial.print('0'); }
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    if (GPS.milliseconds < 10) {
      Serial.print("00");
    } else if (GPS.milliseconds > 9 && GPS.milliseconds < 100) {
      Serial.print("0");
    }
    Serial.println(GPS.milliseconds);
}

My header file is :
/*
 * GPS.h - library used to show Latitude and Longitude
 */

 #ifndef GPS_Loc_h
 #define GPS_Loc_h

 #include "Arduino.h"

class SoftwareSerial;
class Adafruit_GPS;

 class GPS_Loc
 {
  public:
    GPS_Loc();
    void displaytime();
    void displayloc();
    uint32_t timer;
    float old_lat,old_lon,new_lat,new_lon;
 };

 #endif

My cpp file is:
/*
 * GPS_Loc.cpp - library used to show Latitude and Longitude
 */

 #include "Arduino.h"
 #include "GPS_Loc.h"

 #include "Adafruit_GPS.h"
 #include "SoftwareSerial.h"

 #define GPSECHO  true

SoftwareSerial mySerial(11,10);
Adafruit_GPS GPS(&mySerial);

GPS_Loc::GPS_Loc()
{
  timer = millis();
  old_lat = old_lat;
  old_lon = old_lon;
  new_lat = new_lat;
  new_lon = new_lon;
}

void GPS_Loc::displayloc(){
  //Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand("$PMTK220,30000*1F");
  mySerial.println(PMTK_Q_RELEASE);
  char c = GPS.read();
  if (GPS.newNMEAreceived()) {
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
    }

if (GPS.fix) {

      old_lat = GPS.latitudeDegrees;
      old_lon = GPS.longitudeDegrees;
      if (timer > millis())  timer = millis();
      if (millis() - timer > 60000) {
        timer = millis();
          Serial.println("Location 1 minute:");
          displaytime();
          new_lat = GPS.latitudeDegrees;
          new_lon = GPS.longitudeDegrees;

          if (new_lat == old_lat){
            new_lat = old_lat;
          }
          else{
            new_lat = GPS.latitudeDegrees;
          }
      Serial.print("Location lat: ");
          Serial.println(new_lat,6);

          if (new_lon == old_lon){
            new_lon = old_lon;
          }
          else{
            new_lon = GPS.longitudeDegrees;
          }

          Serial.print("Location long: ");
          Serial.println(new_lon,6);

}
}
}

void GPS_Loc::displaytime(){
    Serial.print("\nTime: ");
    if (GPS.hour < 10) { Serial.print('0'); }
    Serial.print(GPS.hour, DEC); Serial.print(':');
    if (GPS.minute < 10) { Serial.print('0'); }
    Serial.print(GPS.minute, DEC); Serial.print(':');
    if (GPS.seconds < 10) { Serial.print('0'); }
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    if (GPS.milliseconds < 10) {
      Serial.print("00");
    } else if (GPS.milliseconds > 9 && GPS.milliseconds < 100) {
      Serial.print("0");
    }
    Serial.println(GPS.milliseconds);
}

My demo code using my own library is:
#include <GPS_Loc.h>

GPS_Loc bgps;

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

}

void loop() {
  // put your main code here, to run repeatedly:
  bgps.displaytime();
  bgps.displayloc();
}

Output of inline code

I think the problem might be with GPS.begin(9600);. You are initialize the serial connection every time you call displayLoc. But in the inline code, you only do this once. Try adding an init function to your class, that will setup the serial only once.

I think Gerben is on to something.  If you re-initialize the gps at every loop and then never give it time to acquire the gps signal then your if (GPS.fix) condition is never true and you never print out any other data.  All your timing code is inside the GPS.fix condition which doesn't happen until you have a fix.
Try putting the init code inside your contructor for your class. Somethink like :
GPS_Loc::GPS_Loc()
{
  timer = millis();
  old_lat = old_lat;
  old_lon = old_lon;
  new_lat = new_lat;
  new_lon = new_lon;

  //Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand("$PMTK220,30000*1F");
  mySerial.println(PMTK_Q_RELEASE);
}

void GPS_Loc::displayloc(){
  delay(100); // short delay to stop a no-fix runaway
  char c = GPS.read();
  if (GPS.newNMEAreceived()) {
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
    }

if (GPS.fix) {

It might also be useful to put a small delay somewhere in the code so that it won't loop like crazy before getting a fix.

Still I am not getting the output


text:
How to set current position for the DC motor to zero + store current positions in an array and run it?
I would like to know how to set the current position for the DC motors to zero and store the current position in an array. after that I would like it to loop in the array to run all steps that was stored in the array?
Am using Genuino UNO board, I have 4 DC motors and each 2 wheels are connected to an H-bridge.
I have an application that have a "save" button and a "Run" button.
For the save button, I would like it to set the current position for each wheel to zero first then store the positions of each wheel in an array.
For the run button, I would like it to loop in the array that was made by the save button and show the output on each wheels.
basically what am trying to achieve is to make the robotic car that can move any direction I tell it to move in the same time  I can control the wheel speed.
all that move are being sent via Bluetooth as numbers.
I hope it's clear now
here is my code
#include <SoftwareSerial.h>

SoftwareSerial Bluetooth(0, 1); // Arduino(RX, TX) - HC-05 Bluetooth (TX, RX)

// Define the motors and the pins
// Motor A1

int enA1 = 2;
int in11 = 3;
int in21 = 4;

// Motor B1

int enB1 = 5;
int in31 = 6;
int in41 = 7;

//other H-bridge

// Motor A2

int enA2 = 8;
int in12 = 9;
int in22 = 10;

// Motor B2

int enB2 = 11;
int in32 = 12;
int in42 = 13;

int wheelSpeed = 125;
int dataIn, m;
//lbw left back wheel / lfw left fron wheel / rbw right back wheel / rfw right front wheel
int lbw[50], lfw[50], rbw[50], rfw[50]; // for storing positions/steps
int index = 0;

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

  Bluetooth.begin(9600); // Default baud rate of the Bluetooth module
  Bluetooth.setTimeout(1);
  Serial.print("connected");
  Serial.print("-------------------");
  delay(20);

  pinMode(enA1, OUTPUT);
  pinMode(enB1, OUTPUT);
  pinMode(in11, OUTPUT);
  pinMode(in21, OUTPUT);
  pinMode(in31, OUTPUT);
  pinMode(in41, OUTPUT);
  pinMode(enA2, OUTPUT);
  pinMode(enB2, OUTPUT);
  pinMode(in12, OUTPUT);
  pinMode(in22, OUTPUT);
  pinMode(in32, OUTPUT);
  pinMode(in42, OUTPUT);
}

void loop() {
  // Check for incoming data

 if (Bluetooth.available() > 0) {
    dataIn = Bluetooth.read();  // Read the data

    if (dataIn == 0) {
      m = 0;
    }
    if (dataIn == 1) {
      m = 1;
    }
    if (dataIn == 2) {
      m = 2;
    }
    if (dataIn == 3) {
      m = 3;
    }
    if (dataIn == 4) {
      m = 4;
    }
    if (dataIn == 5) {
      m = 5;
    }
    if (dataIn == 6) {
      m = 6;
    }
    if (dataIn == 7) {
      m = 7;
    }
    if (dataIn == 8) {
      m = 8;

    }
    if (dataIn == 9) {
      m = 9;
    }
    if (dataIn == 10) {
      m = 10;
    }
    if (dataIn == 11) {
      m = 11;
    }

    if (dataIn == 12) {
      m = 12;
    }
    if (dataIn == 14) {
      m = 14;
    }
    // Set speed
    if (dataIn >= 16) {
      wheelSpeed = dataIn * 10;
      Serial.println(wheelSpeed);
    }
  }
  if (m == 4) {
    moveSidewaysLeft();
  }
  if (m == 5) {
    moveSidewaysRight();
  }
  if (m == 2) {
    moveForward();
  }
  if (m == 7) {
    moveBackward();
  }
  if (m == 3) {
    moveRightForward();
  }
  if (m == 1) {
    moveLeftForward();
  }
  if (m == 8) {
    moveRightBackward();
  }
  if (m == 6) {
    moveLeftBackward();
  }
  if (m == 9) {
    rotateLeft();
  }
  if (m == 10) {
    rotateRight();
  }

  if (m == 0) {
    stopMoving();
  }
  //Serial.println(dataIn);
  // If button "SAVE" is pressed
  if (m == 12) {
    if (index == 0) {
        digitalWrite(in11, LOW);
        digitalWrite(in21, LOW);
        digitalWrite(in31, LOW);
        digitalWrite(in41, LOW);
        digitalWrite(in12, LOW);
        digitalWrite(in22, LOW);
        digitalWrite(in32, LOW);
        digitalWrite(in42, LOW);

    }

    // save position into the array
  }
  //if (m == 14) {
   // runSteps();
    //if (dataIn != 14) {
      //stopMoving();
      // Clear the array data to 0
   // }
  //}

}

//method to read the array from what was saved by the save button and run it step by step
//void runSteps() {}

void moveForward() {
        digitalWrite(in11, HIGH);
        digitalWrite(in21, LOW);
        digitalWrite(in31, HIGH);
        digitalWrite(in41, LOW);
        digitalWrite(in12, HIGH);
        digitalWrite(in22, LOW);
        digitalWrite(in32, HIGH);
        digitalWrite(in42, LOW);
        Serial.println("Motor: move Forward");
}

void moveBackward() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, HIGH);
        digitalWrite(in31, LOW);
        digitalWrite(in41, HIGH);
        digitalWrite(in12, LOW);
        digitalWrite(in22, HIGH);
        digitalWrite(in32, LOW);
        digitalWrite(in42, HIGH);
        Serial.println("Motor: move Backward");
}

void moveSidewaysLeft() {
        digitalWrite(in11, HIGH);
        digitalWrite(in21, LOW);
        digitalWrite(in31, LOW);
        digitalWrite(in41, HIGH);
        digitalWrite(in12, LOW);
        digitalWrite(in22, HIGH);
        digitalWrite(in32, HIGH);
        digitalWrite(in42, LOW);
        Serial.println("Motor: move Sideways Left");
}
void moveSidewaysRight() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, HIGH);
        digitalWrite(in31, HIGH);
        digitalWrite(in41, LOW);
        digitalWrite(in12, HIGH);
        digitalWrite(in22, LOW);
        digitalWrite(in32, LOW);
        digitalWrite(in42, HIGH);
        Serial.println("Motor: move Sideways right");
}

void moveRightForward() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, LOW);
        digitalWrite(in31, HIGH);
        digitalWrite(in41, LOW);
        digitalWrite(in12, HIGH);
        digitalWrite(in22, LOW);
        digitalWrite(in32, LOW);
        digitalWrite(in42, LOW);
        Serial.println("Motor: move Right Forward");
}

void moveLeftBackward() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, LOW);
        digitalWrite(in31, LOW);
        digitalWrite(in41, HIGH);
        digitalWrite(in12, LOW);
        digitalWrite(in22, HIGH);
        digitalWrite(in32, LOW);
        digitalWrite(in42, LOW);
        Serial.println("Motor: move left Back ward");
}

void moveLeftForward() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, LOW);
        digitalWrite(in31, LOW);
        digitalWrite(in41, HIGH);
        digitalWrite(in12, LOW);
        digitalWrite(in22, HIGH);
        digitalWrite(in32, LOW);
        digitalWrite(in42, LOW);
        Serial.println("Motor: move Left Forward");
}

void moveRightBackward() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, HIGH);
        digitalWrite(in31, LOW);
        digitalWrite(in41, LOW);
        digitalWrite(in12, LOW);
        digitalWrite(in22, LOW);
        digitalWrite(in32, LOW);
        digitalWrite(in42, HIGH);
        Serial.println("Motor: move Right Backward");
}

void rotateLeft() {
        digitalWrite(in11, HIGH);
        digitalWrite(in21, LOW);
        digitalWrite(in31, LOW);
        digitalWrite(in41, HIGH);
        digitalWrite(in12, HIGH);
        digitalWrite(in22, LOW);
        digitalWrite(in32, LOW);
        digitalWrite(in42, HIGH);
        Serial.println("Motor: rotate Left");
  }

void rotateRight() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, HIGH);
        digitalWrite(in31, HIGH);
        digitalWrite(in41, LOW);
        digitalWrite(in12, LOW);
        digitalWrite(in22, HIGH);
        digitalWrite(in32, HIGH);
        digitalWrite(in42, LOW);
        Serial.println("Motor: rotate Right");
  }

void stopMoving() {
        digitalWrite(in11, LOW);
        digitalWrite(in21, LOW);
        digitalWrite(in31, LOW);
        digitalWrite(in41, LOW);
        digitalWrite(in12, LOW);
        digitalWrite(in22, LOW);
        digitalWrite(in32, LOW);
        digitalWrite(in42, LOW);
        Serial.println("Motor: off");
  }

A DC motor does not know steps, unless you introduce them by using something like a rotary encoder

Could it be, that you mean the current state (i.e. the contents of the variables inXX and enXX of the DC motors instead of the "position"?  I guess so because you said, you want to reset the position to zero on a save event, and what you do then is setting the inXX all to LOW. That would be easy to achieve. But saving the current position of the wheels is not that easy. Then you do define what position means. Do your wheels turn constantly, like car wheels, or are they more like servos and have a well defined position within 360°? (I guess they are like car wheels when I see the prog.)

This is the type DC motor am using:
https://www.amazon.com/Electric-Magnetic-Gearbox-Plastic-Yeeco/dp/B07DQGX369/ref=sr_1_fkmr0_1?keywords=OLatus+DC+BO+Motor+Dual+shaft+Smart+Car+Robot+Gear+Motor+for+Arduino+%282+Pieces%29&qid=1573914307&sr=8-1-fkmr0
What I mean by positions are that  if I press the buttons to make car move forward ,side way left then backward --> all these I want it to be save in the array so when I press the run button it will redo all these position manually by looping in the array.
I hope you understood me

that does not explain what positions means ... you basically repeated what you already said in your post

As I understood it from your comments, your aim is not really to store the actual positions of the wheels or your robot, but to save and repeat the actions, that the robot did. (Meaning you don't have a "position" here, but only a measurement of wheel speed)
If that is true, then you can save this in a 2-dimensional array with the element form {speed_wheel_1, speed_wheel2, duration}. So each action is defined by the speeds of both wheels and the duration of the action, for example:
Driving forward at full speed for 3s, turn on the spot to the left with half speed for 1.5s, drive a curve with motor left full speed and motor right half speed for 5s

This would translate to the following elements:
{100, 100, 3000}
{-50, 50, 1500}
{100, 50, 5000}

The speeds have to be read in percent here and the durations in milliseconds.

Obviously you are controlling the robot over serial. I don't completely understand your code (also as you didn't show us the full code), so I will give some hints, how you can go on from here:
You are obtaining the speeds from serial into the variable wheelSpeed. We cannot see, how you are using this variable later, but you can use it in some way to set the speed fields of a new array element.
Then you need the duration. The Arduino framework has a function for that: millis(). It will return the number of milliseconds since the startup, much like a clock. When an action starts (when the corresponding serial command is received), you have to set a timestamp:
unsigned long timestamp;
...
timestamp = millis();

When the action ends (either because it actually only had a limited duration, or because another command is received), you calculate the difference between the current millis value and the timestamp. This is the duration.
So the corresponding code parts will look like this:
unsigned long timestamp = 0; // Define timestamp at global scope
unsigned int current_element = 0; // A variable to keep track of the current array element
int actions[10][3]; // Array to hold up to 10 actions

void start_action(byte speed_left, byte speed_right){
    actions[current_element][0] = speed_left;
    actions[current_element][1] = speed_right;
    timestamp = millis();
    // Start the action with the provided speeds here
}

void end_action(unsigned int element_index){
    actions[current_element][2] = millis() - timestamp;
    current_element++;
    if(current_element >= 10){
        // Do something to prevent more actions. Maybe just disable recording.
}

For repeating the actions, you just have to cycle over the array and set the corresponding speeds for the corresponding time.
If you want to go fancy, you can ditch the 2-dimensional array and instead define a struct for an action:
struct Action{
    int speed_left;
    int speed_right;
    unsigned long duration;
};

Then you can create a simple array of the Action objects and reference the fields by name:
Action actions[10];
...
actions[1].duration = millis() - timestamp;

thank you so much
I've updated my question + the code.
but I  have another problem if you can help me with which is: when my phone send data(any number 1-14) via Bluetooth it doesn't show the output on the wheels!!
example: when I pressed button move forward which send number 2 to the Bluetooth module, the wheels doesn't move.

I don't know what exactly you are sending, but I guess you are sending an ASCII "2" over bluetooth. In your code you only check for the decimal values of the read data. An ASCII-encoded "2" equals a decimal 50. Now you can either change the sending code to send raw decimal values instead of ASCII-encoded data, or you an change the receiving code to react to ASCII encoded data. The last can be done by changing the numbers in the if statements to the appropriate numbers of the ASCII characters. Or just simply writing them as characters: if(dataIn == '2')


text:
Protect the Arduino make with Unique Id
I’d like to protect my arduino make with a unique serial number for every device I make.
What are the proper ways to do it? Probably there are kind of best practices…
Keep it in EEPROM is obviously a bad idea.
I believe that there is some chip that can be added to the circuitry.
The general idea is the following.
Circuitry has a hardware which gives a unique id (serial number). Distributor/seller generates the signature using unique id and put it to the eeprom. Arduino program verifies this signature using hardware serial number. Arduino program is distributed in binary or within the device.

Why is EEPROM a bad idea for this?

Because it can be rewritten easily.

And even with an extra chip, the sketch on the Arduino needs to send read and send the ID of the device. One could easily change the sketch to not send the ID from the extra chip, but a custom one. Unless you connect the extra chip directly to the external device or you use encryption, it is still possible to change. What are you trying here? Is it a safety measure, so that no one temperes with your device? Or do you just want to prevent to accidentially override it?

@chrisl, I distribute hex only, no sources. Since that nobody can alter the sketch. I am trying to protect my hex from easy copying.

"Since that nobody can alter the sketch." This is plain wrong. It is no problem to decompile hex dumps of several KB, especially if you know the hardware. I've done that multiple times.

@thebusybee, so, what do you suggest?

It depends on why and against what you want protection.

@thebusybee If you can read assembler code, you are elite, I believe. But simple farmer can’t. Disassembling requires special intelligence.  However, a humble farmer is able to install Arduino IDE and follow some simple instructions. But he won’t ever disassemble the hex, alter it and compile it again.

@thebusybee I want to have a reasonable protection of my makes from copying without purchasing.

Then your external chip has to contain a cypher algorithm that will be feeded by an identifier from your sketch. That chip has to be serialized so that different chips will return different results on the same identifier. The chip must have protection against reading it. -- Only the correct identifier will produce some values that are urgently needed to run the sketch. This could be some machine code parts of a kernal. Without this values it wont run.

But beware! Don't just return a boolean saying "OK/Error". It far too simple to patch that single instruction to disable the protection scheme. Such a patch will spread much faster than you can call "Stop!" -- And you have to think about what to do if some curious guy reveals the secret contents and publishes it. This already happened, I watched it, and will happen again.

Let us continue this discussion in chat.

I still suggest using the eeprom.
It is the firmware's job to handle whether or not data in eeprom can be written.
You could implement wrapper functions for the arduino which can only read/write after a defined offset. You can set this read-only data with the .eep-file when you upload your sketch. The eeprom file then may be generated programmatically.
Once you have to flash several individual devices with a final firmware version, there are no benefits in using the arduino ide. You can upload the firmware and the eeprom file using avrdude:
avrdude -P YOUR_PORT -b 115200 -p ATmega328P -e -U flash:w:YOUR_FIRMWARE.hex -U eeprom:w:YOUR_EEPROM.eep

It's up to you how to generate the eeprom file (bash/batch, make, pyhton,...).

Sounds interesting! Can you add an example how to use it?

I don't get it. Anybody can upload eeprom file from another arduino. I want to protect my devices from copying.

@zhekaus doesn't the upload work? You have to run the command from the build directory. You may have to select a programmer, but I think avrdude would force you. The simplest to get an eeprom file to start with might be to initialize the eeprom with temporary firmware which stores the desired values and then read-back the .eep-file using the above command with eeprom:r:initial.eep.

@zhekaus also, what do you mean by "protect my devices from copying"? An attacker would be able to read or write any unencrypted data the same way you do anyway.

nobody asks how to upload eeprom. Let's stick to the initial question, please ))

attacker does not know how to verify this unencrypted data. Official distributor does. PS. How to @ your nickname, Sim Son?

@zhekaus select an respond to comment for the '@' or type it manually (no spaces)

Sim Sin, of course, I know it. But stackexchange does not allow this with your two-word nickname ))

My general idea is: Circuitry has a hardware which gives unique id (serial number). Distributor/seller generates the signature using unique id. Arduino program verifies this signature using hardware serial number. Signature is stored in eeprom. Arduino program is distributed like binary.

Hmm, I can't read that in your question, but now I got it due to the comments. "Hidden in data" is not the same as "encrypted" and therefore storing such information at dedicated addresses in flash means no security. You can encrypt the information beforehand, but if it's encrypted you can use the eeprom.

I don’t understand your proposal. Anybody can copy hex and eeprom from one Arduino to another. Where is the protection here? It does not mattet whether it's encrypted or not.
However, nobody can copy DS2401.

Anyone who hooks up some wires can read the ds2401.

Maybe he can read. But can he forge? Allrighty, anyway, when we talk about the protection, we always keep in mind the cost of breaching it. Certainly, nobody believes in absolutely robust security. The question is in the cost of breeching. Yeah, probably DS2401 is not a good idea, but at least, it already looks like much better than simple keeping unique id in eeprom, since anybody can copy it with avrdude.

Then hacker will do it the same way old DOS games was cracked - dowload and debug the hex - overwrite the function reading DS2401 to not read it and return correct value insted, then distribute the modified hex. Anybody can download it, burn it and whether they have or not the DS2401, the function will return correct result and the Arduino will work the same way, the original one worked. Needs one "elite hacker" and internet copy to work on as many Arduinos as its users wants. That said, I do not think that this approach is working nor the best possible one.

I found a way! I can use DS2401 or DS2411.
These devices are 64-bit read only memory (ROM) "silicon serial number" devices which are programmed by the manufacturer with a unique 48 bit serial number, an 8 bit product family code, and an 8 bit CRC.

it can be removed, replaced

If it's removed, device won't work. Also, I suppose to keep a signature in eeprom which will be verified with unique id. If it’s not verified, device won’t work.

@zhekaus (See my comment at your question,too.) Since your sketch can be decompiled it is no problem to work around any protection you implemented.

@thebusybee You are right. But it requires extra skills, much more advances than avrdude using. My makes are not rocket science. I simply want to have a reasonable protection, nothing fancy or extremely robust.


text:
Can i combine an ultrasonic sensor and gps together?
I need to operate 2 different sensors by Arduino UNO: GPS module and Ultrasonic sensor. I have managed to run each one of them separately and I don't know how to manipulate the code;
GPS MODULE
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

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

void loop()
{
  // This sketch displays information
  // every time a new sentence is correctly encoded.
  while (ss.available() > 0)
  {
    gps.encode(ss.read());
    if (gps.location.isUpdated())
    {
      Serial.print("Latitude= ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(" Longitude= ");
      Serial.println(gps.location.lng(), 6);
    }
  }
}

ULTRASONIC SENSOR
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;
void setup()
{
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void loop()
{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;

  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

That's easy. I have no possibility to try it. But if your code has been working, this will also. (Just copy/paste.) I had to change the while loop into a if block, because I was not sure, if the while blocks for a longer time. It could have been that the GPS sends and sends and sends ... That would block the ultrasonic sensor.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

const int trigPin = 9;
const int echoPin = 10;

long duration;
int distance;

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

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  // This sketch displays information
  // every time a new sentence is correctly encoded.
  if (ss.available() > 0)
  {
    gps.encode(ss.read());
    if (gps.location.isUpdated())
    {
      Serial.print("Latitude= ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(" Longitude= ");
      Serial.println(gps.location.lng(), 6);
    }
  }

  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;

  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

Thank you for your respond and help sir. But i do have some problems in the output. The gps coordinate does not show

@AfiqAzmii I'd showed you how to combine the two sketches. That's what you have been asking for. I can't tell you, why this doesn't work, because I don't know anything about the setup. I can not see any pictures of your project and the wiring and I have no link to the documentation of both sensors.  I even don't know which one you use. You did also not tell me, if the distance sensor works correctly.  As this is a complete new question, it would be better to add a new question or update the old one. If you add all the information I asked for, someone or me have a better chance to help you.

A I've seen you had already asked a new question. I'look into it.